/* CLOTHIXPACK — shared shell: ticker + nav + cart drawer + footer.
   Cart persists to localStorage as `cxp.cart`.
   Exposes: window.Shell { Ticker, Nav, CartDrawer, Foot }
            window.useCart() hook
            window.openCart() / closeCart() globals (set by CartDrawer)
*/

const { useState, useEffect, useCallback } = React;

/* -------------------- cart store -------------------- */
const CART_KEY = "cxp.cart";
function loadCart() {
  try { return JSON.parse(localStorage.getItem(CART_KEY)) || []; } catch { return []; }
}
function saveCart(items) {
  localStorage.setItem(CART_KEY, JSON.stringify(items));
  window.dispatchEvent(new CustomEvent("cxp:cart", { detail: items }));
}
function cartItemKey(item) {
  const base = `${item.code}/${item.size}/${item.color}`;
  if (!item.customSize) return base;
  return `${base}/${JSON.stringify({
    fit: item.customFit || "",
    unit: item.measurementUnit || "",
    measurements: item.measurements || {},
    notes: item.customNotes || "",
  })}`;
}

function useCart() {
  const [items, setItems] = useState(loadCart);
  useEffect(() => {
    const on = (e) => setItems(e.detail);
    const onStorage = () => setItems(loadCart());
    window.addEventListener("cxp:cart", on);
    window.addEventListener("storage", onStorage);
    return () => { window.removeEventListener("cxp:cart", on); window.removeEventListener("storage", onStorage); };
  }, []);
  const add = useCallback((item) => {
    const cur = loadCart();
    const key = cartItemKey(item);
    const idx = cur.findIndex(i => cartItemKey(i) === key);
    if (idx >= 0) { cur[idx].qty += item.qty || 1; }
    else { cur.push({ ...item, qty: item.qty || 1 }); }
    saveCart(cur);
    window.openCart && window.openCart();
  }, []);
  const update = useCallback((key, qty) => {
    const cur = loadCart().map(i => cartItemKey(i) === key ? { ...i, qty } : i).filter(i => i.qty > 0);
    saveCart(cur);
  }, []);
  const remove = useCallback((key) => {
    saveCart(loadCart().filter(i => cartItemKey(i) !== key));
  }, []);
  const count = items.reduce((s, i) => s + i.qty, 0);
  const subtotal = items.reduce((s, i) => s + i.qty * i.price, 0);
  return { items, add, update, remove, count, subtotal };
}

/* -------------------- ticker -------------------- */
function Ticker() {
  const items = [
    "AW26 COLLECTION LIVE",
    "CANADIAN-REGISTERED HOUSE",
    "INTERNATIONAL PRODUCTION WORKFLOW",
    "TRACKED SHIPPING OPTIONS",
    "CANADIAN-REGISTERED HOUSE",
  ];
  return (
    <div className="ticker ticker-static">
      <div className="ticker-track">
        {items.map((item, i) => (
          <span className="ticker-item" key={i}>{item}</span>
        ))}
      </div>
    </div>
  );
}

