// LAM Shining — UI components.
// Header, Hero variants, Ribbon, Featured grid, Categories, Footer, WhatsApp FAB, Toast, MobileDrawer.

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

// ── Icons ────────────────────────────────────────────────────────────────────
const Icon = {
  Search: (p) => (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" strokeLinecap="round"/>
    </svg>
  ),
  Bag: (p) => (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M5 8h14l-1 12H6L5 8z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/>
    </svg>
  ),
  Menu: (p) => (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 7h18M3 17h18" strokeLinecap="round"/>
    </svg>
  ),
  X: (p) => (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M6 6l12 12M18 6 6 18" strokeLinecap="round"/>
    </svg>
  ),
  Arrow: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  WhatsApp: (p) => (
    <svg viewBox="0 0 24 24" width="26" height="26" fill="currentColor" {...p}>
      <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.2-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-1.7-.9-2.9-1.6-4-3.6-.3-.5.3-.5.9-1.5.1-.2.1-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5 0 1.5 1.1 2.9 1.2 3 .1.2 2.1 3.2 5 4.5 1.9.7 2.6.8 3.5.7.6-.1 1.7-.7 2-1.4.3-.7.3-1.2.2-1.4-.1-.2-.3-.3-.6-.4zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.4c1.5.8 3.1 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
    </svg>
  ),
  Instagram: (p) => (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="5"/>
      <circle cx="12" cy="12" r="4"/>
      <circle cx="17.5" cy="6.5" r=".8" fill="currentColor"/>
    </svg>
  ),
  TikTok: (p) => (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" {...p}>
      <path d="M16 3v2.6c1 .7 2.2 1.1 3.4 1.1V9c-1.2 0-2.4-.3-3.4-.8v6.3a5.2 5.2 0 1 1-5.2-5.2v2.5a2.8 2.8 0 1 0 2.8 2.7V3H16z"/>
    </svg>
  ),
  Heart: (p) => (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M12 20.5s-7.5-4.5-7.5-10.2a4.3 4.3 0 0 1 7.5-2.9 4.3 4.3 0 0 1 7.5 2.9c0 5.7-7.5 10.2-7.5 10.2z"/>
    </svg>
  ),
};

// ── Header ───────────────────────────────────────────────────────────────────
function Header({ cartCount, onCart, onMenu, onNav, activeSection }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const NAV = [
    { id: "home", label: "Home", ar: "الرئيسية" },
    { id: "shop", label: "Shop", ar: "المتجر" },
    { id: "categories", label: "Categories", ar: "الأقسام" },
    { id: "payment", label: "Payment", ar: "الدفع" },
  ];

  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <button className="icon-btn nav-burger hide-desktop" onClick={onMenu} aria-label="Menu">
        <Icon.Menu />
      </button>
      <a href="#" className="nav-logo" onClick={(e) => { e.preventDefault(); onNav("home"); }}>
        LAM <i>Shining</i>
      </a>
      <nav className="nav-links">
        {NAV.map(n => (
          <a key={n.id} href={`#${n.id}`}
             className={`nav-link ${activeSection === n.id ? "active" : ""}`}
             onClick={(e) => { e.preventDefault(); onNav(n.id); }}>
            {n.label}
          </a>
        ))}
      </nav>
      <div className="nav-actions">
        <button className="icon-btn hide-mobile" aria-label="Search"><Icon.Search /></button>
        <button className="icon-btn" onClick={onCart} aria-label="Bag">
          <Icon.Bag />
          {cartCount > 0 && <span className="cart-pip">{cartCount}</span>}
        </button>
      </div>
    </header>
  );
}

