// components.jsx — chrome (logo, nav, footer, primitives) for Montroi
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─────────────────────────────────────────────────────────────
// Logo — typographic wordmark, no SVG mark (per brief: vector requested but not yet supplied)
function Logo({ size = 22, onClick }) {
  return (
    <a href="#/" onClick={(e) => { if (onClick) { e.preventDefault(); onClick(); } }}
       className="m-logo" style={{ fontSize: size, letterSpacing: ".34em" }}>
      MONTROI
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
// Tiny utility icons (hairline, no fill)
const Ic = {
  arrow: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor"
         strokeWidth="1.25" strokeLinecap="square" strokeLinejoin="miter" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6"/>
    </svg>
  ),
  arrowLong: (p) => (
    <svg viewBox="0 0 48 12" width="48" height="12" fill="none" stroke="currentColor"
         strokeWidth="1" strokeLinecap="square" {...p}>
      <path d="M0 6h44M38 1.5 44 6l-6 4.5"/>
    </svg>
  ),
  bag: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.25" {...p}>
      <path d="M5 8h14l-1 12H6L5 8Z"/><path d="M9 8a3 3 0 0 1 6 0"/>
    </svg>
  ),
  close: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor"
         strokeWidth="1.25" {...p}>
      <path d="M5 5l14 14M19 5 5 19"/>
    </svg>
  ),
  menu: (p) => (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor"
         strokeWidth="1.25" {...p}>
      <path d="M3 7h18M3 17h18"/>
    </svg>
  ),
  search: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.25" {...p}>
      <circle cx="11" cy="11" r="6"/><path d="m20 20-3.5-3.5"/>
    </svg>
  ),
  globe: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor"
         strokeWidth="1.1" {...p}>
      <circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>
    </svg>
  ),
  ig: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.1" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="4"/><circle cx="12" cy="12" r="4"/>
      <circle cx="17.5" cy="6.5" r=".7" fill="currentColor"/>
    </svg>
  ),
  fb: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.1" {...p}>
      <path d="M15 8h-2a1 1 0 0 0-1 1v3h3l-.5 3H12v6H9v-6H7v-3h2V9a4 4 0 0 1 4-4h2v3Z"/>
    </svg>
  ),
  vimeo: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.1" {...p}>
      <path d="M3 8c1.6-1.5 4-2.5 4 0 0 1.5-2 6-3 8-1 1-1 2 1 2 4 0 8-8 9-12 .8-3-1-4-3-4-3 0-5 4-5 6"/>
    </svg>
  ),
  whatsapp: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
         strokeWidth="1.1" {...p}>
      <path d="M4 20l1.3-3.6A8 8 0 1 1 8.4 19.4L4 20Z"/>
    </svg>
  ),
};