/* -------------------- nav -------------------- */
function Nav({ active = "home" }) {
  const { count } = useCart();
  return (
    <header className="nav">
      <div className="nav-inner">
        <div className="nav-left">
          <a className={"nav-link" + (active==="shop"?" active":"")} href="/shop">Shop</a>
          <a className={"nav-link" + (active==="lookbook"?" active":"")} href="/lookbook">Lookbook</a>
          <a className={"nav-link" + (active==="about"?" active":"")} href="/about">About</a>
          <a className={"nav-link" + (active==="atelier"?" active":"")} href="/atelier">Atelier</a>
          <a className={"nav-link" + (active==="journal"?" active":"")} href="/journal">Journal</a>
        </div>
        <a className="brand" href="/" aria-label="Clothixpack home">
          <img className="brand-logo" src="assets/clothixpack-logo-nav.png" alt="Clothixpack" />
        </a>
        <div className="nav-right">
          <button className="icon-btn" aria-label="Search">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
            Search
          </button>
          <button className="nav-link">EN / USD</button>
          <button className="icon-btn" onClick={() => window.openCart && window.openCart()} aria-label="Open cart">
            Cart {count > 0 && <span className="cart-count">{count}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

/* -------------------- cart drawer -------------------- */
function CartDrawer() {
  const [open, setOpen] = useState(false);
  const [finalSaleAccepted, setFinalSaleAccepted] = useState(false);
  const { items, update, remove, subtotal } = useCart();

  useEffect(() => {
    window.openCart = () => setOpen(true);
    window.closeCart = () => setOpen(false);
    return () => { window.openCart = null; window.closeCart = null; };
  }, []);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
  }, [open]);

  useEffect(() => {
    if (!items.length) setFinalSaleAccepted(false);
  }, [items.length]);

  return (
    <>
      <div className={"drawer-scrim" + (open ? " open" : "")} onClick={() => setOpen(false)}/>
      <aside className={"drawer" + (open ? " open" : "")} role="dialog" aria-label="Shopping cart">
        <div className="drawer-head">
          <div className="title">Cart · {items.length} {items.length === 1 ? "item" : "items"}</div>
          <button className="drawer-close" onClick={() => setOpen(false)} aria-label="Close cart">
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2 2 L10 10 M10 2 L2 10"/></svg>
          </button>
        </div>

        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="cart-empty">
              <div className="e-glyph">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 7h12l-1.5 12h-9z"/><path d="M9 7V5a3 3 0 016 0v2"/></svg>
              </div>
              <div className="mono lbl">Empty cargo</div>
              <p style={{margin: 0, fontSize: 13}}>Nothing's loaded in yet. Pick a piece and lock it in.</p>
              <a href="/shop" className="btn" style={{marginTop: 16}}>Browse the drop <span className="arrow">→</span></a>
            </div>
          ) : items.map((i, idx) => {
            const key = cartItemKey(i);
            const measurementSummary = i.customSize && i.measurements
              ? Object.entries(i.measurements)
                .slice(0, 6)
                .map(([label, value]) => `${label}: ${value}${i.measurementUnit || ""}`)
                .join(" · ")
              : "";
            return (
              <div className="cart-item" key={idx}>
                <div className="thumb">
                  <div style={{position:"absolute", inset:0, display:"flex", alignItems:"center", justifyContent:"center"}}>
                    <window.Silhouette cat={i.cat} view="front"/>
                  </div>
                </div>
                <div>
                  <div className="ci-name">{i.name}</div>
                  <div className="ci-code">{i.code}</div>
                  <div className="ci-opts">{i.size} · {i.color}</div>
                  {i.customSize && (
                    <div className="ci-custom">
                      <span>{i.customFit || "Custom fit"}</span>
                      {measurementSummary && <span>{measurementSummary}</span>}
                      {i.customNotes && <span>{i.customNotes}</span>}
                    </div>
                  )}
                  <div className="qty">
                    <button onClick={() => update(key, i.qty - 1)}>−</button>
                    <div className="v">{i.qty}</div>
                    <button onClick={() => update(key, i.qty + 1)}>+</button>
                  </div>
                </div>
                <div style={{textAlign:"right", display:"flex", flexDirection:"column", alignItems:"flex-end", gap:6}}>
                  <div className="ci-price">${(i.price * i.qty).toLocaleString()}</div>
                  <button className="ci-remove" onClick={() => remove(key)}>Remove</button>
                </div>
              </div>
            );
          })}
        </div>

        {items.length > 0 && (
          <div className="drawer-foot">
            <div className="totals-row"><span>Subtotal</span><span>${subtotal.toLocaleString()}</span></div>
            <div className="totals-row"><span>Shipping</span><span>Canada delivery only · calculated at checkout</span></div>
            <div className="totals-row grand"><span>Total</span><span className="v">${subtotal.toLocaleString()}</span></div>
            <label className="cart-policy-check">
              <input
                type="checkbox"
                checked={finalSaleAccepted}
                onChange={(event) => setFinalSaleAccepted(event.target.checked)}
              />
              <span>I understand eligible returns or exchanges follow the Refund &amp; Return Policy and Canada delivery terms. Made-to-measure orders are cut to my submitted measurements.</span>
            </label>
            <button className="btn primary block" disabled={!finalSaleAccepted}>Checkout <span className="arrow">→</span></button>
            <div className="lbl" style={{textAlign:"center"}}>Final sale · Tracked shipping options · Secure / SSL</div>
          </div>
        )}
      </aside>
    </>
  );
}

