/* global React */
const { useState, useEffect, useRef, useMemo, useContext, createContext } = React;

/* =========================================================
   App context — cart, lang, density, palette, navigation
   ========================================================= */
const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

/* =========================================================
   Hash routing
   ========================================================= */
function parseHash() {
  const raw = (location.hash || "#/").replace(/^#/, "");
  const [path, query = ""] = raw.split("?");
  const params = Object.fromEntries(new URLSearchParams(query));
  const segments = path.split("/").filter(Boolean);
  return { path: "/" + segments.join("/"), segments, params };
}
function useRoute() {
  const [route, setRoute] = useState(parseHash());
  useEffect(() => {
    const on = () => { setRoute(parseHash()); window.scrollTo({ top: 0, behavior: "instant" }); };
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return route;
}
function navigate(path) {
  location.hash = "#" + path;
}

/* =========================================================
   Currency formatter — USD verbatim (no invention)
   ========================================================= */
function fmtUSD(n) {
  return n.toFixed(2).replace(/\.00$/, "");
}

/* =========================================================
   Logo / sparrow mark
   ========================================================= */
function SparrowMark({ size = 28, color = "currentColor", className = "" }) {
  return (
    <svg viewBox="0 0 674 460" width={size * 1.46} height={size} className={className} aria-hidden="true">
      <path d="M553.3,0L573.3,0L593.3,0L613.3,13.3L633.3,20L653.3,26.7L673.3,33.3L660,40L640,53.3L620,73.3L606.7,93.3L606.7,113.3L600,133.3L606.7,153.3L613.3,173.3L613.3,193.3L620,213.3L620,233.3L613.3,253.3L613.3,273.3L600,293.3L586.7,313.3L566.7,326.7L546.7,340L526.7,353.3L506.7,360L486.7,366.7L466.7,380L473.3,400L466.7,420L446.7,426.7L426.7,426.7L420,413.3L426.7,393.3L420,373.3L400,373.3L380,373.3L360,373.3L340,373.3L320,366.7L300,366.7L280,360L260,360L240,366.7L220,373.3L200,380L180,393.3L160,400L140,413.3L120,426.7L100,433.3L80,446.7L60,453.3L40,460L20,460L0,460L20,446.7L40,433.3L60,420L80,406.7L100,400L120,386.7L140,380L160,373.3L180,360L200,346.7L220,333.3L240,320L260,313.3L280,300L300,286.7L320,266.7L340,253.3L360,233.3L380,220L400,200L420,180L440,160L453.3,140L466.7,120L480,100L486.7,80L493.3,60L506.7,40L520,20L540,6.7Z" fill={color}/>
    </svg>
  );
}

function Logo({ size = 24, onClick }) {
  return (
    <a className="nav-logo" href="#/" onClick={(e) => { if (onClick) onClick(e); }}>
      <SparrowMark size={size} color="var(--primary)" />
      <span className="wordmark">Orient 499</span>
    </a>
  );
}

/* =========================================================
   Navigation
   ========================================================= */
function Nav() {
  const { route, lang, setLang, cart, openCart } = useApp();
  const path = route.path;
  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const [mobOpen, setMobOpen] = useState(false);
  useEffect(() => { setMobOpen(false); }, [path]);

  const links = [
    { p: "/story",        en: "The Story",      ar: "الحكاية" },
    { p: "/fashion",      en: "Fashion",        ar: "الأزياء" },
    { p: "/home-decor",   en: "Home & Décor",   ar: "المنزل والديكور" },
    { p: "/sustainability", en: "Sustainability", ar: "الاستدامة" },
    { p: "/journal",      en: "Journal",        ar: "اليوميات" },
    { p: "/boutique",     en: "Boutique",       ar: "البوتيك" },
  ];

  const isActive = (p) => path === p || (p !== "/" && path.startsWith(p));

  return (
    <header className="nav">
      <div className="nav-inner">
        <div className="nav-left">
          {links.slice(0, 3).map((l) => (
            <a key={l.p} className={"nav-link" + (isActive(l.p) ? " active" : "")} href={"#" + l.p}>
              {lang === "ar" ? l.ar : l.en}
            </a>
          ))}
          <button className="mob-toggle nav-link" onClick={() => setMobOpen(!mobOpen)} aria-label="Menu">Menu</button>
        </div>
        <div className="nav-center">
          <Logo />
        </div>
        <div className="nav-right">
          {links.slice(3).map((l) => (
            <a key={l.p} className={"nav-link" + (isActive(l.p) ? " active" : "")} href={"#" + l.p}>
              {lang === "ar" ? l.ar : l.en}
            </a>
          ))}
          <div className="lang-switch" role="tablist" aria-label="Language">
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "ar" ? "active" : ""} onClick={() => setLang("ar")}>ع</button>
          </div>
          <button className="nav-link cart-btn" onClick={openCart}>
            Bag <span className="count">{cartCount}</span>
          </button>
        </div>
      </div>
      {mobOpen && (
        <div style={{ borderTop: "1px solid var(--border)", padding: "16px var(--pad-edge)", background: "var(--surface)" }}>
          {links.map((l) => (
            <a key={l.p} className="nav-link" href={"#" + l.p}
               style={{ display: "block", padding: "10px 0" }}>
              {lang === "ar" ? l.ar : l.en}
            </a>
          ))}
        </div>
      )}
    </header>
  );
}

/* =========================================================
   Footer
   ========================================================= */
function Footer() {
  const { contact, social } = window.O499.contact;
  const c = window.O499.contact;
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-col foot-brand">
            <SparrowMark size={36} color="var(--primary)" />
            <div className="ww">ORIENT 499</div>
            <p>Sustainable Lebanese craft — slow-made fashion & handmade décor co-created with master artisans since 2006.</p>
          </div>
          <div className="foot-col">
            <h4>House</h4>
            <ul>
              <li><a href="#/story">The Story</a></li>
              <li><a href="#/story#artisans">Master Artisans</a></li>
              <li><a href="#/sustainability">Sustainability</a></li>
              <li><a href="#/journal">Journal</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h4>Shop</h4>
            <ul>
              <li><a href="#/fashion">Fashion</a></li>
              <li><a href="#/home-decor">Home & Décor</a></li>
              <li><a href="#/fashion?filter=ooak">One-of-a-kind</a></li>
              <li><a href="#/contact?topic=bespoke">Bespoke enquiries</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h4>Visit</h4>
            <ul>
              <li>The Yard, WH 48a<br/>Alserkal Avenue, Al Quoz 3<br/>Dubai, UAE</li>
              <li style={{ marginTop: 12 }}>499 Omar Daouk Street<br/>Mina El Hosn, Beirut</li>
            </ul>
          </div>
          <div className="foot-col">
            <h4>Contact</h4>
            <ul>
              <li><a href={"tel:" + c.phoneRaw}>{c.phone}</a></li>
              <li><a href={"mailto:" + c.email}>{c.email}</a></li>
              <li style={{ marginTop: 12 }}>
                <a href={c.social.instagram} target="_blank" rel="noopener noreferrer">Instagram</a>
                {" · "}
                <a href={c.social.facebook} target="_blank" rel="noopener noreferrer">Facebook</a>
              </li>
              <li style={{ marginTop: 14 }}><a href="#/contact" className="btn-link">Enquire <span className="arrow"></span></a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2006 – 2026 · Orient 499 · Beirut → Dubai</span>
          <span>Prices in USD · Verified</span>
        </div>
      </div>
    </footer>
  );
}

/* =========================================================
   Product card
   ========================================================= */
function ProductCard({ p, eager = false }) {
  return (
    <a className="pc" href={"#/product/" + p.id}>
      <div className="pc-frame">
        <img src={p.img} alt={p.name} loading={eager ? "eager" : "lazy"} />
        {p.ooak && <span className="badge ooak">One of a kind</span>}
        <span className="quick">View piece</span>
      </div>
      <div className="pc-meta">
        <span className="pc-detail">{p.type} · {p.material.split("·")[0].trim()}</span>
        <span className="pc-name">{p.name}</span>
        <span className="pc-price"><span className="currency">$</span>{fmtUSD(p.price)} <span style={{ color: "var(--muted)", fontSize: 11, letterSpacing: "0.16em" }}>USD</span></span>
      </div>
    </a>
  );
}

/* =========================================================
   Cart drawer
   ========================================================= */
function CartDrawer() {
  const { cart, cartOpen, closeCart, addToCart, removeFromCart, setQty } = useApp();
  const total = cart.reduce((s, it) => s + it.price * it.qty, 0);
  return (
    <React.Fragment>
      <div className={"drawer-back" + (cartOpen ? " open" : "")} onClick={closeCart}></div>
      <aside className={"drawer" + (cartOpen ? " open" : "")} aria-hidden={!cartOpen} aria-label="Bag">
        <div className="drawer-head">
          <div>
            <div className="eyebrow gold">Your bag</div>
            <div className="title">{cart.length} {cart.length === 1 ? "piece" : "pieces"}</div>
          </div>
          <button onClick={closeCart} className="nav-link">Close ×</button>
        </div>
        <div className="drawer-body">
          {cart.length === 0 && (
            <div style={{ padding: "48px 0", textAlign: "center", color: "var(--muted)" }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--text)", marginBottom: 12 }}>The bag is empty.</div>
              <div style={{ fontSize: 13 }}>Begin with the collection — every piece is hand-made and named.</div>
              <div style={{ marginTop: 24 }}>
                <a href="#/fashion" className="btn-link" onClick={closeCart}>Browse the collection <span className="arrow"></span></a>
              </div>
            </div>
          )}
          {cart.map((it) => (
            <div key={it.id} className="cart-row">
              <img src={it.img} alt={it.name} />
              <div>
                <div className="nm">{it.name}</div>
                <div className="det">{it.type} · {it.material.split("·")[0].trim()}</div>
                <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 8 }}>
                  <div className="qty" style={{ display: "inline-flex" }}>
                    <button onClick={() => setQty(it.id, it.qty - 1)} aria-label="Less">−</button>
                    <span className="n">{it.qty}</span>
                    <button onClick={() => setQty(it.id, it.qty + 1)} aria-label="More">+</button>
                  </div>
                  <button onClick={() => removeFromCart(it.id)} style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--muted)", textDecoration: "underline" }}>Remove</button>
                </div>
              </div>
              <div className="pr"><span style={{ color: "var(--muted)" }}>$</span>{fmtUSD(it.price * it.qty)}</div>
            </div>
          ))}
        </div>
        {cart.length > 0 && (
          <div className="drawer-foot">
            <div className="tot">
              <span style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", alignSelf: "center" }}>Subtotal · USD</span>
              <span className="num">${fmtUSD(total)}</span>
            </div>
            <p style={{ fontSize: 12, color: "var(--muted)", margin: "0 0 16px" }}>
              Checkout completes on our Shopify boutique. Shipping calculated at next step.
            </p>
            <a href="https://orient499.com/cart" target="_blank" rel="noopener" className="btn btn-gold" style={{ width: "100%", justifyContent: "center" }} onClick={closeCart}>
              Proceed to checkout
            </a>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
}

/* =========================================================
   Toast
   ========================================================= */
function Toast() {
  const { toast } = useApp();
  return <div className={"toast" + (toast ? " show" : "")}>{toast}</div>;
}

/* =========================================================
   Section header
   ========================================================= */
function SectionHeader({ chapter, eyebrow, title, right }) {
  return (
    <div className="sec-header">
      <div className="left">
        {chapter && <span className="chapter">{chapter}</span>}
        {eyebrow && <span className="eyebrow gold">{eyebrow}</span>}
      </div>
      <h2 className="display-l">{title}</h2>
      {right && <div className="right">{right}</div>}
    </div>
  );
}

/* =========================================================
   Sparrow divider
   ========================================================= */
function SparrowDivider() {
  return (
    <div className="sparrow-divider">
      <span className="ln"></span>
      <SparrowMark size={22} color="var(--primary)" />
      <span className="ln"></span>
    </div>
  );
}

/* =========================================================
   Marquee strip
   ========================================================= */
function Marquee({ items }) {
  const doubled = items.concat(items);
  return (
    <div className="marq">
      <div className="marq-track">
        {doubled.map((t, i) => <span key={i} className="marq-item">{t}</span>)}
      </div>
    </div>
  );
}

/* =========================================================
   Placeholder (warm-striped) — for flagged missing imagery
   ========================================================= */
function Placeholder({ label, aspect = "4 / 5", style = {}, stockSeed, stockTags }) {
  // If a stockSeed is given, show a real stock photo (Lorem Picsum,
  // seeded → deterministic) instead of the striped placeholder, with a small
  // "stock stand-in" pill so it stays honest.
  if (stockSeed) {
    const ratio = (typeof aspect === "string" && aspect.includes("/"))
      ? aspect.split("/").map(s => parseFloat(s.trim()))
      : [4, 5];
    const w = 1000, h = Math.round(w * (ratio[1] / ratio[0]));
    const src = `https://picsum.photos/seed/${encodeURIComponent(stockSeed)}/${w}/${h}`;
    return (
      <div className="standin" style={{ aspectRatio: aspect, ...style }}>
        <img src={src} alt="" loading="lazy" />
        <span className="standin-tag">{stockTags || "Stock stand-in · to replace"}</span>
      </div>
    );
  }
  return (
    <div className="ph" style={{ aspectRatio: aspect, ...style }}>
      <span className="ph-label">{label}</span>
    </div>
  );
}

/* =========================================================
   Notice (for hours/landline conflicts)
   ========================================================= */
function Notice({ children }) {
  return <div className="notice">{children}</div>;
}

/* Expose to other files */
Object.assign(window, {
  AppCtx, useApp, useRoute, navigate, parseHash,
  fmtUSD, SparrowMark, Logo, Nav, Footer, ProductCard, CartDrawer,
  SectionHeader, SparrowDivider, Marquee, Placeholder, Notice, Toast
});