// ── Mobile drawer ────────────────────────────────────────────────────────────
function MobileDrawer({ open, onClose, onNav }) {
  const NAV = [
    { id: "home",       label: "Home",       ar: "الرئيسية" },
    { id: "shop",       label: "Shop",       ar: "المتجر" },
    { id: "categories", label: "Categories", ar: "الأقسام" },
    { id: "payment",    label: "Payment",    ar: "الدفع" },
  ];
  return (
    <React.Fragment>
      <div className={`drawer-scrim ${open ? "open" : ""}`} onClick={onClose} />
      <aside className={`drawer ${open ? "open" : ""}`}>
        <div className="drawer-hd">
          <div className="nav-logo">LAM <i>Shining</i></div>
          <button className="drawer-x icon-btn" onClick={onClose} aria-label="Close">
            <Icon.X />
          </button>
        </div>
        <nav className="drawer-nav">
          {NAV.map(n => (
            <a key={n.id} className="drawer-link serif"
               onClick={() => { onNav(n.id); onClose(); }}>
              <span>{n.label}</span>
              <span className="ar">{n.ar}</span>
            </a>
          ))}
        </nav>
        <div className="drawer-socials">
          <a href="#" onClick={(e) => e.preventDefault()}>Instagram</a>
          <a href="#" onClick={(e) => e.preventDefault()}>TikTok</a>
          <a href="#" onClick={(e) => e.preventDefault()}>WhatsApp</a>
        </div>
      </aside>
    </React.Fragment>
  );
}

// ── Hero variants ────────────────────────────────────────────────────────────
const HERO_IMG = "https://images.unsplash.com/photo-1515562141207-7a88fb7ce338?w=1600&q=85&auto=format&fit=crop";

function HeroEditorial({ onShop }) {
  return (
    <section className="hero-editorial" id="home" style={{ "--hero-img": `url(${HERO_IMG})` }} data-screen-label="01 Hero">
      <div>
        <div className="h-eyebrow">Issue No. 01 · Spring / Summer 2026</div>
        <h1 className="reveal in">
          Quiet luxury,<br />loudly <i>loved.</i>
        </h1>
        <div className="h-ar ar reveal in" data-delay="1">فخامة هادئة، محبوبة بشدة</div>
        <div className="h-meta reveal in" data-delay="2">
          <p className="h-tag">
            A small Egyptian accessories house, founded in Cairo. Hand-finished
            pieces designed to be worn every day — never saved for someday.
          </p>
          <button className="h-cta" onClick={onShop}>
            Discover the Collection <Icon.Arrow />
          </button>
        </div>
      </div>
    </section>
  );
}

function HeroSplit({ onShop }) {
  return (
    <section className="hero-split" id="home" style={{ "--hero-img": `url(${HERO_IMG})` }} data-screen-label="01 Hero">
      <div className="hs-text">
        <div className="eyebrow">Spring / Summer 2026</div>
        <h1>
          Made for<br />everyday <i>elegance.</i>
        </h1>
        <div className="hs-ar ar serif">مصنوع للأناقة اليومية</div>
        <p className="hs-tag">
          A small Egyptian accessories house. Hand-finished pieces designed to be
          worn every day — never saved for someday.
        </p>
        <button className="h-cta" onClick={onShop}>
          Shop the Collection <Icon.Arrow />
        </button>
      </div>
      <div className="hs-img" />
    </section>
  );
}

function HeroGrand({ onShop }) {
  return (
    <section className="hero-grand" id="home" style={{ "--hero-img": `url(${HERO_IMG})` }} data-screen-label="01 Hero">
      <div className="hg-img" />
      <div className="hg-inner">
        <div className="hg-eyebrow eyebrow">Est. Cairo · 2024</div>
        <h1>
          LAM<br /><i>Shining</i>
        </h1>
        <div className="hg-ar ar serif">لام شاينينج</div>
        <p className="hg-tag">
          A small Egyptian accessories house. Hand-finished pieces designed to be
          worn every day — never saved for someday.
        </p>
        <button className="h-cta" onClick={onShop}>
          Discover the Collection <Icon.Arrow />
        </button>
      </div>
    </section>
  );
}

function Hero({ variant, onShop }) {
  if (variant === "split")  return <HeroSplit onShop={onShop} />;
  if (variant === "grand")  return <HeroGrand onShop={onShop} />;
  return <HeroEditorial onShop={onShop} />;
}

