/* Shared components for Hands Carpets */

const { useState, useEffect, useRef } = React;

// ── Icons ─────────────────────────────────────────────────────────
const Icon = {
  search: <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  bag:    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 7h14l-1.5 13H6.5L5 7Z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>,
  arrow:  <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  arrowSm:<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 8h10M9 3l5 5-5 5"/></svg>,
  arrowUp:<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M7 17 17 7M9 7h8v8"/></svg>,
  close:  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 6l12 12M18 6 6 18"/></svg>,
  heart:  <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 10c0 5.5-7 10-7 10Z"/></svg>,
  heartF: <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 10c0 5.5-7 10-7 10Z"/></svg>,
  whats:  <svg viewBox="0 0 32 32" fill="currentColor"><path d="M16.001 3C9.376 3 4 8.373 4 14.999c0 2.293.677 4.444 1.927 6.296L4 28l6.875-1.804A11.96 11.96 0 0 0 16 27c6.624 0 12-5.373 12-11.999S22.624 3 16.001 3Zm0 21.835c-1.752 0-3.474-.482-4.971-1.392l-.357-.214-4.083 1.072 1.094-3.978-.234-.41a9.84 9.84 0 0 1-1.4-5.064c0-5.435 4.422-9.857 9.858-9.857 5.434 0 9.856 4.422 9.856 9.857.001 5.434-4.421 9.857-9.857 9.857l-.006-.04zm5.4-7.387c-.296-.148-1.75-.86-2.022-.958-.272-.099-.47-.149-.668.149-.197.296-.766.957-.94 1.154-.173.198-.346.222-.643.074-.297-.148-1.253-.461-2.387-1.474-.882-.787-1.477-1.76-1.65-2.057-.173-.297-.018-.457.13-.605.133-.133.297-.347.446-.52.149-.173.198-.296.297-.495.099-.198.05-.371-.025-.52-.074-.149-.668-1.61-.915-2.204-.24-.578-.485-.5-.668-.51-.173-.009-.371-.011-.569-.011a1.09 1.09 0 0 0-.792.371c-.272.297-1.04 1.016-1.04 2.478 0 1.461 1.065 2.873 1.213 3.07.149.198 2.097 3.202 5.083 4.49.71.307 1.264.49 1.696.626.713.227 1.362.195 1.876.118.572-.085 1.75-.715 1.997-1.405.247-.69.247-1.282.173-1.405-.074-.124-.272-.198-.569-.346z"/></svg>,
  burger: <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 7h18M3 12h18M3 17h18"/></svg>,
  pin:    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 22s-7-7.5-7-13a7 7 0 0 1 14 0c0 5.5-7 13-7 13Z"/><circle cx="12" cy="9" r="2.5"/></svg>,
  phone:  <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.33 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>,
  mail:   <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="5" width="18" height="14" rx="1"/><path d="m3 7 9 6 9-6"/></svg>,
};

