import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import {
  Search, ChevronRight, Shield, Zap, Clock, Truck, Phone,
  CheckCircle2, Users, DollarSign, MessageSquare, Wrench,
  ArrowRight, Settings, Lightbulb, Square, CircleDot
} from "lucide-react";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;
const HERO_BG = "https://images.unsplash.com/photo-1652453822989-b1d345a866d8?w=1800&q=70";

const CATEGORIES = [
  { name: "Engines & Transmissions", icon: Settings, slug: "Engine" },
  { name: "Headlights & Taillights", icon: Lightbulb, slug: "Lighting" },
  { name: "Bumpers & Body Parts", icon: Square, slug: "Body" },
  { name: "Mirrors & Glass", icon: CircleDot, slug: "Mirrors" },
  { name: "Wheels & Suspension", icon: CircleDot, slug: "Suspension" },
  { name: "Interior & Electronics", icon: Wrench, slug: "Interior" },
];

const MAKES = [
  { name: "Mercedes-Benz", short: "MB" },
  { name: "BMW", short: "BMW" },
  { name: "Ford", short: "FD" },
  { name: "Chevrolet", short: "CH" },
  { name: "Toyota", short: "TY" },
  { name: "Nissan", short: "NS" },
];

export default function Home() {
  const navigate = useNavigate();
  const [vin, setVin] = useState("");
  const [vinLoading, setVinLoading] = useState(false);
  const [inventory, setInventory] = useState([]);

  useEffect(() => {
    axios.get(`${API}/inventory`).then(r => setInventory(r.data?.slice(0, 8) || [])).catch(() => {});
  }, []);

  const handleVinSearch = async (e) => {
    e.preventDefault();
    if (!vin || vin.length < 11) { toast.error("Enter a valid VIN"); return; }
    setVinLoading(true);
    try {
      const { data } = await axios.get(`${API}/vin-decode/${vin}`);
      navigate(`/inventory?vin=${vin}&year=${data.year || ""}&make=${data.make || ""}&model=${data.model || ""}`);
    } catch { toast.error("VIN decode failed"); }
    setVinLoading(false);
  };

  return (
    <div data-testid="home-page" className="bg-[#0B0B0B]">

      {/* ========== 1. HERO ========== */}
      <section className="relative min-h-[92vh] flex items-center justify-center overflow-hidden">
        <div className="absolute inset-0">
          <img src={HERO_BG} alt="" className="w-full h-full object-cover opacity-30" style={{ filter: "blur(1px)" }} />
          <div className="absolute inset-0 bg-gradient-to-b from-[#0B0B0B]/60 via-[#0B0B0B]/80 to-[#0B0B0B]" />
        </div>

        <div className="relative z-10 w-full max-w-3xl mx-auto px-4 text-center pt-16">
          {/* Trust badge */}
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-[#3B82F6]/8 border border-[#3B82F6]/20 rounded-sm mb-8 animate-fade-in-up">
            <CheckCircle2 className="h-3.5 w-3.5 text-[#3B82F6]" />
            <span className="text-[12px] font-semibold text-[#3B82F6] uppercase tracking-wider">VIN-Verified Fitment</span>
          </div>

          <h1 data-testid="hero-headline" className="text-4xl sm:text-5xl lg:text-[56px] font-extrabold tracking-[-0.04em] text-white leading-[1.08] mb-6 animate-fade-in-up delay-100">
            VIN-Verified OEM Auto Parts.<br />Delivered Fast.
          </h1>

          <p className="text-[16px] sm:text-[18px] text-[#A0A0A0] leading-relaxed mb-10 max-w-2xl mx-auto animate-fade-in-up delay-200">
            Find the exact part for your vehicle in minutes. No guesswork. No wrong orders. Just verified fitment and fast nationwide shipping.
          </p>

          {/* VIN Search */}
          <form onSubmit={handleVinSearch} data-testid="hero-vin-form" className="animate-fade-in-up delay-300">
            <div className="flex flex-col sm:flex-row gap-3 max-w-xl mx-auto">
              <div className="relative flex-1">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-[#555]" />
                <input
                  data-testid="hero-vin-input"
                  type="text"
                  value={vin}
                  onChange={e => setVin(e.target.value.toUpperCase())}
                  maxLength={17}
                  placeholder="Enter your 17-digit VIN"
                  className="w-full h-14 pl-12 pr-4 bg-[#161616] border border-[#2A2A2A] rounded text-[15px] text-white placeholder:text-[#555] focus:outline-none focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]/30 transition-all font-mono tracking-wide"
                />
              </div>
              <button
                data-testid="hero-vin-submit"
                type="submit"
                disabled={vinLoading}
                className="h-14 px-8 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[14px] font-bold uppercase tracking-wider rounded transition-colors flex-shrink-0 flex items-center justify-center gap-2"
              >
                {vinLoading ? (
                  <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                ) : (
                  <>Search by VIN</>
                )}
              </button>
            </div>
          </form>

          <div className="mt-5 animate-fade-in-up delay-400">
            <Link to="/inventory" className="text-[13px] text-[#888] hover:text-[#3B82F6] transition-colors font-medium">
              Browse Inventory <ChevronRight className="h-3.5 w-3.5 inline" />
            </Link>
          </div>
        </div>
      </section>

      {/* ========== 2. TRUST BAR ========== */}
      <section className="bg-[#111111] border-y border-[#1E1E1E]">
        <div className="max-w-[1200px] mx-auto px-4">
          <div className="grid grid-cols-2 lg:grid-cols-4 divide-x divide-[#1E1E1E]">
            {[
              { icon: Shield, label: "VIN-Verified Fitment" },
              { icon: Clock, label: "24-48 Hour Quotes" },
              { icon: Truck, label: "Nationwide Shipping" },
              { icon: DollarSign, label: "Up to 70% Below Retail" },
            ].map(t => (
              <div key={t.label} className="flex items-center justify-center gap-3 py-5">
                <t.icon className="h-[18px] w-[18px] text-[#3B82F6] flex-shrink-0" />
                <span className="text-[13px] font-semibold text-white/80">{t.label}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ========== 3. FEATURED INVENTORY ========== */}
      {inventory.length > 0 && (
        <section className="max-w-[1200px] mx-auto px-4 py-20">
          <div className="flex items-end justify-between mb-8">
            <div>
              <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white">Recently Added Inventory</h2>
              <p className="text-[14px] text-[#888] mt-1.5">Real parts. In stock. Ready to ship.</p>
            </div>
            <Link to="/inventory" className="hidden sm:flex items-center gap-1 text-[13px] font-semibold text-[#3B82F6] hover:text-[#60A5FA] transition-colors">
              View All <ArrowRight className="h-4 w-4" />
            </Link>
          </div>

          <div data-testid="parts-grid" className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {inventory.map(item => (
              <div
                key={item.id}
                data-testid={`part-card-${item.id}`}
                className="bg-[#161616] border border-[#222] rounded overflow-hidden hover:border-[#3B82F6]/30 transition-all duration-300 group"
              >
                <div className="h-48 bg-[#111] flex items-center justify-center overflow-hidden relative">
                  {item.image_url ? (
                    <img src={item.image_url} alt={item.name} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" loading="lazy" />
                  ) : (
                    <div className="text-[#222]">
                      <Wrench className="h-10 w-10" />
                    </div>
                  )}
                  {/* Condition badge */}
                  <div className="absolute top-3 left-3">
                    <span className={`px-2 py-1 text-[10px] font-bold uppercase tracking-wider rounded-sm backdrop-blur-sm ${
                      item.condition === "New" ? "bg-[#22C55E]/20 text-[#22C55E] border border-[#22C55E]/30" :
                      item.condition === "OEM" ? "bg-[#3B82F6]/20 text-[#3B82F6] border border-[#3B82F6]/30" :
                      "bg-white/10 text-white/70 border border-white/20"
                    }`}>
                      {item.condition}
                    </span>
                  </div>
                  {/* In stock badge */}
                  <div className="absolute top-3 right-3">
                    <span className="px-2 py-1 text-[9px] font-bold uppercase tracking-wider bg-[#22C55E]/15 text-[#22C55E] border border-[#22C55E]/20 rounded-sm backdrop-blur-sm">
                      In Stock
                    </span>
                  </div>
                </div>

                <div className="p-4">
                  <p className="text-[11px] text-[#666] uppercase tracking-wide mb-1">{item.category}</p>
                  <h3 className="text-[14px] font-semibold text-white mb-1 line-clamp-1 group-hover:text-[#3B82F6] transition-colors">{item.name}</h3>
                  <p className="text-[12px] text-[#888] mb-4">Fits: {item.vehicle_year} {item.make} {item.model}</p>
                  <div className="flex items-end justify-between">
                    <div>
                      <p className="text-[20px] font-bold text-white leading-none">${item.price}</p>
                      {item.retail_price && (
                        <p className="text-[11px] text-[#666] mt-0.5"><span className="line-through">${item.retail_price}</span> <span className="text-[#22C55E]">Save {Math.round((1 - item.price / item.retail_price) * 100)}%</span></p>
                      )}
                    </div>
                    <Link
                      to={`/find-part?part=${encodeURIComponent(item.name)}&year=${item.vehicle_year || ""}&make=${item.make || ""}&model=${item.model || ""}`}
                      className="h-8 px-3 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[11px] font-semibold uppercase tracking-wide rounded-sm flex items-center transition-colors"
                    >
                      Get Quote
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div className="sm:hidden mt-6 text-center">
            <Link to="/inventory" className="text-[13px] font-semibold text-[#3B82F6]">View All Inventory <ArrowRight className="h-3.5 w-3.5 inline" /></Link>
          </div>
        </section>
      )}

      {/* ========== 4. SHOP BY CATEGORY ========== */}
      <section className="bg-[#0F0F0F] border-y border-[#1A1A1A]">
        <div className="max-w-[1200px] mx-auto px-4 py-20">
          <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white mb-2 text-center">Shop by Category</h2>
          <p className="text-[14px] text-[#888] text-center mb-10">Find exactly what you need.</p>

          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
            {CATEGORIES.map(cat => (
              <Link
                key={cat.name}
                to={`/inventory?q=${encodeURIComponent(cat.slug)}`}
                data-testid={`cat-${cat.slug.toLowerCase()}`}
                className="bg-[#161616] border border-[#222] rounded p-6 hover:border-[#3B82F6]/40 transition-all duration-300 group text-center"
              >
                <cat.icon className="h-6 w-6 text-[#555] group-hover:text-[#3B82F6] mx-auto mb-3 transition-colors" />
                <p className="text-[14px] font-semibold text-white group-hover:text-[#3B82F6] transition-colors">{cat.name}</p>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* ========== 5. SHOP BY MAKE ========== */}
      <section className="max-w-[1200px] mx-auto px-4 py-20">
        <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white mb-2 text-center">Shop by Make</h2>
        <p className="text-[14px] text-[#888] text-center mb-10">OEM parts for every major manufacturer.</p>

        <div className="grid grid-cols-3 md:grid-cols-6 gap-3">
          {MAKES.map(make => (
            <Link
              key={make.name}
              to={`/inventory?make=${encodeURIComponent(make.name)}`}
              data-testid={`make-${make.short.toLowerCase()}`}
              className="bg-[#161616] border border-[#222] rounded p-5 hover:border-[#3B82F6]/40 transition-all duration-300 group text-center"
            >
              <p className="text-[22px] font-bold text-[#444] group-hover:text-[#3B82F6] transition-colors mb-1 tracking-tight">{make.short}</p>
              <p className="text-[11px] text-[#888] group-hover:text-white transition-colors">{make.name}</p>
            </Link>
          ))}
        </div>
      </section>

      {/* ========== 6. HOW IT WORKS ========== */}
      <section className="bg-[#0F0F0F] border-y border-[#1A1A1A]">
        <div className="max-w-[1200px] mx-auto px-4 py-20">
          <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white text-center mb-10">How It Works</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {[
              { step: "01", title: "Enter Your VIN", desc: "Paste your Vehicle Identification Number. We decode it instantly and identify your exact vehicle specs." },
              { step: "02", title: "We Match Your Part", desc: "Our sourcing team finds the exact OEM or quality recycled part from our nationwide supplier network. Quote in 24-48hrs." },
              { step: "03", title: "Receive & Install", desc: "Pay securely online. We ship direct to you with full tracking. Install with confidence knowing the part is verified." },
            ].map(s => (
              <div key={s.step} className="relative p-6 bg-[#161616] border border-[#222] rounded">
                <p className="text-[40px] font-extrabold text-[#3B82F6]/15 leading-none mb-4 tracking-tighter">{s.step}</p>
                <h3 className="text-[16px] font-bold text-white mb-2">{s.title}</h3>
                <p className="text-[13px] text-[#888] leading-relaxed">{s.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ========== 7. WHY CHOOSE US ========== */}
      <section className="max-w-[1200px] mx-auto px-4 py-20">
        <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white text-center mb-2">Why Queen City Auto Parts</h2>
        <p className="text-[14px] text-[#888] text-center mb-10">Built for people who know cars.</p>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
          {[
            { icon: Shield, title: "VIN-Verified Accuracy", desc: "Every part matched to your vehicle's exact specs." },
            { icon: Wrench, title: "OEM & Quality Recycled", desc: "Genuine OEM or tested recycled parts only." },
            { icon: Users, title: "Real Human Sourcing", desc: "Expert team, not an algorithm." },
            { icon: DollarSign, title: "Transparent Pricing", desc: "No hidden fees. Price includes sourcing." },
            { icon: Phone, title: "Direct Support", desc: "Call or text us anytime." },
          ].map(w => (
            <div key={w.title} className="p-5 bg-[#161616] border border-[#222] rounded text-center">
              <w.icon className="h-5 w-5 text-[#3B82F6] mx-auto mb-3" />
              <h3 className="text-[13px] font-bold text-white mb-1">{w.title}</h3>
              <p className="text-[12px] text-[#888] leading-relaxed">{w.desc}</p>
            </div>
          ))}
        </div>
      </section>

      {/* ========== 8. REQUEST PART CTA ========== */}
      <section className="bg-[#0F0F0F] border-y border-[#1A1A1A]">
        <div className="max-w-[800px] mx-auto px-4 py-16 text-center">
          <h2 className="text-[28px] font-bold tracking-[-0.03em] text-white mb-3">Can't Find Your Part?</h2>
          <p className="text-[15px] text-[#888] mb-8 max-w-lg mx-auto">
            Tell us what you need. Our sourcing team will find it, price it, and get it to you fast.
          </p>
          <div className="flex items-center justify-center gap-4 flex-wrap">
            <Link
              to="/find-part"
              data-testid="cta-request-btn"
              className="h-12 px-8 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[14px] font-bold uppercase tracking-wider rounded flex items-center transition-colors"
            >
              Request a Part <ArrowRight className="ml-2 h-4 w-4" />
            </Link>
            <a
              href="tel:+17049003512"
              className="h-12 px-6 bg-transparent border border-[#2A2A2A] hover:border-[#3B82F6] text-white text-[14px] font-medium rounded flex items-center gap-2 transition-colors"
            >
              <Phone className="h-4 w-4 text-[#3B82F6]" /> (704) 900-3512
            </a>
          </div>
        </div>
      </section>

      {/* ========== 9. FINAL CTA ========== */}
      <section className="max-w-[1200px] mx-auto px-4 py-20 text-center">
        <h2 className="text-[24px] sm:text-[32px] font-bold tracking-[-0.03em] text-white mb-4">
          Stop Guessing. Start Ordering the Right Part.
        </h2>
        <p className="text-[14px] text-[#888] mb-8 max-w-md mx-auto">
          Enter your VIN and get matched with verified parts in minutes.
        </p>
        <Link
          to="/find-part"
          className="inline-flex h-12 px-10 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[14px] font-bold uppercase tracking-wider rounded items-center transition-colors"
        >
          Get Started
        </Link>
      </section>
    </div>
  );
}