/* -------------------- footer -------------------- */
function Foot() {
  return (
    <footer className="foot">
      <div className="col">
        <div className="brand" style={{marginBottom: 20}}>
          <img className="brand-logo footer-brand-logo" src="assets/clothixpack-logo-nav.png" alt="Clothixpack" />
        </div>
        <p style={{maxWidth: 320, color: "var(--text-mute)", fontSize: 14, marginTop: 0}}>
          Canadian-registered technical citywear house. Built through an international production workflow with tracked shipping options.
        </p>
        <nav className="foot-social" aria-label="Social media and inquiry channels">
          <a className="foot-social-link" href="https://www.instagram.com/clothixpack" target="_blank" rel="noopener noreferrer" aria-label="Clothixpack on Instagram">
            <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="4"></rect><circle cx="12" cy="12" r="3.35"></circle><path d="M16.7 7.3h.1"></path></svg>
            <span className="sr-only">Instagram</span>
          </a>
          <a className="foot-social-link" href="https://www.tiktok.com/@clothixpack" target="_blank" rel="noopener noreferrer" aria-label="Clothixpack on TikTok">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14.5 4v9.25a3.85 3.85 0 1 1-3.85-3.85"></path><path d="M14.5 6.8c1.15 1.85 2.5 2.8 4.25 2.95"></path></svg>
            <span className="sr-only">TikTok</span>
          </a>
          <a className="foot-social-link" href="https://www.youtube.com/@clothixpack" target="_blank" rel="noopener noreferrer" aria-label="Clothixpack on YouTube">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.8 7.2c1.9-.4 10.5-.4 12.4 0 1 .2 1.7 1 1.9 2.1.25 1.35.25 4.05 0 5.4-.2 1.1-.9 1.9-1.9 2.1-1.9.4-10.5.4-12.4 0-1-.2-1.7-1-1.9-2.1-.25-1.35-.25-4.05 0-5.4.2-1.1.9-1.9 1.9-2.1Z"></path><path d="m10.6 9.4 4.35 2.6-4.35 2.6Z"></path></svg>
            <span className="sr-only">YouTube</span>
          </a>
          <a className="foot-whatsapp" href="/whatsapp-inquiry?text=Inquiry%3A%20I%20need%20help%20with%20a%20Clothixpack%20order%2C%20sizing%2C%20or%20product%20selection." aria-label="Start a WhatsApp inquiry with Clothixpack">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.2 19.1 6.3 16A7.2 7.2 0 1 1 9 18.25Z"></path><path d="M9.2 8.3c.35 2.55 1.95 4.55 4.6 5.85l1.55-1.05 2.05.75c-.2 1.3-1.1 2.05-2.35 2.05-3.9 0-7.1-3.15-7.1-7.05 0-1.25.8-2.15 2.05-2.35Z"></path></svg>
            <span>WhatsApp inquiry</span>
          </a>
        </nav>
        <div className="lbl" style={{marginTop: 24}}>SYS / v4.0.26</div>
      </div>
      <div className="col">
        <h4>Shop</h4>
        <ul>
          <li><a href="/shop#jackets">Jackets</a></li>
          <li><a href="/shop#pants">Pants</a></li>
          <li><a href="/shop#shirts">Shirts</a></li>
          <li><a href="/shop#hoodies">Hoodies</a></li>
          <li><a href="/shop#skirts">Skirts</a></li>
          <li><a href="/shop#tracksuits">Tracksuits</a></li>
        </ul>
      </div>
      <div className="col">
        <h4>Index</h4>
        <ul>
          <li><a href="/about">About</a></li>
          <li><a href="/atelier">Atelier</a></li>
          <li><a href="/journal">Field Reports</a></li>
          <li><a href="/techwear">Techwear by Country</a></li>

        </ul>
      </div>
      <div className="col">
        <h4>Markets</h4>
        <ul>
          <li><a href="/techwear/united-states">USA Techwear</a></li>
          <li><a href="/techwear/germany">Germany Techwear</a></li>
          <li><a href="/techwear/japan">Japan Techwear</a></li>
          <li><a href="/techwear/europe">Europe Techwear</a></li>
          <li><a href="/techwear/canada">Canada Techwear</a></li>
        </ul>
      </div>
      <div className="col">
        <h4>Support</h4>
        <ul>
          <li><a href="/fit-consultation">Fit Consultation</a></li>
          <li><a href="/fit-consultation">Fit Consultation</a></li>
          <li><a href="/shipping">Shipping &amp; Duties</a></li>
          <li><a href="/refund-policy">Refund &amp; Return Policy</a></li>
          <li><a href="/faq">FAQ</a></li>
          <li><a href="mailto:sales@clothixpack.com">Contact</a></li>
        </ul>
      </div>
      <div className="foot-bottom">
        <div>© 2026 CLOTHIXPACK · ALL RIGHTS RESERVED</div>
        <div>REGISTERED ADDRESS · 265 BRUNSWICK AVE · LONDON ON N6G 5P8 · CANADA</div>
        <div>RETURNS / CANADA DELIVERY / SECURE CHECKOUT</div>
      </div>
    </footer>
  );
}

window.Shell = { Ticker, Nav, CartDrawer, Foot };
window.useCart = useCart;