// ── Navbar ────────────────────────────────────────────────────────
function Navbar({ route, navigate, cartCount, openCart }) {
  const [scrolled, setScrolled] = useState(false);
  const [mega, setMega] = useState(null); // "collections" | null
  const megaRef = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // close mega when route changes
  useEffect(() => { setMega(null); }, [route]);

  const navItems = [
    { key: "collections", label: "Collections", hasMenu: true },
    { key: "bespoke",     label: "Bespoke" },
    { key: "projects",    label: "Projects" },
    { key: "craft",       label: "The Craft" },
    { key: "showroom",    label: "Showroom" },
  ];

  return (
    <header
      className={"nav " + (scrolled || route !== "home" ? "scrolled" : "")}
      onMouseLeave={() => setMega(null)}
    >
      <div className="nav-inner">
        <div className="nav-links" style={{ justifySelf: "start" }}>
          {navItems.map(item => (
            <a
              key={item.key}
              className={"nav-link " + (route === item.key || (item.key === "collections" && route === "collection") ? "active" : "")}
              href="#"
              onClick={(e) => { e.preventDefault(); if (item.hasMenu) { setMega(mega === item.key ? null : item.key); } else { navigate(item.key); } }}
              onMouseEnter={() => { if (item.hasMenu) setMega(item.key); else setMega(null); }}
            >
              {item.label}
              {item.hasMenu && <span className="chev">▼</span>}
            </a>
          ))}
        </div>

        <a href="#" onClick={(e) => { e.preventDefault(); navigate("home"); }} className="nav-logo" aria-label="Hands — go to home">
          <HandsLogo size={36} />
        </a>

        <div className="nav-right">
          <a href="#" className="nav-icon-btn" onClick={(e) => { e.preventDefault(); navigate("contact"); }}>
            {Icon.search}
          </a>
          <a href="#" className="nav-cta" onClick={(e) => { e.preventDefault(); navigate("bespoke"); }}>
            Book a consultation
          </a>
          <a href="#" className="nav-icon-btn cart-pill" onClick={(e) => { e.preventDefault(); openCart(); }}>
            {Icon.bag} <span>Bag</span>
            {cartCount > 0 && <span className="cart-count">{cartCount}</span>}
          </a>
        </div>
      </div>

      <div ref={megaRef} className={"mega " + (mega === "collections" ? "open" : "")}>
        <div className="mega-grid">
          <div className="mega-col">
            <h5>By style</h5>
            <ul>
              {COLLECTIONS_BY_STYLE.slice(0, 5).map(c => (
                <li key={c.handle}><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: c.handle }); setMega(null); }}>{c.name}</a></li>
              ))}
            </ul>
          </div>
          <div className="mega-col">
            <h5>By material</h5>
            <ul>
              {COLLECTIONS_BY_MATERIAL.map(c => (
                <li key={c.handle}><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: c.handle }); setMega(null); }}>{c.name}</a></li>
              ))}
            </ul>
          </div>
          <div className="mega-col">
            <h5>By room</h5>
            <ul>
              {COLLECTIONS_BY_ROOM.map(c => (
                <li key={c.handle}><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: c.handle }); setMega(null); }}>{c.name}</a></li>
              ))}
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collections"); setMega(null); }} style={{ color: "var(--gold)", fontSize: 15, fontFamily: "var(--mono)", letterSpacing: "0.16em", textTransform: "uppercase" }}>View all collections →</a></li>
            </ul>
          </div>
          <div className="mega-feat" onClick={() => { navigate("bespoke"); setMega(null); }} style={{ cursor: "pointer" }}>
            <img src="media/custom-made-thumb.webp" alt="Bespoke" />
            <div className="mega-feat-cap">
              <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--gold-soft)", marginBottom: 6 }}>The Atelier</div>
              <div className="serif" style={{ fontSize: 30, lineHeight: 1.05 }}>A bespoke<br/>carpet for your<br/><em style={{ fontStyle: "italic" }}>exact</em> room.</div>
              <div style={{ marginTop: 14, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase" }}>Begin a project →</div>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

// ── WhatsApp FAB ──────────────────────────────────────────────────
function WhatsAppFab() {
  const url = "https://wa.me/971588250451?text=" + encodeURIComponent("Hello Hands Carpets — I'd like to enquire about your carpets.");
  return (
    <a className="wa-fab" href={url} target="_blank" rel="noopener" aria-label="WhatsApp Hands Carpets">
      {Icon.whats}
    </a>
  );
}

// ── ProductCard ───────────────────────────────────────────────────
function ProductCard({ p, onOpen, fav, toggleFav, badge }) {
  return (
    <div className="prod-card" onClick={() => onOpen(p)}>
      <div className="prod-card-img">
        <img src={p.img} alt={p.title} loading="lazy" />
        <div className="prod-card-badge">{badge || p.type}</div>
        <button
          className={"prod-card-fav " + (fav ? "on" : "")}
          onClick={(e) => { e.stopPropagation(); toggleFav(p.handle); }}
          aria-label="Add to wishlist"
        >
          {fav ? Icon.heartF : Icon.heart}
        </button>
        <div className="prod-card-quick">View piece →</div>
      </div>
      <div className="prod-card-meta">
        <div>
          <h4 className="prod-card-title">{p.title}</h4>
          <div className="prod-card-sub">{p.palette}</div>
        </div>
        <div className="prod-card-price">{fmtAED(p.price)}</div>
      </div>
    </div>
  );
}

// ── Cart Drawer ───────────────────────────────────────────────────
function CartDrawer({ open, close, cart, removeFromCart, navigate }) {
  const total = cart.reduce((s, ci) => s + (ci.price * ci.qty), 0);

  useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <>
      <div className={"drawer-bg " + (open ? "open" : "")} onClick={close} />
      <aside className={"drawer " + (open ? "open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Your bag</h3>
          <button className="drawer-close" onClick={close}>Close {Icon.close}</button>
        </div>
        <div className="drawer-body">
          {cart.length === 0 ? (
            <div className="drawer-empty">
              <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--muted)" }}>Empty bag</div>
              <h4>Begin with a piece.</h4>
              <p style={{ maxWidth: 320, margin: "0 auto 24px" }}>Explore ready hand-knotted carpets — or open a bespoke enquiry for a piece woven to your room.</p>
              <button className="btn btn-dark" onClick={() => { close(); navigate("collections"); }}>Explore collections {Icon.arrowSm}</button>
            </div>
          ) : cart.map(ci => (
            <div key={ci.handle} className="cart-item">
              <img src={ci.img} alt={ci.title} />
              <div>
                <h4 className="ci-title">{ci.title}</h4>
                <div className="ci-sub">{ci.type} · {ci.palette}</div>
                <div className="ci-sub" style={{ marginTop: 6 }}>Qty {ci.qty}</div>
                <button className="ci-remove" onClick={() => removeFromCart(ci.handle)}>Remove</button>
              </div>
              <div className="ci-price">{fmtAED(ci.price * ci.qty)}</div>
            </div>
          ))}
        </div>
        {cart.length > 0 && (
          <div className="drawer-foot">
            <div className="drawer-total">
              <div>
                <div className="lbl">Subtotal</div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)", marginTop: 4 }}>Shipping & taxes at checkout</div>
              </div>
              <div className="val">{fmtAED(total)}</div>
            </div>
            <button className="btn btn-primary">Checkout via Shopify {Icon.arrow}</button>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)", marginTop: 14, textAlign: "center" }}>
              Secure handoff to <span style={{ color: "var(--ink)" }}>handscarpets.ae</span> checkout
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

// ── Footer ────────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <div className="lockup"><HandsLogo size={48} /></div>
            <p>A house of carpets since 1881. Bespoke hand-knotted carpets woven from the finest New Zealand wool, for the world's most exceptional rooms.</p>
            <div className="socials">
              <a href="https://instagram.com/handscarpets" target="_blank" rel="noopener" aria-label="Instagram">Ig</a>
              <a href="https://facebook.com/handscarpets" target="_blank" rel="noopener" aria-label="Facebook">Fb</a>
              <a href="https://twitter.com/handscarpets" target="_blank" rel="noopener" aria-label="Twitter">X</a>
              <a href="https://in.pinterest.com/handscarpets" target="_blank" rel="noopener" aria-label="Pinterest">Pn</a>
              <a href="https://www.linkedin.com/company/hands-carpets-&-rugs---india/" target="_blank" rel="noopener" aria-label="LinkedIn">In</a>
              <a href="https://www.youtube.com/channel/UCOtTXL-IvBsJ4EYAJVdC0_A" target="_blank" rel="noopener" aria-label="YouTube">Yt</a>
            </div>
          </div>
          <div className="footer-col">
            <h5>Shop</h5>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: "persian" }); }}>Persian</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: "traditional" }); }}>Traditional</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: "contemporary" }); }}>Contemporary</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collection", { handle: "modern" }); }}>Modern</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("collections"); }}>All collections</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Atelier</h5>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("bespoke"); }}>Bespoke service</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("projects"); }}>Trade & projects</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("craft"); }}>The Craft</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>Showroom</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Visit</h5>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>Dubai — d3</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>New Delhi</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>Mumbai</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>Hyderabad</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("showroom"); }}>Singapore</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <ul>
              <li><a href="tel:+97145898510">+971 4 589 8510</a></li>
              <li><a href="tel:+971588250574">+971 58 825 0574</a></li>
              <li><a href="https://wa.me/971588250451" target="_blank" rel="noopener">WhatsApp · 0451</a></li>
              <li><a href="mailto:info@handscarpets.ae">info@handscarpets.ae</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("contact"); }}>Enquiry form</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "rgba(250,244,234,0.55)" }}>
            © 1881–{new Date().getFullYear()} Hands Carpets FZ-LLC · #3 Building 9, d3 Dubai · A heritage carpet house
          </div>
          <div className="legal">
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="#">Cookies</a>
            <a href="#">Trade login</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── Page head (shared) ────────────────────────────────────────────
function PageHead({ crumb, title, sub, bg }) {
  return (
    <div className="page-head">
      <div className="bg" style={{ backgroundImage: `url(${bg || "media/collection-traditional.webp"})` }} />
      <div className="page-head-inner">
        <div className="crumb">{crumb}</div>
        <h1 dangerouslySetInnerHTML={{ __html: title }} />
        {sub && <p className="sub">{sub}</p>}
      </div>
    </div>
  );
}

Object.assign(window, { Icon, Navbar, WhatsAppFab, ProductCard, CartDrawer, Footer, PageHead });
