// ─────────── East Wind Social Club — Shop / Product / Story / Club ───────────

function ShopPage({ products, catalogError, onOpen, onQuickAdd }) {
  const cats = ["All", ...Array.from(new Set(products.map(product => product.category)))];
  const [cat, setCat] = useState("All");
  const shown = cat === "All" || !cats.includes(cat) ? products : products.filter(p => p.category === cat);
  return (
    <div className="ew-page">
      <header className="ew-pagehead">
        <span className="ew-kicker">The shop</span>
        <h1 className="ew-pagehead__title">The whole hand.</h1>
        <p className="ew-pagehead__lede">The current East Wind collection — live pricing, colors, sizes, and availability direct from the studio.</p>
      </header>
      {catalogError && <p className="ew-commerce-alert" role="alert">Live Shopify inventory is temporarily unavailable: {catalogError}</p>}
      <div className="ew-filter">
        {cats.map(c => (
          <button key={c} className={"ew-chip" + (cat === c ? " is-active" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
        <span className="ew-filter__count">{shown.length} pieces</span>
      </div>
      <div className="ew-grid ew-grid--3 ew-shopgrid">
        {shown.map(p => <ProductCard key={p.id} product={p} onOpen={onOpen} onQuickAdd={onQuickAdd} />)}
      </div>
    </div>
  );
}

// ─────────── Product detail ───────────
const COLOR_SWATCHES = {
  bone: "#E8DFCA", blush: "#F3CDC5", sage: "#A8B89C", powder: "#B9CBDC",
  white: "#F8F7F2", black: "#181818", natural: "#DCCDAF", pink: "#E7B7C5",
  "light pink": "#EECAD3", "light blue": "#B8D2E5", gray: "#85898C", "silver gray": "#B6B8B8",
};

function colorSwatch(name) {
  return COLOR_SWATCHES[String(name || "").toLowerCase()] || "#C9A66B";
}

function Accordion({ title, children, open: open0 }) {
  const [open, setOpen] = useState(!!open0);
  return (
    <div className={"ew-acc" + (open ? " is-open" : "")}>
      <button className="ew-acc__head" onClick={() => setOpen(o => !o)}>
        <span>{title}</span><span className="ew-acc__pm">{open ? "–" : "+"}</span>
      </button>
      {open && <div className="ew-acc__body">{children}</div>}
    </div>
  );
}

function ProductPage({ product, products, cartBusy, onAdd, onOpen, onNav }) {
  const [size, setSize] = useState(null);
  const [color, setColor] = useState(product.colors?.[0] || product.colorway);
  const [qty, setQty] = useState(1);
  const [err, setErr] = useState(false);
  const related = products.filter(p => p.id !== product.id).slice(0, 3);
  const selectedVariant = size ? ShopifyStore.findVariant(product, size, color) : null;
  const unitPrice = selectedVariant?.price ?? product.price;

  useEffect(() => {
    setSize(null);
    setColor(product.colors?.[0] || product.colorway);
    setQty(1);
    setErr(false);
  }, [product.id]);

  const add = () => {
    if (!size) { setErr(true); return; }
    if (!selectedVariant?.availableForSale) { setErr(true); return; }
    onAdd(product, size, qty, color);
  };

  const quickAddRelated = (relatedProduct) => {
    const relatedSize = relatedProduct.sizes?.find(value => value.toLowerCase() === "m") || relatedProduct.sizes?.[0] || "One Size";
    onAdd(relatedProduct, relatedSize, 1, relatedProduct.colors?.[0] || relatedProduct.colorway);
  };

  return (
    <div className="ew-page ew-pdp">
      <button className="ew-back" onClick={() => onNav({ name: "shop" })}>← Back to shop</button>
      <div className="ew-pdp__grid">
        {/* MEDIA */}
        <div className="ew-pdp__media">
          <div className="ew-pdp__hero" style={{ background: product.cardBg }}>
            {product.badge && <span className="ew-card__badge">{product.badge}</span>}
            <ProductVisual product={{ ...product, image: selectedVariant?.image || product.image }} />
          </div>
          <div className="ew-pdp__thumbs">
            <div className="ew-pdp__thumb is-active" style={{ background: product.cardBg }}><ProductVisual product={product} /></div>
            <div className="ew-pdp__thumb" style={{ background: "#0F2A44" }}>
              <span className="ew-pdp__thumblabel">東</span>
            </div>
            <image-slot id={"pdp-" + product.id} class="ew-pdp__thumb ew-pdp__thumb--slot" shape="rounded" radius="2" placeholder="On-body"></image-slot>
          </div>
        </div>

        {/* INFO */}
        <div className="ew-pdp__info">
          <div className="ew-pdp__crumbs"><span>{product.category}</span><span className="ew-pdp__run">Live Shopify inventory</span></div>
          <h1 className="ew-pdp__name">{product.name}</h1>
          <p className="ew-pdp__tag">{product.tagline}</p>
          <div className="ew-pdp__price">{formatMoney(unitPrice, product.currencyCode)}</div>

          <p className="ew-pdp__story">{product.story}</p>

          <div className="ew-pdp__block">
            <div className="ew-pdp__blabel"><span>Colorway</span><em>{color}</em></div>
            <div className="ew-pdp__sws">
              {product.colors.map(nm => (
                <button key={nm} className={"ew-pdp__sw" + (nm === color ? " is-active" : "")} style={{ background: colorSwatch(nm) }}
                  onClick={() => { setColor(nm); setErr(false); }} title={nm} aria-label={nm}></button>
              ))}
            </div>
          </div>

          <div className="ew-pdp__block">
            <div className="ew-pdp__blabel"><span>Size</span><a href="#" onClick={e => e.preventDefault()}>Size guide</a></div>
            <div className="ew-pdp__sizes">
              {product.sizes.map(s => {
                const variant = ShopifyStore.findVariant(product, s, color);
                const soldOut = variant && !variant.availableForSale;
                return <button key={s} disabled={!variant || soldOut}
                  className={"ew-size" + (size === s ? " is-active" : "") + (err && !size ? " is-err" : "") + (soldOut ? " is-soldout" : "")}
                  onClick={() => { setSize(s); setErr(false); }}>{String(s).toUpperCase()}</button>;
              })}
            </div>
            {err && <span className="ew-pdp__errmsg">{!size ? "Please choose a size." : "That variant is currently sold out."}</span>}
          </div>

          <div className="ew-pdp__buy">
            <div className="ew-qty ew-qty--lg">
              <button onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease">−</button>
              <span>{qty}</span>
              <button onClick={() => setQty(q => q + 1)} aria-label="Increase">+</button>
            </div>
            <Button variant="solid" full disabled={cartBusy || !product.availableForSale} onClick={add}>
              {cartBusy ? "Adding…" : product.availableForSale ? `Add to bag — ${formatMoney(unitPrice * qty, product.currencyCode)}` : "Sold out"}
            </Button>
          </div>
          <p className="ew-pdp__ship">◷ Ships in 3–5 days · Complimentary over $120 · Members ship free</p>

          <div className="ew-pdp__accs">
            <Accordion title="Details & fit" open>
              <ul className="ew-pdp__list">
                <li><span>Garment</span>{product.garment}</li>
                <li><span>Fabric</span>{product.fabric}</li>
                <li><span>Color</span>{color}</li>
                <li><span>Availability</span>{product.availableForSale ? "Available" : "Sold out"}</li>
              </ul>
            </Accordion>
            <Accordion title="The mark on this piece">
              <p>{product.story}</p>
            </Accordion>
            <Accordion title="Shipping & returns">
              <p>Numbered runs ship within 3–5 business days. Complimentary returns within 30 days on unworn pieces with the 東 hangtag attached.</p>
            </Accordion>
          </div>
        </div>
      </div>

      {/* RELATED */}
      <section className="ew-related">
        <div className="ew-sec-head">
          <h2 className="ew-sec-title">Complete the hand.</h2>
          <button className="ew-sec-link" onClick={() => onNav({ name: "shop" })}>Shop all →</button>
        </div>
        <div className="ew-grid ew-grid--3">
          {related.map(p => <ProductCard key={p.id} product={p} onOpen={onOpen} onQuickAdd={quickAddRelated} />)}
        </div>
      </section>
    </div>
  );
}

// ─────────── The Line (drop landing) ───────────
function TheLinePage({ products, onOpen, onQuickAdd, onNav }) {
  return (
    <div className="ew-page">
      <header className="ew-drophero">
        <span className="ew-kicker ew-kicker--gold">Spring · Drop 01</span>
        <h1 className="ew-drophero__title"><em>The Line.</em></h1>
        <p className="ew-drophero__lede">The complete East Wind collection, drawn from the table and made for everyone who throws the tiles.</p>
        <Button variant="line" onClick={() => onNav({ name: "shop" })}>Shop the drop ↓</Button>
      </header>
      <div className="ew-linelist">
        {products.map((p, i) => {
          return (
            <article className={"ew-row" + (i % 2 ? " ew-row--flip" : "")} key={p.id}>
              <button className="ew-row__media" style={{ background: p.cardBg }} onClick={() => onOpen(p)}>
                <ProductVisual product={p} />
              </button>
              <div className="ew-row__copy">
                <span className="ew-row__no">No. {String(i + 1).padStart(2, "0")}</span>
                <h3 className="ew-row__name">{p.name}</h3>
                <p className="ew-row__tag">{p.tagline}</p>
                <p className="ew-row__story">{p.story}</p>
                <div className="ew-row__meta">
                  <span>{p.garment}</span><span className="ew-row__dot">·</span>
                  <span>{p.colorway}</span><span className="ew-row__dot">·</span>
                  <span>{formatMoney(p.price, p.currencyCode)}</span>
                </div>
                <Button variant="line" onClick={() => onOpen(p)}>View piece →</Button>
              </div>
            </article>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Story ───────────
function StoryPage({ onNav }) {
  return (
    <div className="ew-page ew-storypage">
      <header className="ew-storypage__hero">
        <LogoStack ring="#0F2A44" script="#0F2A44" caps="#A98548" scale={1.3} />
        <p className="ew-storypage__tag">East starts the game.</p>
      </header>
      <section className="ew-storypage__lead">
        <span className="ew-kicker ew-kicker--gold">Our story</span>
        <p>It began during a season when I needed connection the most — and found it around a mahjong table.</p>
      </section>
      <section className="ew-storynarr">
        <div className="ew-storynarr__col">
          <p>East Wind Social Club was born after I became a mom, deep in the beautiful chaos of motherhood. Learning mahjong with my mother-in-law gave me something I didn't know I was missing: a reason to gather, to slow down, to reconnect with friends and family.</p>
          <p>What started around a table became something bigger — a social club built on community, conversation, and the simple joy of spending time together.</p>
        </div>
        <div className="ew-storynarr__col">
          <p>Our pieces are inspired by the game that brought us together, and by the people who make time for themselves, their friendships, and their communities.</p>
          <p className="ew-storynarr__sign">East starts the game.<span>— the founder</span></p>
        </div>
      </section>
      <section className="ew-storypage__why">
        <div className="ew-storypage__char"><span>東</span></div>
        <div>
          <h2>One character, endlessly repeatable.</h2>
          <p>東 is the character for East — and in mahjong, East is the dealer; East is where every game begins. It carries the game and the heritage in a single brushstroke, and stands on its own: the icon on the avatar, the tag, the sleeve. Legible at one inch.</p>
        </div>
      </section>
      <section className="ew-give">
        <div className="ew-give__seal">
          <svg width="120" height="120" viewBox="0 0 100 100"><circle cx="50" cy="50" r="46" fill="none" stroke="#C9A66B" strokeWidth="1.3" /><text x="50" y="68" fontFamily="Noto Serif SC, serif" fontSize="52" fontWeight="700" fill="#F2EAD3" textAnchor="middle">東</text></svg>
        </div>
        <span className="ew-kicker ew-kicker--gold">Every hand gives back</span>
        <h2 className="ew-give__title">A seat at the table, for more women.</h2>
        <p className="ew-give__body">A portion of every purchase supports organizations that combat maternal isolation and create opportunities for women to build meaningful community — because no one should have to play alone.</p>
      </section>
      <section className="ew-storycta">
        <Button variant="solid" onClick={() => onNav({ name: "shop" })}>Shop the line</Button>
      </section>
    </div>
  );
}

// ─────────── Club ───────────
function ClubPage({ onNav }) {
  const perks = [
    ["First deal", "Shop every numbered drop before it opens to the public — and lock your size before it sells out."],
    ["A standing table", "An invitation to hosted games in your city. Tiles, rosé, and a room of fellow players."],
    ["The founding hangtag", "Members for Drop 01 receive the numbered 東 hangtag — proof you were here first."],
    ["Members ship free", "Complimentary shipping and returns on everything, every time, no minimum."],
  ];
  return (
    <div className="ew-page ew-clubpage">
      <header className="ew-clubhero">
        <EastMark size={92} ring="#C9A66B" char="#F2EAD3" />
        <span className="ew-kicker ew-kicker--gold">Membership</span>
        <h1 className="ew-clubhero__title">Pull up a chair.</h1>
        <p className="ew-clubhero__lede">East Wind is a label and a club. Three hundred founding seats for 2026 — first access, a place at the table, and the hangtag that proves it.</p>
        <div className="ew-clubhero__seats"><strong>142</strong> of 300 founding seats remain</div>
      </header>
      <section className="ew-perks">
        {perks.map(([t, d], i) => (
          <div className="ew-perk" key={t}>
            <span className="ew-perk__no">{String(i + 1).padStart(2, "0")}</span>
            <h3>{t}</h3>
            <p>{d}</p>
          </div>
        ))}
      </section>
      <section className="ew-join">
        <div className="ew-join__card">
          <span className="ew-kicker">Founding membership</span>
          <div className="ew-join__price"><span>$0</span><em>/ join free for Drop 01</em></div>
          <form className="ew-join__form" onSubmit={e => e.preventDefault()}>
            <input type="text" placeholder="First name" aria-label="First name" />
            <input type="email" placeholder="Email address" aria-label="Email" />
            <Button variant="solid" full type="submit">Claim a founding seat</Button>
          </form>
          <p className="ew-join__fine">No card required to hold a seat. We'll write before the next game.</p>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { ShopPage, ProductPage, TheLinePage, StoryPage, ClubPage });
