// ===== Sections =====
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Announcement ----------
const AnnounceBar = () => (
  <div className="announce">
    <div className="shell announce-inner">
      <div className="announce-msg">
        <span className="announce-dot"></span>
        Free same-day delivery in Algiers on orders over 50 000 DA
      </div>
      <div className="announce-links">
        <a href="track.html">Track Order</a>
        <a href="info.html?topic=support">Support</a>
        <span style={{ opacity: 0.85, cursor: "default" }}>FR / EN / AR</span>
      </div>
    </div>
  </div>
);

// ---------- Header ----------
const Header = ({ cartCount, onCartOpen, query, setQuery }) => (
  <header className="header">
    <div className="shell header-row">
      <a className="logo" href="index.html">
        <span className="logo-mark logo-placeholder">
          <span className="ph-mark">LOGO</span>
        </span>
        <span className="logo-name logo-name-placeholder">Your Brand</span>
      </a>

      <div className="search">
        <div className="search-cat">
          All Categories
          <Icon name="chev" style={{ width: 14, height: 14 }} />
        </div>
        <input
          placeholder="Search RTX 5080, Ryzen 9, OLED monitor..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        <button className="search-btn"><Icon name="search" /></button>
      </div>

      <div className="header-actions">
        <a className="icon-btn" href="tel:+213560110230">
          <Icon name="phone" style={{ color: "var(--purple-bright)" }} />
          <div className="icon-btn-meta">
            <span className="lbl">Call</span>
            <span className="val">0560 11 02 30</span>
          </div>
        </a>
        <a className="icon-btn" href="info.html?topic=contact" aria-label="Account">
          <Icon name="user" />
        </a>
        <a className="icon-btn" href="info.html?topic=faq" aria-label="Wishlist">
          <Icon name="heart" />
        </a>
        <button className="icon-btn" onClick={onCartOpen}>
          <Icon name="cart" />
          {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
          <div className="icon-btn-meta">
            <span className="lbl">Cart</span>
            <span className="val">{cartCount} item{cartCount === 1 ? "" : "s"}</span>
          </div>
        </button>
      </div>
    </div>
  </header>
);

// ---------- Mega Nav ----------
const MegaNav = () => {
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("click", onDoc);
    return () => document.removeEventListener("click", onDoc);
  }, []);
  return (
    <div className="meganav">
      <div className="shell meganav-row">
        <div ref={ref} style={{ height: "100%", position: "relative" }}>
          <button
            className={`cat-trigger ${open ? "open" : ""}`}
            onClick={(e) => { e.stopPropagation(); setOpen(!open); }}
          >
            <Icon name="grid" />
            All Categories
            <Icon name="chev" className="chev" />
          </button>
          {open && (
            <div className="cat-panel" onClick={(e) => e.stopPropagation()}>
              {CATEGORIES.map(c => (
                <a className="cat-item" key={c.id} href={`shop.html?cat=${c.id}`}>
                  <Icon name={c.icon} />
                  <span>{c.label}</span>
                  <Icon name="chevR" className="arrow" />
                </a>
              ))}
            </div>
          )}
        </div>

        <nav className="nav-links">
          {NAV_LINKS.map((l, i) => {
            const hrefs = ["shop.html", "shop.html?cat=case", "shop.html?cat=gpu", "shop.html?cat=kb", "shop.html?cat=mon", "shop.html", "#"];
            return (
              <a key={i} className="nav-link" href={hrefs[i] || "#"}>
                {l.label}
                {l.hot && <span className="hot">{l.hot}</span>}
              </a>
            );
          })}
        </nav>

        <div className="nav-meta">
          <span className="nav-meta-item">
            <Icon name="truck" /> Free delivery 50K+
          </span>
          <span className="nav-meta-item">
            <Icon name="shield" /> 2-year warranty
          </span>
        </div>
      </div>
    </div>
  );
};

