/* ============================================================
   LINGEA — shared components
   ============================================================ */
const { useState, useEffect, useRef } = React;

const fmt = (n) => window.LINGEA.fmt(n);

/* ---------- tiny line icons ---------- */
function Icon({ name, size = 20, stroke = 1.4 }) {
  const common = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: "currentColor", strokeWidth: stroke,
    strokeLinecap: "round", strokeLinejoin: "round",
  };
  if (name === "bag")
    return (
      <svg {...common}>
        <path d="M6 8h12l-1 12H7L6 8z" />
        <path d="M9 8V6.5a3 3 0 0 1 6 0V8" />
      </svg>
    );
  if (name === "close")
    return (<svg {...common}><path d="M5 5l14 14M19 5L5 19" /></svg>);
  if (name === "arrow")
    return (<svg {...common}><path d="M4 12h15M13 6l6 6-6 6" /></svg>);
  if (name === "minus")
    return (<svg {...common}><path d="M5 12h14" /></svg>);
  if (name === "plus")
    return (<svg {...common}><path d="M12 5v14M5 12h14" /></svg>);
  if (name === "shield")
    return (<svg {...common}><path d="M12 3l7 3v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6l7-3z" /></svg>);
  if (name === "truck")
    return (<svg {...common}><path d="M3 7h11v8H3zM14 10h4l3 3v2h-7z" /><circle cx="7" cy="17.5" r="1.6"/><circle cx="17.5" cy="17.5" r="1.6"/></svg>);
  if (name === "gem")
    return (<svg {...common}><path d="M6 4h12l3 5-9 11L3 9l3-5z" /><path d="M3 9h18M9 4l-3 5 6 11 6-11-3-5" /></svg>);
  if (name === "return")
    return (<svg {...common}><path d="M4 9h11a5 5 0 0 1 0 10H9" /><path d="M7 5L3 9l4 4" /></svg>);
  return null;
}

/* ---------- product image with graceful fallback ---------- */
function ProductImage({ product, label }) {
  const [err, setErr] = useState(false);
  const src = product.images && product.images[0];
  return (
    <div className="pimg">
      {!err && src ? (
        <img src={src} alt={product.name} onError={() => setErr(true)} loading="lazy" />
      ) : (
        <div className="ph">
          <div className="ph__ring" />
          <div className="ph__label">{label || (product.type + " — product shot")}</div>
        </div>
      )}
    </div>
  );
}

/* ---------- reveal hook: no-op. Entrance is now pure CSS (.fade-up animation),
   which is capture-safe and never leaves content hidden. Kept so page
   components can call it without change. ---------- */
function useReveal(dep) { /* intentionally empty */ }

/* ---------- Header ---------- */
function Header({ route, nav, bagCount, openBag, solid }) {
  const isHome = route.page === "home";
  const forceSolid = solid || !isHome;
  return (
    <header className={"site-head" + (forceSolid ? " solid" : "")}>
      <div className="head-inner">
        <nav className="head-nav left">
          <button className="nav-link" onClick={() => nav({ page: "collection" })}>Collection</button>
          <button className="nav-link" onClick={() => nav({ page: "story" })}>The Edition</button>
        </nav>

        <button className="wordmark" onClick={() => nav({ page: "home" })} aria-label="Lingea — home">
          Lingea
        </button>

        <nav className="head-nav right">
          <button className="nav-link" onClick={() => nav({ page: "collection" })}>Shop</button>
          <button className="nav-link bag-btn" onClick={openBag}>
            <Icon name="bag" size={19} />
            <span className="bag-count">{bagCount > 0 ? bagCount : ""}</span>
          </button>
        </nav>
      </div>
    </header>
  );
}

/* ---------- announcement bar ---------- */
function Marquee() {
  return (
    <div className="announce">
      <span>Complimentary insured overnight shipping, signature required</span>
      <span className="dot">·</span>
      <span>Edition 01 — seven pieces, made to order</span>
      <span className="dot">·</span>
      <span>White-glove 30-day returns</span>
    </div>
  );
}

/* ---------- product card ---------- */
function ProductCard({ product, nav, index = 0 }) {
  return (
    <button
      className="pcard fade-up"
      style={{ animationDelay: (index % 3) * 90 + "ms" }}
      onClick={() => nav({ page: "product", id: product.id })}
    >
      <div className="pcard-img">
        <ProductImage product={product} />
        <span className="pcard-edition">{product.edition || ""}</span>
      </div>
      <div className="pcard-meta">
        <div className="pcard-namerow">
          <h3 className="pcard-name">
            {product.name}
            {product.variant ? <span className="pcard-variant"> · {product.variant}</span> : null}
          </h3>
          <span className="pcard-price">{fmt(product.price)}</span>
        </div>
        <p className="pcard-type">{product.type}</p>
      </div>
    </button>
  );
}

/* ---------- trust row ---------- */
function TrustRow() {
  const items = [
    { icon: "truck", t: "Insured overnight", s: "FedEx priority, signature required, fully insured in transit." },
    { icon: "return", t: "White-glove returns", s: "30 days, tamper-evident security tag, prepaid and insured." },
    { icon: "gem", t: "Certified stones", s: "Independent coloured-stone reports. Exact carat & gram weights." },
    { icon: "shield", t: "Lifetime care", s: "Complimentary cleaning, re-polish and prong-check, for life." },
  ];
  return (
    <div className="trust-row">
      {items.map((it, i) => (
        <div className="trust-cell fade-up" key={i} style={{ animationDelay: i * 70 + "ms" }}>
          <span className="trust-ic"><Icon name={it.icon} size={22} stroke={1.2} /></span>
          <h4>{it.t}</h4>
          <p>{it.s}</p>
        </div>
      ))}
    </div>
  );
}

