// ─────────── East Wind Social Club — UI components ───────────
const { useState, useEffect, useRef } = React;

function formatMoney(amount, currencyCode = "USD") {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: currencyCode, maximumFractionDigits: 2 }).format(Number(amount || 0));
}

function ProductVisual({ product, className = "" }) {
  const Graphic = product?.graphic ? GARMENT_GRAPHICS[product.graphic] : null;
  if (Graphic) return <Graphic />;
  if (product?.image) return <img className={"ew-product-img " + className} src={product.image} alt={product.imageAlt || product.name || "East Wind product"} loading="lazy" />;
  return <div className="ew-product-fallback"><EastMark size={64} ring="#C9A66B" char="#0F2A44" /></div>;
}

// The 東 ring mark — the brand icon
function EastMark({ size = 44, ring = "#0F2A44", char = "#0F2A44", strokeW = 1.3 }) {
  const r = size / 2;
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" aria-label="East Wind">
      <circle cx="50" cy="50" r="46" fill="none" stroke={ring} strokeWidth={strokeW} />
      <circle cx="50" cy="50" r="41" fill="none" stroke={ring} strokeWidth={strokeW * 0.45} opacity="0.6" />
      <text x="50" y="68" fontFamily="Noto Serif SC, serif" fontSize="54" fontWeight="700" fill={char} textAnchor="middle">東</text>
    </svg>
  );
}

// Full stacked lockup — 東 ring + script + caps
function LogoStack({ ring = "#F2EAD3", script = "#F2EAD3", caps = "#C9A66B", scale = 1 }) {
  return (
    <svg width={300 * scale} height={250 * scale} viewBox="0 0 300 250" aria-label="East Wind Social Club">
      <g transform="translate(150, 68)">
        <circle r="52" fill="none" stroke={ring} strokeWidth="1.2" />
        <circle r="46" fill="none" stroke={ring} strokeWidth="0.5" opacity="0.6" />
        <text x="0" y="20" fontFamily="Noto Serif SC, serif" fontSize="62" fontWeight="700" fill={ring} textAnchor="middle">東</text>
      </g>
      <text x="150" y="182" fontFamily="Pinyon Script, cursive" fontSize="66" fill={script} textAnchor="middle">East Wind</text>
      <text x="150" y="214" fontFamily="Bodoni Moda, serif" fontWeight="400" fontSize="17" fill={caps} textAnchor="middle" letterSpacing="11">SOCIAL CLUB</text>
    </svg>
  );
}

function Button({ children, variant = "solid", onClick, full, type = "button", small, disabled }) {
  const cls = ["ew-btn", `ew-btn--${variant}`, full ? "ew-btn--full" : "", small ? "ew-btn--sm" : ""].join(" ");
  return <button type={type} className={cls} onClick={onClick} disabled={disabled}>{children}</button>;
}

// ─────────── Announcement bar ───────────
const ANNOUNCEMENTS = [
  "East starts the game.",
  "Complimentary shipping over $120 · Members first.",
  "Spring Drop 01 — limited runs, numbered.",
  "Tiles in, phones down, rosé poured.",
];
function AnnouncementBar() {
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI(v => (v + 1) % ANNOUNCEMENTS.length), 4200);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="ew-announce">
      <span className="ew-announce__dot">·</span>
      <span key={i} className="ew-announce__text">{ANNOUNCEMENTS[i]}</span>
      <span className="ew-announce__dot">·</span>
    </div>
  );
}