// ---------- Hero ----------
const HERO_SLIDES = [
  {
    tag: "RTX 50 SERIES IS HERE",
    title: ["Built for the new era of ", "ray-traced", " worlds."],
    sub: "Drop the latest Blackwell GPUs into a chassis tuned by engineers. Free delivery, full warranty.",
    specs: [
      { k: "GPU Boost", v: "+38%" },
      { k: "AI cores", v: "TENSOR Gen-5" },
      { k: "Latency", v: "<6 ms" },
    ],
    img: "https://images.unsplash.com/photo-1591488320449-011701bb6704?w=900&q=80&auto=format",
    primary: { label: "Shop GPUs", href: "shop.html?cat=gpu" },
    ghost: { label: "Browse all", href: "shop.html" },
  },
  {
    tag: "STREAMER PRESET",
    title: ["Stream, encode, win — ", "all at once", "."],
    sub: "Dual-PC presets, hardware encoders, calibrated audio chains. Pre-built and ready in 24 hours.",
    specs: [
      { k: "Encode", v: "AV1 / HEVC" },
      { k: "Audio", v: "32-bit ADC" },
      { k: "Ready", v: "<24 h" },
    ],
    img: "https://images.unsplash.com/photo-1587202372634-32705e3bf49c?w=900&q=80&auto=format",
    primary: { label: "Shop Streamer rigs", href: "shop.html?cat=case" },
    ghost: { label: "Custom build", href: "info.html?topic=custom" },
  },
  {
    tag: "STUDENT DEAL",
    title: ["Esports-ready ", "starter rigs", " from 89K DA."],
    sub: "Entry tier, lasting hardware. Upgrade-friendly motherboards on every config.",
    specs: [
      { k: "1080p", v: "144 FPS" },
      { k: "From", v: "89 000 DA" },
      { k: "Pay over", v: "3 / 6 mo" },
    ],
    img: "https://images.unsplash.com/photo-1593640408182-31c70c8268f5?w=900&q=80&auto=format",
    primary: { label: "See starter rigs", href: "shop.html?cat=case" },
    ghost: { label: "Build your own", href: "info.html?topic=custom" },
  },
];

const Hero = () => {
  const [slide, setSlide] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setSlide(s => (s + 1) % HERO_SLIDES.length), 6500);
    return () => clearInterval(t);
  }, []);
  const s = HERO_SLIDES[slide];
  return (
    <section className="hero shell">
      <div className="hero-grid">
        <div className="hero-main">
          <div className="hero-content">
            <div className="hero-tag">
              <Icon name="sparkle" style={{ width: 12, height: 12 }} /> {s.tag}
            </div>
            <h1 className="hero-title">
              {s.title[0]}<em>{s.title[1]}</em>{s.title[2]}
            </h1>
            <p className="hero-sub">{s.sub}</p>
            <div className="hero-specs">
              {s.specs.map((sp, i) => (
                <div className="hero-spec" key={i}>
                  <div className="k">{sp.k}</div>
                  <div className="v">{sp.v}</div>
                </div>
              ))}
            </div>
            <div className="hero-cta">
              <a className="btn btn-primary" href={s.primary?.href || "shop.html"}>
                {s.primary?.label || "Shop now"} <Icon name="arrow" />
              </a>
              <a className="btn btn-ghost" href={s.ghost?.href || "#"}>
                <Icon name="cpu" /> {s.ghost?.label || "Build Your PC"}
              </a>
            </div>
            <div className="hero-dots">
              {HERO_SLIDES.map((_, i) => (
                <button key={i} className={`hero-dot ${i === slide ? "active" : ""}`} onClick={() => setSlide(i)} />
              ))}
            </div>
          </div>
          <div className="hero-visual">
            {HERO_SLIDES.map((slideData, i) => (
              <img
                key={i}
                src={slideData.img}
                alt={slideData.tag}
                className={`hero-img ${i === slide ? "active" : ""}`}
              />
            ))}
            <div className="hero-visual-bg"></div>
          </div>
        </div>

        <div className="hero-side">
          <a className="hero-card a" href="shop.html?cat=case">
            <div>
              <div className="eyebrow">Limited Drop</div>
              <h3>Lavender Mesh Series</h3>
              <p>Custom-painted chassis — only 80 units in Algeria.</p>
            </div>
            <div className="shop">Reserve yours <Icon name="arrow" style={{ width: 12, height: 12 }} /></div>
          </a>
          <a className="hero-card b" href="info.html?topic=tradein">
            <div>
              <div className="eyebrow">Trade-in Program</div>
              <h3>Up to 35K DA back</h3>
              <p>Bring your old rig, we credit it toward a new build.</p>
            </div>
            <div className="shop">See offer <Icon name="arrow" style={{ width: 12, height: 12 }} /></div>
          </a>
        </div>
      </div>
    </section>
  );
};