/* ---------- Bag drawer ---------- */
function BagDrawer({ open, items, products, close, setQty, remove, nav }) {
  const lines = items
    .map((it) => ({ ...it, product: products.find((p) => p.id === it.id) }))
    .filter((l) => l.product);
  const subtotal = lines.reduce((s, l) => s + l.product.price * l.qty, 0);

  return (
    <>
      <div className={"bag-scrim" + (open ? " show" : "")} onClick={close} />
      <aside className={"bag" + (open ? " open" : "")} aria-hidden={!open}>
        <div className="bag-head">
          <span className="eyebrow">Your Bag {lines.length ? `· ${lines.length}` : ""}</span>
          <button className="bag-x" onClick={close} aria-label="Close bag"><Icon name="close" size={20} /></button>
        </div>

        {lines.length === 0 ? (
          <div className="bag-empty">
            <p className="serif-quote">Your bag is empty.</p>
            <p className="body" style={{ maxWidth: 260 }}>Seven pieces make up Edition 01. Each is made to order.</p>
            <button className="btn ghost" onClick={() => { close(); nav({ page: "collection" }); }}>View the collection</button>
          </div>
        ) : (
          <>
            <div className="bag-lines">
              {lines.map((l) => (
                <div className="bag-line" key={l.key}>
                  <button className="bag-thumb" onClick={() => { close(); nav({ page: "product", id: l.product.id }); }}>
                    <ProductImage product={l.product} />
                  </button>
                  <div className="bag-line-meta">
                    <div className="bag-line-top">
                      <div>
                        <h4>{l.product.name}{l.product.variant ? <span> · {l.product.variant}</span> : null}</h4>
                        <p className="bag-line-type">{l.product.type}{l.size ? ` · Size ${l.size}` : ""}</p>
                      </div>
                      <button className="bag-remove" onClick={() => remove(l.key)}>Remove</button>
                    </div>
                    <div className="bag-line-bottom">
                      <div className="qty">
                        <button onClick={() => setQty(l.key, Math.max(1, l.qty - 1))}><Icon name="minus" size={14} /></button>
                        <span>{l.qty}</span>
                        <button onClick={() => setQty(l.key, l.qty + 1)}><Icon name="plus" size={14} /></button>
                      </div>
                      <span className="bag-line-price">{fmt(l.product.price * l.qty)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div className="bag-foot">
              <div className="bag-note"><Icon name="truck" size={16} stroke={1.3} /> Complimentary insured overnight shipping</div>
              <div className="bag-subtotal">
                <span className="eyebrow">Subtotal</span>
                <span className="bag-sub-val">{fmt(subtotal)}</span>
              </div>
              <button className="btn block" onClick={() => alert("This is a design prototype — checkout is not connected.")}>Proceed to checkout</button>
              <p className="bag-tax">Duties &amp; taxes calculated at checkout · Made to order, 3–4 weeks</p>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

/* ---------- Footer ---------- */
function Footer({ nav }) {
  return (
    <footer className="site-foot">
      <div className="wrap foot-top">
        <div className="foot-brand">
          <button className="wordmark big" onClick={() => nav({ page: "home" })}>Lingea</button>
          <p className="body" style={{ maxWidth: 320, marginTop: 18 }}>
            Colour, set in gold. A foundational edition of seven, made to order in solid 18k gold with certified coloured stones.
          </p>
        </div>

        <div className="foot-cols">
          <div className="foot-col">
            <span className="eyebrow">Collection</span>
            <button onClick={() => nav({ page: "collection", filter: "Bracelets" })}>Bracelets</button>
            <button onClick={() => nav({ page: "collection", filter: "Rings" })}>Rings</button>
            <button onClick={() => nav({ page: "collection", filter: "Brooches" })}>Brooches</button>
            <button onClick={() => nav({ page: "collection" })}>The full edition</button>
          </div>
          <div className="foot-col">
            <span className="eyebrow">House</span>
            <button onClick={() => nav({ page: "story" })}>The Edition</button>
            <button onClick={() => nav({ page: "story" })}>Materials &amp; certification</button>
            <button onClick={() => nav({ page: "story" })}>Shipping &amp; returns</button>
            <button onClick={() => nav({ page: "story" })}>Book an appointment</button>
          </div>
          <div className="foot-col news">
            <span className="eyebrow">The List</span>
            <p className="body" style={{ fontSize: 14, margin: "4px 0 14px" }}>
              Early access to Edition 02, and invitations to private viewings.
            </p>
            <form className="news-form" onSubmit={(e) => { e.preventDefault(); e.target.reset(); alert("Thank you — you're on the list."); }}>
              <input type="email" required placeholder="Email address" aria-label="Email address" />
              <button type="submit" aria-label="Subscribe"><Icon name="arrow" size={18} /></button>
            </form>
          </div>
        </div>
      </div>

      <div className="wrap foot-bottom">
        <span>© {new Date().getFullYear()} Lingea. All rights reserved.</span>
        <span className="foot-legal">
          <button>Privacy</button><button>Terms</button><button>Accessibility</button>
        </span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Icon, ProductImage, useReveal, Header, Marquee,
  ProductCard, TrustRow, BagDrawer, Footer, fmt,
});