// ─────────── Header ───────────
function Header({ route, onNav, cartCount, onCart, scrolled }) {
  const link = (to, label) => (
    <button className={"ew-nav__link" + (route.name === to ? " is-active" : "")} onClick={() => onNav({ name: to })}>{label}</button>
  );
  return (
    <header className={"ew-header" + (scrolled ? " is-scrolled" : "")}>
      <nav className="ew-nav">
        <div className="ew-nav__group ew-nav__group--left">
          {link("shop", "Shop")}
          {link("the-line", "The Line")}
          {link("cities", "Cities")}
          {link("story", "Our Story")}
        </div>
        <button className="ew-nav__brand" onClick={() => onNav({ name: "home" })} aria-label="East Wind Social Club — home">
          <EastMark size={38} />
          <span className="ew-nav__wordmark">East Wind<em>Social Club</em></span>
        </button>
        <div className="ew-nav__group ew-nav__group--right">
          {link("club", "The Club")}
          <button className="ew-nav__icon" aria-label="Search">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="11" cy="11" r="7" /><line x1="16.5" y1="16.5" x2="21" y2="21" /></svg>
          </button>
          <button className="ew-nav__cart" onClick={onCart} aria-label="Cart">
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M5 8 h14 l-1.2 12 a1 1 0 0 1 -1 1 H7.2 a1 1 0 0 1 -1 -1 Z" /><path d="M9 8 V6.5 a3 3 0 0 1 6 0 V8" /></svg>
            {cartCount > 0 && <span className="ew-nav__cart-count">{cartCount}</span>}
          </button>
        </div>
      </nav>
    </header>
  );
}

// ─────────── Product card ───────────
function ProductCard({ product, onOpen, onQuickAdd, eager }) {
  const [hover, setHover] = useState(false);
  return (
    <article className="ew-card" onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <div className="ew-card__media" style={{ background: product.cardBg }} onClick={() => onOpen(product)} role="button" aria-label={`View ${product.name}`}>
        {product.badge && <span className="ew-card__badge">{product.badge}</span>}
        <div className="ew-card__garment"><ProductVisual product={product} /></div>
        <div className={"ew-card__quickadd" + (hover ? " is-shown" : "")} onClick={e => e.stopPropagation()}>
          <Button variant="solid" full small disabled={!product.availableForSale} onClick={() => onQuickAdd(product)}>
            {product.availableForSale ? `Quick add — ${formatMoney(product.price, product.currencyCode)}` : "Sold out"}
          </Button>
        </div>
      </div>
      <button className="ew-card__body" onClick={() => onOpen(product)}>
        <div className="ew-card__row">
          <h3 className="ew-card__name">{product.name}</h3>
          <span className="ew-card__price">{formatMoney(product.price, product.currencyCode)}</span>
        </div>
        <div className="ew-card__meta">
          <span className="ew-card__sub">{product.sub}</span>
          <span className="ew-card__sw" style={{ background: product.swatch || "var(--rope)" }} title={product.colorway}></span>
          <span className="ew-card__cw">{product.colorway}</span>
        </div>
      </button>
    </article>
  );
}