// ── Marquee ribbon ───────────────────────────────────────────────────────────
function Ribbon() {
  const items = [
    "Free delivery in Cairo over EGP 1500",
    "توصيل مجاني في القاهرة",
    "Hand-finished in Egypt",
    "صُنع يدوياً في مصر",
    "WhatsApp · InstaPay · Vodafone Cash",
    "واتساب · انستا باي · فودافون كاش",
    "New arrivals every Friday",
    "تشكيلات جديدة كل جمعة",
  ];
  // Duplicate for seamless scroll
  const full = [...items, ...items];
  return (
    <div className="ribbon" aria-hidden="true">
      <div className="ribbon-track">
        {full.map((t, i) => (
          <span key={i} className="ribbon-item">
            <span className="dot" />
            <span className={/[\u0600-\u06FF]/.test(t) ? "ar serif" : ""}>{t}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ── Product card ─────────────────────────────────────────────────────────────
function ProductCard({ product, onOpen, onAdd, variant }) {
  const [bg, ink] = product.palette || ["#f4f2ed", "#1a1a1a"];
  const hasImage = !!product.image;
  return (
    <article className="card reveal" onClick={() => onOpen(product)}>
      <div className="card-media">
        {hasImage ? (
          <img src={product.image} alt={product.name} loading="lazy" />
        ) : (
          <div className="placeholder" style={{ background: bg, color: ink }}>
            <span className="placeholder-glyph">{product.name.charAt(0)}</span>
            <div className="placeholder-label">
              <span>LAM · {product.no}</span>
              <span>{product.category.toUpperCase()}</span>
            </div>
          </div>
        )}
        {product.badge && <span className="badge">{product.badge}</span>}
        <button className="card-quickadd" onClick={(e) => { e.stopPropagation(); onAdd(product); }}>
          + Add to Bag
        </button>
      </div>
      <div className="card-body">
        {variant === "editorial" && <div className="card-no">No. {product.no}</div>}
        <div className="card-name serif">{product.name}</div>
        <div className="card-name-ar ar">{product.nameAr}</div>
        <div className="card-price">
          <span className="current">EGP {product.price.toLocaleString()}</span>
          {product.originalPrice && (
            <span className="original">EGP {product.originalPrice.toLocaleString()}</span>
          )}
        </div>
      </div>
    </article>
  );
}

// ── Featured / Shop section ──────────────────────────────────────────────────
function Featured({ products, cardVariant, onOpen, onAdd, filter, setFilter }) {
  const filtered = useMemo(() => {
    return filter === "all" ? products : products.filter(p => p.category === filter);
  }, [products, filter]);
  return (
    <section className="section" id="shop" data-screen-label="02 Shop">
      <div className="section-hd">
        <div>
          <div className="eyebrow reveal" style={{ marginBottom: 12 }}>
            <span className="serif" style={{ fontStyle: "italic", textTransform: "none", letterSpacing: 0, fontSize: 14, marginRight: 8 }}>—</span>
            The Collection · المجموعة
          </div>
          <h2 className="section-title reveal" data-delay="1">
            Every <i>piece,</i><br />a small obsession.
          </h2>
        </div>
        <div className="section-sub reveal" data-delay="2">
          Twelve pieces, each photographed in natural light.
          <span className="ar">اثنتا عشرة قطعة، كل منها مصورة في إضاءة طبيعية.</span>
        </div>
      </div>

      <div className="filters reveal" data-delay="2">
        <button
          className={`filter-chip ${filter === "all" ? "active" : ""}`}
          onClick={() => setFilter("all")}>
          All · الكل
        </button>
        {CATEGORIES.map(c => (
          <button key={c.id}
                  className={`filter-chip ${filter === c.id ? "active" : ""}`}
                  onClick={() => setFilter(c.id)}>
            {c.name}
          </button>
        ))}
      </div>

      <div className={`products-grid cards-${cardVariant}`}>
        {filtered.map((p, i) => (
          <ProductCard key={p.id}
                       product={p}
                       variant={cardVariant}
                       onOpen={onOpen}
                       onAdd={onAdd} />
        ))}
      </div>
    </section>
  );
}

// ── Categories ───────────────────────────────────────────────────────────────
function Categories({ onPick }) {
  return (
    <section className="section" id="categories" style={{ background: "var(--soft)" }} data-screen-label="03 Categories">
      <div className="section-hd">
        <div>
          <div className="eyebrow reveal" style={{ marginBottom: 12 }}>
            <span className="serif" style={{ fontStyle: "italic", textTransform: "none", letterSpacing: 0, fontSize: 14, marginRight: 8 }}>—</span>
            Categories · الأقسام
          </div>
          <h2 className="section-title reveal" data-delay="1">
            Find your <i>thing.</i>
          </h2>
        </div>
        <div className="section-sub reveal" data-delay="2">
          Six categories, one ethos: pieces that work as hard as you do.
          <span className="ar">ستة أقسام، فلسفة واحدة: قطع تعمل بقدر ما تعمل أنتِ.</span>
        </div>
      </div>
      <div className="cat-grid">
        {CATEGORIES.map((c, i) => (
          <button key={c.id}
                  className="cat reveal"
                  style={{ "--cat-bg": c.accent }}
                  onClick={() => onPick(c.id)}>
            <span className="cat-glyph">{c.name.charAt(0)}</span>
            <span className="cat-count">{String(c.count).padStart(2, "0")} · pieces</span>
            <div className="cat-name serif">{c.name}</div>
            <div className="cat-name-ar ar">{c.nameAr}</div>
          </button>
        ))}
      </div>
    </section>
  );
}

// ── Footer ───────────────────────────────────────────────────────────────────
function Footer({ onNav }) {
  return (
    <footer className="footer" id="payment" data-screen-label="04 Footer">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="logo">LAM <i>Shining</i></div>
          <p className="tag">
            A small Egyptian accessories house. Hand-finished pieces, made to be worn every day.
            <span className="ar serif">دار إكسسوارات مصرية صغيرة، قطع مصنوعة يدوياً لتُلبس كل يوم.</span>
          </p>
        </div>
        <div className="footer-col">
          <h4>Shop</h4>
          <ul>
            {CATEGORIES.map(c => (
              <li key={c.id}><a href="#" onClick={(e) => { e.preventDefault(); onNav("shop"); }}>{c.name}</a></li>
            ))}
          </ul>
        </div>
        <div className="footer-col">
          <h4>Help</h4>
          <ul>
            <li><a href="#" onClick={(e) => e.preventDefault()}>Delivery</a></li>
            <li><a href="#" onClick={(e) => e.preventDefault()}>Returns &amp; Exchange</a></li>
            <li><a href="#" onClick={(e) => e.preventDefault()}>Sizing Guide</a></li>
            <li><a href="#" onClick={(e) => e.preventDefault()}>FAQ</a></li>
            <li><a href="#" onClick={(e) => e.preventDefault()}>Contact</a></li>
          </ul>
        </div>
        <div className="pay-box">
          <h5>Payment</h5>
          <p style={{ fontSize: 12, color: "var(--mute)", margin: 0 }}>
            Three ways to pay. Choose whichever feels easiest.
          </p>
          <div className="meth">
            <div className="meth-row"><span className="lbl">InstaPay</span><span className="v">{BRAND.instapay}</span></div>
            <div className="meth-row"><span className="lbl">Vodafone Cash</span><span className="v">{BRAND.vodafoneCash}</span></div>
            <div className="meth-row"><span className="lbl">Cash on Delivery</span><span className="v">Available</span></div>
          </div>
          <p className="note">
            After payment, send a screenshot on WhatsApp with your order.
            <span className="ar serif">بعد الدفع، أرسلي لقطة الشاشة عبر واتساب مع طلبك.</span>
          </p>
        </div>
      </div>
      <div className="footer-bot">
        <span>© 2026 LAM Shining · Made in Cairo</span>
        <div className="socials">
          <a href="#" onClick={(e) => e.preventDefault()}>Instagram</a>
          <a href="#" onClick={(e) => e.preventDefault()}>TikTok</a>
          <a href="#" onClick={(e) => e.preventDefault()}>WhatsApp</a>
        </div>
      </div>
    </footer>
  );
}

// ── WhatsApp FAB ─────────────────────────────────────────────────────────────
function WhatsAppFab({ onClick }) {
  return (
    <button className="wa-fab" onClick={onClick} aria-label="Order on WhatsApp" title="Order on WhatsApp">
      <Icon.WhatsApp />
    </button>
  );
}

// ── Toast ────────────────────────────────────────────────────────────────────
function Toast({ message }) {
  return <div className={`toast ${message ? "in" : ""}`}>{message}</div>;
}

Object.assign(window, {
  Icon, Header, MobileDrawer, Hero, Ribbon,
  ProductCard, Featured, Categories, Footer, WhatsAppFab, Toast,
});