// ─────────────────────────────────────────────────────────────
// Navbar
function Navbar({ route, navigate, cartCount, openCart, locale, setLocale }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const items = [
    ["/story", "Story"],
    ["/provenance", "Provenance"],
    ["/shop", "Shop"],
    ["/workshops", "Workshops"],
    ["/gifting", "Gifting"],
    ["/boutiques", "Boutiques"],
    ["/journal", "Journal"],
  ];

  return (
    <header className={`m-nav ${scrolled ? "is-scrolled" : ""}`}>
      <div className="m-nav__row m-nav__row--top">
        <button className="m-nav__menu" onClick={() => setMobileOpen(true)} aria-label="Menu">
          <Ic.menu/>
        </button>
        <nav className="m-nav__primary" aria-label="Primary">
          {items.slice(0, 4).map(([href, label]) => (
            <a key={href} href={`#${href}`}
               className={`m-nav__link ${route === href ? "is-active" : ""}`}
               onClick={(e) => { e.preventDefault(); navigate(href); }}>{label}</a>
          ))}
        </nav>
        <div className="m-nav__brand">
          <Logo size={18} onClick={() => navigate("/")}/>
        </div>
        <nav className="m-nav__primary m-nav__primary--end" aria-label="Secondary">
          {items.slice(4).map(([href, label]) => (
            <a key={href} href={`#${href}`}
               className={`m-nav__link ${route === href ? "is-active" : ""}`}
               onClick={(e) => { e.preventDefault(); navigate(href); }}>{label}</a>
          ))}
        </nav>
        <div className="m-nav__utils">
          <button className="m-nav__util" onClick={() => setLocale(locale === "EN" ? "AR" : "EN")}
                  aria-label="Language">
            <Ic.globe/> <span>{locale}</span>
          </button>
          <button className="m-nav__util" aria-label="Search"><Ic.search/></button>
          <button className="m-nav__util m-nav__bag" onClick={openCart} aria-label="Bag">
            <Ic.bag/>
            {cartCount > 0 ? <span className="m-nav__count">{cartCount}</span> : null}
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      {mobileOpen ? (
        <div className="m-mobile" role="dialog" aria-modal="true">
          <div className="m-mobile__bar">
            <Logo size={16} onClick={() => { navigate("/"); setMobileOpen(false); }}/>
            <button onClick={() => setMobileOpen(false)} className="m-nav__util"><Ic.close/></button>
          </div>
          <nav className="m-mobile__list">
            {items.map(([href, label]) => (
              <a key={href} href={`#${href}`}
                 onClick={(e) => { e.preventDefault(); navigate(href); setMobileOpen(false); }}>
                {label} <Ic.arrow/>
              </a>
            ))}
          </nav>
          <div className="m-mobile__foot">
            <a href="tel:+971507490210">+971 50 749 0210</a>
            <a href="mailto:info@montroi.com">info@montroi.com</a>
          </div>
        </div>
      ) : null}
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// Footer
function Footer({ navigate }) {
  return (
    <footer className="m-foot">
      <div className="m-foot__top">
        <div className="m-foot__brand">
          <Logo size={20}/>
          <p className="m-foot__tag">A philosophy of modern nomadism.<br/>Dubai · est. 2014.</p>
          <div className="m-foot__socials" aria-label="Social">
            <a href="https://instagram.com/montroi" target="_blank" rel="noreferrer"><Ic.ig/></a>
            <a href="https://facebook.com/montroi" target="_blank" rel="noreferrer"><Ic.fb/></a>
            <a href="https://vimeo.com/716720227" target="_blank" rel="noreferrer"><Ic.vimeo/></a>
          </div>
        </div>
        <FootCol heading="Discover" items={[
          ["/story", "The Montroi Story"],
          ["/provenance", "Provenance · Ateliers"],
          ["/journal", "Journal & Films"],
          ["/one-and-only", "One&Only Collection"],
        ]} navigate={navigate}/>
        <FootCol heading="Shop" items={[
          ["/shop/leather", "Leather Goods"],
          ["/shop/fragrance", "Fragrance"],
          ["/shop/home", "Home & Objects"],
          ["/shop", "Catalogue"],
        ]} navigate={navigate}/>
        <FootCol heading="Experience" items={[
          ["/workshops", "Workshops"],
          ["/gifting", "Concierge Gifting"],
          ["/boutiques", "Boutiques"],
          ["/contact", "Contact"],
        ]} navigate={navigate}/>
        <div className="m-foot__col">
          <h4>Stay in the journal</h4>
          <p className="m-foot__small">
            Quiet dispatches: new collections, atelier journeys, workshop dates. No noise.
          </p>
          <form className="m-foot__news" onSubmit={(e) => e.preventDefault()}>
            <input type="email" placeholder="your@email" aria-label="Email"/>
            <button type="submit" aria-label="Subscribe"><Ic.arrowLong/></button>
          </form>
          <p className="m-foot__contact">
            <a href="tel:+971507490210">+971 50 749 0210</a><br/>
            <a href="mailto:info@montroi.com">info@montroi.com</a><br/>
            WH 49 Alserkal Avenue, Al Quoz, Dubai
          </p>
        </div>
      </div>
      <div className="m-foot__bot">
        <span>© {new Date().getFullYear()} Montroi. The most valuable possessions are those with stories to tell.</span>
        <span className="m-foot__legal">
          <a href="#/legal">Privacy</a> · <a href="#/legal">Terms</a> · <a href="#/legal">Shipping</a>
        </span>
      </div>
    </footer>
  );
}
function FootCol({ heading, items, navigate }) {
  return (
    <div className="m-foot__col">
      <h4>{heading}</h4>
      <ul>
        {items.map(([href, label]) => (
          <li key={href}>
            <a href={`#${href}`} onClick={(e) => { e.preventDefault(); navigate(href); }}>{label}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ProductCard — editorial, no shouting CTA
function ProductCard({ product, onAdd, navigate, size = "M" }) {
  const [adding, setAdding] = useState(false);
  return (
    <article className={`m-card m-card--${size}`}>
      <button className="m-card__shot" onClick={() => navigate(`/product/${product.handle}`)}
              aria-label={product.title}>
        <img src={product.image} alt={product.title} loading="lazy"/>
        <span className="m-card__plus" onClick={(e) => {
          e.stopPropagation(); setAdding(true); onAdd(product);
          setTimeout(() => setAdding(false), 900);
        }}>{adding ? "Added" : "Add to bag"}</span>
      </button>
      <div className="m-card__meta">
        <span className="m-card__atelier">{product.atelier}</span>
        <h3 className="m-card__title" onClick={() => navigate(`/product/${product.handle}`)}>{product.title}</h3>
        <span className="m-card__price">${product.price.toFixed(2)} <em>USD</em></span>
      </div>
    </article>
  );
}

// ─────────────────────────────────────────────────────────────
// Section primitives
function SectionHeading({ eyebrow, title, lede, align = "left" }) {
  return (
    <header className={`m-secthd m-secthd--${align}`}>
      {eyebrow ? <span className="m-eyebrow">{eyebrow}</span> : null}
      <h2 className="m-h2">{title}</h2>
      {lede ? <p className="m-lede">{lede}</p> : null}
    </header>
  );
}

function CTA({ children, onClick, kind = "primary", as = "button", href }) {
  const cn = `m-cta m-cta--${kind}`;
  if (as === "a") {
    return <a className={cn} href={href} onClick={onClick}><span>{children}</span><Ic.arrowLong/></a>;
  }
  return <button className={cn} onClick={onClick}><span>{children}</span><Ic.arrowLong/></button>;
}

// ─────────────────────────────────────────────────────────────
// Cart drawer
function CartDrawer({ open, onClose, items, setItems, navigate }) {
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <div className={`m-cart ${open ? "is-open" : ""}`} aria-hidden={!open}>
      <div className="m-cart__scrim" onClick={onClose}></div>
      <aside className="m-cart__panel" aria-label="Shopping bag">
        <div className="m-cart__head">
          <span className="m-eyebrow">Your bag</span>
          <button onClick={onClose} className="m-nav__util" aria-label="Close"><Ic.close/></button>
        </div>
        <div className="m-cart__body">
          {items.length === 0 ? (
            <div className="m-cart__empty">
              <p>Your bag is quiet. Begin with the collection.</p>
              <CTA kind="ghost" onClick={() => { onClose(); navigate("/shop"); }}>Browse the shop</CTA>
            </div>
          ) : items.map((it) => (
            <div key={it.handle} className="m-cart__line">
              <img src={it.image} alt=""/>
              <div className="m-cart__lineMeta">
                <span className="m-card__atelier">{it.atelier}</span>
                <h4>{it.title}</h4>
                <div className="m-cart__qty">
                  <button onClick={() => setItems(items.map(x => x.handle === it.handle
                    ? { ...x, qty: Math.max(1, x.qty - 1) } : x))}>−</button>
                  <span>{it.qty}</span>
                  <button onClick={() => setItems(items.map(x => x.handle === it.handle
                    ? { ...x, qty: x.qty + 1 } : x))}>+</button>
                  <button className="m-cart__rm" onClick={() =>
                    setItems(items.filter(x => x.handle !== it.handle))}>Remove</button>
                </div>
              </div>
              <span className="m-cart__linePrice">${(it.price * it.qty).toFixed(2)}</span>
            </div>
          ))}
        </div>
        {items.length > 0 ? (
          <div className="m-cart__foot">
            <div className="m-cart__sub">
              <span>Subtotal</span><span>${subtotal.toFixed(2)} USD</span>
            </div>
            <p className="m-cart__ship">
              Complimentary worldwide shipping on orders over $200. Furniture excluded.
            </p>
            <CTA kind="primary">Continue to checkout</CTA>
            <button className="m-cart__cont" onClick={onClose}>Continue browsing</button>
          </div>
        ) : null}
      </aside>
    </div>
  );
}

window.MONTROI_COMP = {
  Logo, Ic, Navbar, Footer, ProductCard, SectionHeading, CTA, CartDrawer,
};