// ─────────── Cart drawer ───────────
function CartDrawer({ open, items, subtotal, currencyCode = "USD", busy, error, onClose, onQty, onRemove, onCheckout, onNav }) {
  const computedSubtotal = subtotal ?? items.reduce((s, it) => s + it.price * it.qty, 0);
  const freeAt = 120;
  const toFree = Math.max(0, freeAt - computedSubtotal);
  const pct = Math.min(100, (computedSubtotal / freeAt) * 100);
  return (
    <>
      <div className={"ew-scrim" + (open ? " is-open" : "")} onClick={onClose}></div>
      <aside className={"ew-cart" + (open ? " is-open" : "")} aria-hidden={!open}>
        <header className="ew-cart__head">
          <span className="ew-cart__title">Your Tiles <em>({items.reduce((s, i) => s + i.qty, 0)})</em></span>
          <button className="ew-cart__close" onClick={onClose} aria-label="Close cart">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
          </button>
        </header>

        {items.length > 0 && (
          <div className="ew-cart__ship">
            {toFree > 0
              ? <p>You're <strong>{formatMoney(toFree, currencyCode)}</strong> from complimentary shipping.</p>
              : <p>You've unlocked <strong>complimentary shipping.</strong></p>}
            <div className="ew-cart__track"><div className="ew-cart__fill" style={{ width: pct + "%" }}></div></div>
          </div>
        )}

        <div className="ew-cart__body">
          {items.length === 0 ? (
            <div className="ew-cart__empty">
              <EastMark size={56} ring="#C9A66B" char="#0F2A44" />
              <p>Your hand is empty.</p>
              <span>Every game begins with East. Start yours.</span>
              <Button variant="solid" onClick={() => { onClose(); onNav({ name: "shop" }); }}>Shop the line</Button>
            </div>
          ) : items.map(it => {
            return (
              <div className="ew-line" key={it.key}>
                <div className="ew-line__media" style={{ background: it.cardBg || "#EDE6D2" }}><ProductVisual product={it} /></div>
                <div className="ew-line__info">
                  <div className="ew-line__top">
                    <h4>{it.name}</h4>
                    <button className="ew-line__x" disabled={busy} onClick={() => onRemove(it.key)} aria-label="Remove">✕</button>
                  </div>
                  <p className="ew-line__sub">{it.colorway} · Size {it.size}</p>
                  <div className="ew-line__bottom">
                    <div className="ew-qty">
                      <button disabled={busy} onClick={() => onQty(it.key, -1)} aria-label="Decrease">−</button>
                      <span>{it.qty}</span>
                      <button disabled={busy} onClick={() => onQty(it.key, 1)} aria-label="Increase">+</button>
                    </div>
                    <span className="ew-line__price">{formatMoney(it.lineTotal ?? it.price * it.qty, currencyCode)}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {items.length > 0 && (
          <footer className="ew-cart__foot">
            <div className="ew-cart__sub"><span>Subtotal</span><span>{formatMoney(computedSubtotal, currencyCode)}</span></div>
            <p className="ew-cart__note">Shipping & taxes calculated at checkout.</p>
            {error && <p className="ew-cart__error" role="alert">{error}</p>}
            <Button variant="solid" full disabled={busy} onClick={onCheckout}>{busy ? "Updating…" : "Checkout"}</Button>
            <button className="ew-cart__cont" onClick={onClose}>Continue shopping</button>
          </footer>
        )}
      </aside>
    </>
  );
}

// ─────────── Footer ───────────
function Footer({ onNav }) {
  return (
    <footer className="ew-foot">
      <div className="ew-foot__top">
        <div className="ew-foot__brand">
          <LogoStack scale={0.92} />
          <p className="ew-foot__tag">A social club for everyone who plays.</p>
        </div>
        <div className="ew-foot__cols">
          <div className="ew-foot__col">
            <h5>Shop</h5>
            <button onClick={() => onNav({ name: "shop" })}>All garments</button>
            <button onClick={() => onNav({ name: "the-line" })}>The Line</button>
          </div>
          <div className="ew-foot__col">
            <h5>Brand</h5>
            <button onClick={() => onNav({ name: "story" })}>Our story</button>
            <button onClick={() => onNav({ name: "cities" })}>Cities</button>
            <button onClick={() => onNav({ name: "club" })}>The Club</button>
            <button onClick={() => onNav({ name: "cities", focus: "request" })}>Request a city</button>
            <button onClick={() => onNav({ name: "contact" })}>Contact us</button>
          </div>
          <div className="ew-foot__col ew-foot__col--news">
            <h5>Join the table</h5>
            <p>First looks at every drop, and an invitation to the next game.</p>
            <form className="ew-news" onSubmit={e => e.preventDefault()}>
              <input type="email" placeholder="Your email" aria-label="Email" />
              <button type="submit" aria-label="Subscribe">→</button>
            </form>
          </div>
        </div>
      </div>
      <div className="ew-foot__bar">
        <span>East Wind Social Club · Est. MMXXVI</span>
        <span className="ew-foot__links">
          <a href="#">Shipping</a><a href="#">Returns</a><a href="#">Care</a><a href="#">Contact</a>
        </span>
        <span>© 2026 — Made in U.S.A.</span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  EastMark, LogoStack, Button, AnnouncementBar, Header, ProductCard, CartDrawer, Footer, ProductVisual, formatMoney,
});