// ---------- Stats strip ----------
const Stats = () => (
  <div className="shell">
    <div className="stats">
      <div className="stat">
        <div className="stat-icon"><Icon name="truck" /></div>
        <div><div className="t">Same-day delivery</div><div className="s">Algiers, Oran, Constantine</div></div>
      </div>
      <div className="stat">
        <div className="stat-icon"><Icon name="shield" /></div>
        <div><div className="t">2-year warranty</div><div className="s">All components covered</div></div>
      </div>
      <div className="stat">
        <div className="stat-icon"><Icon name="refresh" /></div>
        <div><div className="t">14-day returns</div><div className="s">No questions asked</div></div>
      </div>
      <div className="stat">
        <div className="stat-icon"><Icon name="chat" /></div>
        <div><div className="t">Expert support</div><div className="s">9 AM – 9 PM, 7 days</div></div>
      </div>
    </div>
  </div>
);

// ---------- Category tiles ----------
const CategoryTiles = () => (
  <section className="section shell">
    <div className="section-head">
      <div className="section-title">
        <div className="eyebrow">Shop by category</div>
        <h2>Every part of the rig.</h2>
      </div>
      <div className="section-actions">
        <a className="tab-pill" href="shop.html">View all 12 →</a>
      </div>
    </div>
    <div className="cat-grid">
      {CATEGORIES.slice(0, 8).map(c => (
        <a className="cat-tile" key={c.id} href={`shop.html?cat=${c.id}`}>
          <img className="cat-tile-bg" src={c.img} alt={c.label} loading="lazy" />
          <div className="cat-tile-overlay"></div>
          <div className="cat-tile-text">
            <div className="label">{c.label}</div>
            <div className="count">{c.count} products</div>
          </div>
        </a>
      ))}
    </div>
  </section>
);

// ---------- Flash deals header ----------
const FlashCountdown = () => {
  const [t, setT] = useState({ h: 14, m: 32, s: 21 });
  useEffect(() => {
    const id = setInterval(() => {
      setT(prev => {
        let { h, m, s } = prev;
        s--; if (s < 0) { s = 59; m--; }
        if (m < 0) { m = 59; h--; }
        if (h < 0) { h = 23; }
        return { h, m, s };
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);
  const pad = (n) => String(n).padStart(2, "0");
  return (
    <div className="countdown">
      <div className="cd-cell"><div className="n">{pad(t.h)}</div><div className="l">hours</div></div>
      <span className="cd-sep">:</span>
      <div className="cd-cell"><div className="n">{pad(t.m)}</div><div className="l">min</div></div>
      <span className="cd-sep">:</span>
      <div className="cd-cell"><div className="n">{pad(t.s)}</div><div className="l">sec</div></div>
    </div>
  );
};

// ---------- Product Card ----------
const ProductCard = ({ p, onOpen, onAdd, faved, onFav }) => {
  const discount = p.was ? Math.round((1 - p.price / p.was) * 100) : 0;
  return (
    <div className="product-card">
      <a className="product-media" href={`product.html?id=${p.id}`}>
        <div className="product-badges">
          {p.badges.map((b, i) => {
            const cls = b.includes("%") ? "sale" : b === "NEW" ? "new" : "hot";
            return <span key={i} className={`badge ${cls}`}>{b}</span>;
          })}
        </div>
        <button className={`product-fav ${faved ? "active" : ""}`} onClick={(e) => { e.preventDefault(); e.stopPropagation(); onFav(p.id); }}>
          <Icon name="heart" />
        </button>
        {p.img ? (
          <img src={p.img} alt={p.name} className="product-img" loading="lazy" />
        ) : (
          <PHLabel>{p.cat.toLowerCase()}.render</PHLabel>
        )}
      </a>
      <div className="product-body">
        <div className="product-brand">{p.brand}</div>
        <a href={`product.html?id=${p.id}`} className="product-name-link">
          <h3 className="product-name">{p.name}</h3>
        </a>
        <div className="product-specs">
          {p.specs.map((s, i) => <span key={i} className="spec-chip">{s}</span>)}
        </div>
        <div className="product-rating">
          <Stars value={p.rating} />
          <span>{p.rating.toFixed(1)} · {p.reviews} reviews</span>
        </div>
        <div className="product-price-row">
          <div className="price-block">
            <div className="now">{money(p.price)}<span className="cur"> {p.currency}</span></div>
            {p.was && (
              <div>
                <span className="was">{money(p.was)}</span>
                <span className="save">save {discount}%</span>
              </div>
            )}
          </div>
          <button className="add-btn" onClick={() => onAdd(p)} aria-label="Add to cart">
            <Icon name="plus" />
          </button>
        </div>
      </div>
    </div>
  );
};

// ---------- Flash deals section ----------
const FlashDeals = ({ onOpen, onAdd, faves, onFav }) => {
  const deals = PRODUCTS.filter(p => p.was).slice(0, 4);
  return (
    <section className="section shell">
      <div className="flash">
        <div className="flash-title">
          <div className="flash-bolt"><Icon name="bolt" /></div>
          <div>
            <h3>Flash deals · ends tonight</h3>
            <p>Hand-picked drops. Hard cap on units, no rainchecks.</p>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "center" }}>
          <FlashCountdown />
        </div>
        <button className="btn btn-ghost" style={{ background: "rgba(255,255,255,0.05)" }} onClick={() => { location.href = 'shop.html'; }}>
          See all deals <Icon name="arrow" />
        </button>
      </div>
      <div className="product-grid">
        {deals.map(p => (
          <ProductCard
            key={p.id} p={p}
            onOpen={onOpen} onAdd={onAdd}
            faved={faves.has(p.id)} onFav={onFav}
          />
        ))}
      </div>
    </section>
  );
};

// ---------- Featured Products ----------
const Featured = ({ onOpen, onAdd, faves, onFav }) => {
  const [tab, setTab] = useState("all");
  const tabs = [
    { id: "all", label: "All Bestsellers" },
    { id: "GPU", label: "GPUs" },
    { id: "CPU", label: "CPUs" },
    { id: "MONITOR", label: "Monitors" },
    { id: "KEYBOARD", label: "Keyboards" },
  ];
  const list = tab === "all" ? PRODUCTS : PRODUCTS.filter(p => p.cat === tab);
  return (
    <section className="section shell">
      <div className="section-head">
        <div className="section-title">
          <div className="eyebrow">Most wanted</div>
          <h2>Bestsellers this week.</h2>
        </div>
        <div className="section-actions">
          {tabs.map(t => (
            <button key={t.id} className={`tab-pill ${tab === t.id ? "active" : ""}`} onClick={() => setTab(t.id)}>
              {t.label}
            </button>
          ))}
        </div>
      </div>

      <div className="filters-row">
        <div className="filters">
          <button className="filter-pill active"><Icon name="fire" /> Trending</button>
          <button className="filter-pill"><Icon name="sparkle" /> New arrivals</button>
          <button className="filter-pill"><Icon name="discount" /> On sale</button>
          <button className="filter-pill"><Icon name="crown" /> Editor's pick</button>
          <button className="filter-pill">In stock only</button>
        </div>
        <select className="sort-select">
          <option>Sort: Most popular</option>
          <option>Price: low to high</option>
          <option>Price: high to low</option>
          <option>Newest first</option>
          <option>Top rated</option>
        </select>
      </div>

      <div className="product-grid">
        {list.slice(0, 8).map(p => (
          <ProductCard
            key={p.id} p={p}
            onOpen={onOpen} onAdd={onAdd}
            faved={faves.has(p.id)} onFav={onFav}
          />
        ))}
      </div>
    </section>
  );
};

// ---------- Builder banner ----------
const Builder = () => (
  <section className="section shell">
    <div className="builder">
      <div className="builder-l">
        <div className="eyebrow">PC BUILDER</div>
        <h2>Spec your dream rig in 4 steps.</h2>
        <p>Compatibility-checked at every step. Free assembly, stress-testing & a 24-hour burn-in before it ships.</p>
        <div className="builder-steps">
          <div className="b-step active">
            <span className="num">1</span><span className="lbl">Pick a CPU</span>
          </div>
          <div className="b-step">
            <span className="num">2</span><span className="lbl">Choose a GPU</span>
          </div>
          <div className="b-step">
            <span className="num">3</span><span className="lbl">Add parts</span>
          </div>
          <div className="b-step">
            <span className="num">4</span><span className="lbl">Checkout</span>
          </div>
        </div>
        <div style={{ display: "flex", gap: 12 }}>
          <a className="btn btn-primary" href="info.html?topic=custom">Start building <Icon name="arrow" /></a>
          <a className="btn btn-ghost" href="shop.html?cat=case">View prebuilts</a>
        </div>
      </div>
      <div className="builder-r">
        <div style={{ fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>
          Current selection
        </div>
        <div className="parts-list">
          {[
            { icon: "cpu", name: "Processor", val: "Ryzen 9 9950X" },
            { icon: "gpu", name: "Graphics", val: "RTX 5080 16GB" },
            { icon: "ram", name: "Memory", val: "32 GB DDR5-6400" },
            { icon: "ssd", name: "Storage", val: "2 TB NVMe Gen5" },
            { icon: "case", name: "Case", val: "Cipher Mesh Pro" },
          ].map((part, i) => (
            <div className="part-row" key={i}>
              <div className="part-icon"><Icon name={part.icon} /></div>
              <div>
                <div className="part-name">{part.name}</div>
                <div className="part-val">{part.val}</div>
              </div>
              <span className="right"><Icon name="chevR" style={{ width: 14, height: 14 }} /></span>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "8px 12px", marginTop: 8, background: "color-mix(in oklch, var(--purple) 14%, transparent)", border: "1px solid var(--purple)", borderRadius: 8 }}>
          <span style={{ fontSize: 11, color: "var(--ink-dim)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Estimated total</span>
          <span className="display" style={{ fontSize: 20, fontWeight: 600 }}>318 400 <span style={{ fontSize: 11, color: "var(--ink-mute)" }}>DZD</span></span>
        </div>
      </div>
    </div>
  </section>
);

// ---------- Prebuilts ----------
const Prebuilts = ({ onOpen, onAdd, faves, onFav }) => (
  <section className="section shell">
    <div className="section-head">
      <div className="section-title">
        <div className="eyebrow">Ready to ship</div>
        <h2>House-built systems.</h2>
      </div>
      <div className="section-actions">
        <a className="tab-pill" href="shop.html?cat=case">All prebuilts →</a>
      </div>
    </div>
    <div className="product-grid">
      {PREBUILT.map(p => (
        <ProductCard
          key={p.id} p={p}
          onOpen={onOpen} onAdd={onAdd}
          faved={faves.has(p.id)} onFav={onFav}
        />
      ))}
    </div>
  </section>
);

// ---------- Brand strip ----------
const Brands = () => (
  <section className="section shell">
    <div className="brands">
      {BRANDS.map(b => (
        <div className="brand-cell" key={b}>
          <span>{b}</span>
        </div>
      ))}
    </div>
  </section>
);

// ---------- Newsletter ----------
const Newsletter = () => {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  return (
    <section className="section shell">
      <div className="news">
        <div>
          <h2>Drop-day alerts, restock pings, member-only discounts.</h2>
          <p>Join 28 000+ Algerian gamers who hear about new GPU stock before it sells out.</p>
        </div>
        <div>
          <div className="news-form">
            <input
              placeholder="you@gamer.dz"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <button className="btn btn-primary" onClick={() => { setSent(true); setEmail(""); }}>
              {sent ? <><Icon name="check" /> Subscribed</> : <>Notify me <Icon name="arrow" /></>}
            </button>
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 10 }}>
            We send max 1 email per week. No spam, easy unsubscribe.
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- Footer ----------
const Footer = () => (
  <footer className="footer shell">
    <div className="footer-grid">
      <div className="footer-about">
        <a className="logo" href="index.html">
          <span className="logo-mark logo-placeholder">
            <span className="ph-mark">LOGO</span>
          </span>
          <span className="logo-name logo-name-placeholder">Your Brand</span>
        </a>
        <p>Algeria's specialist for gaming hardware, prebuilt rigs, and custom PC assembly. Based in Algiers, shipping nationwide.</p>
        <div className="footer-contact">
          <div><Icon name="pin" /> 12 Rue Didouche Mourad, Algiers 16000</div>
          <div><Icon name="phone" /> 0560 11 02 30 — 0770 88 14 92</div>
          <div><Icon name="mail" /> hello@yourbrand.dz</div>
        </div>
      </div>
      <div>
        <h4>Shop</h4>
        <ul>
          <li><a href="shop.html?cat=case">Prebuilt PCs</a></li>
          <li><a href="shop.html">Components</a></li>
          <li><a href="shop.html?cat=kb">Peripherals</a></li>
          <li><a href="shop.html?cat=mon">Monitors</a></li>
          <li><a href="shop.html?cat=mb">Networking</a></li>
        </ul>
      </div>
      <div>
        <h4>Services</h4>
        <ul>
          <li><a href="index.html#builder">PC Builder</a></li>
          <li><a href="info.html?topic=tradein">Trade-in program</a></li>
          <li><a href="info.html?topic=custom">Custom paint</a></li>
          <li><a href="info.html?topic=repairs">Repairs &amp; RMA</a></li>
          <li><a href="info.html?topic=business">Business orders</a></li>
        </ul>
      </div>
      <div>
        <h4>Support</h4>
        <ul>
          <li><a href="track.html">Order tracking</a></li>
          <li><a href="info.html?topic=shipping">Shipping &amp; returns</a></li>
          <li><a href="info.html?topic=warranty">Warranty</a></li>
          <li><a href="info.html?topic=contact">Contact us</a></li>
          <li><a href="info.html?topic=faq">FAQ</a></li>
        </ul>
      </div>
      <div>
        <h4>Company</h4>
        <ul>
          <li><a href="info.html?topic=about">About us</a></li>
          <li><a href="info.html?topic=showroom">Showroom</a></li>
          <li><a href="info.html?topic=blog">Blog &amp; guides</a></li>
          <li><a href="info.html?topic=careers">Careers</a></li>
          <li><a href="info.html?topic=press">Press kit</a></li>
        </ul>
      </div>
    </div>
    <div className="footer-bottom">
      <div>© 2026 Your Brand SARL · Algiers, Algeria · NIF 099916123456789</div>
      <div className="payments">
        <span className="pay-chip">CIB</span>
        <span className="pay-chip">EDAHABIA</span>
        <span className="pay-chip">CASH</span>
        <span className="pay-chip">3× INSTALL.</span>
      </div>
    </div>
  </footer>
);

window.AnnounceBar = AnnounceBar;
window.Header = Header;
window.MegaNav = MegaNav;
window.Hero = Hero;
window.Stats = Stats;
window.CategoryTiles = CategoryTiles;
window.FlashDeals = FlashDeals;
window.Featured = Featured;
window.Builder = Builder;
window.Prebuilts = Prebuilts;
window.Brands = Brands;
window.Newsletter = Newsletter;
window.Footer = Footer;
window.ProductCard = ProductCard;
