/* global React, PAPERS, QA_SAMPLES, PaperCard, BrandStamp, PaperTexture, Icon */
const { useState, useEffect, useMemo } = React;

function ProductPage({ id, navigate, addToCart, addSample }) {
  const _LIST = (window._INDIE_CATALOG || window.PAPERS || []);
  const paper = _LIST.find(p => p.id === id) || _LIST[0];
  const gsmOptions = Object.keys(paper.price || {}).filter(k => k !== 'default').sort((a,b) => parseInt(a)-parseInt(b));
  const [selectedGsm, setSelectedGsm] = useState(gsmOptions[0] || 'default');
  const [qty, setQty] = useState(Math.max(10, paper.moq));
  const [activeThumb, setActiveThumb] = useState(0);
  const [openQa, setOpenQa] = useState(0);

  const unitPrice = (paper.price && paper.price[selectedGsm]) || paper.price_min || 0;
  const total = unitPrice * qty;

  const related = _LIST.filter(p =>
    p.id !== paper.id && (p.brand === paper.brand || p.finish === paper.finish)
  ).slice(0, 3);

  return (
    <main className="fade-in">
      {/* Breadcrumb */}
      <div className="shell">
        <nav className="crumb">
          <a onClick={() => navigate("/gallery")}>Gallery</a>
          <span className="sep">/</span>
          <a onClick={() => navigate("/gallery?brand=" + encodeURIComponent(paper.brand))}>{paper.brand}</a>
          <span className="sep">/</span>
          <span className="here">{paper.name}</span>
        </nav>
      </div>

      {/* Main product layout */}
      <div className="shell product">
        {/* LEFT — gallery */}
        <div className="product-gallery">
          <div className="main-swatch">
            <PaperTexture tone={paper.swatchTone} grain={paper.grain} />
            <image-slot
              id={`prod-${paper.id}-main`}
              placeholder={`${paper.name} — main swatch (close-up grain)`}
              shape="rect"
              style={{ position:"absolute", inset:0 }}
            />
            <div className="swatch-label">{paper.name.toUpperCase()} · {paper.gsm}GSM</div>
          </div>
          <div className="thumbs">
            {[0,1,2,3].map(i => (
              <button key={i} className={"t" + (activeThumb === i ? " is-active" : "")} onClick={() => setActiveThumb(i)}>
                <div style={{position:"relative", width:"100%", height:"100%"}}>
                  <PaperTexture tone={paper.swatchTone} grain={paper.grain} />
                  <image-slot
                    id={`prod-${paper.id}-thumb-${i}`}
                    placeholder={`${["printed sample","folded sample","grain close-up","stack edge"][i]}`}
                    shape="rect"
                    style={{ position:"absolute", inset:0 }}
                  />
                </div>
              </button>
            ))}
          </div>

          {/* Seen in the wild — mini */}
          <div style={{marginTop:32}}>
            <div className="eyebrow" style={{marginBottom: 12}}>「 Seen in the wild 」</div>
            <div className="seen-grid">
              {["Studio Tertier · Identity, 2025", "Kopikalyan · Packaging", "Selasar Books · Cover"].map((credit, i) => (
                <div key={i} className="seen-item">
                  <PaperTexture tone={shade2(paper.swatchTone, i*5-5)} grain={paper.grain} />
                  <image-slot
                    id={`prod-${paper.id}-wild-${i}`}
                    placeholder={`In-the-wild #${i+1}`}
                    shape="rect"
                    style={{position:"absolute", inset:0}}
                  />
                  <div className="credit">{credit}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT — meta */}
        <div className="product-meta">
          <div className="brand-row">
            <BrandStamp brand={paper.brand} tier={paper.brandTier} />
            <div style={{display:"flex", gap:6}}>
              {paper.eco && <span className="badge badge-eco">Eco · FSC</span>}
              {paper.brandTier === "premium" && <span className="badge badge-premium">Premium</span>}
            </div>
          </div>

          <div>
            <h1>{paper.name.split(" ")[0]} <em>{paper.name.split(" ").slice(1).join(" ")}</em></h1>
            <div className="subtitle">{paper.gsm}gsm · {paper.finish} · {paper.color}</div>
          </div>

          <p className="desc">{paper.description}</p>

          {/* Spec table */}
          <dl className="spec-table">
            <dt>Weight</dt><dd>{paper.gsm} gsm</dd>
            <dt>Finish</dt><dd>{paper.finish}</dd>
            <dt>Color tone</dt><dd>{paper.color}</dd>
            <dt>Grain</dt><dd>{paper.grain}</dd>
            <dt>Print methods</dt><dd>Offset · Digital · Letterpress</dd>
            <dt>Origin</dt><dd>{paper.origin}</dd>
            <dt>MOQ</dt><dd>{paper.moq} lembar</dd>
          </dl>

          {/* Format tabs */}
          <div>
            <div className="eyebrow" style={{marginBottom: 8}}>Gramatur · A3+</div>
            <div className="format-tabs">
              {gsmOptions.length > 0 ? gsmOptions.map(g => (
                <button key={g} className={selectedGsm === g ? "is-active" : ""} onClick={() => setSelectedGsm(g)}>
                  {g} gsm
                </button>
              )) : (
                <button className="is-active">
                  {paper.gsm || '—'} gsm
                </button>
              )}
            </div>
            <div className="mono" style={{fontSize:11, color:'var(--ink-meta)', marginTop:6}}>
              Format: A3+ (32 × 45 cm) · pre-cut
            </div>
          </div>

          {/* Quantity calculator */}
          <div className="qty-calc">
            <div className="qty-row">
              <span className="label">Quantity</span>
              <div className="qty-stepper">
                <button onClick={() => setQty(Math.max(paper.moq, qty - 10))}>−</button>
                <input
                  type="number"
                  value={qty}
                  min={paper.moq}
                  step="10"
                  onChange={(e) => setQty(Math.max(paper.moq, Number(e.target.value) || paper.moq))}
                />
                <button onClick={() => setQty(qty + 10)}>+</button>
              </div>
            </div>
            <div className="moq">Min. {paper.moq} lembar · A3+ pre-cut</div>
            <div className="total">
              <span className="formula">{qty} × Rp {unitPrice.toLocaleString("id-ID")}</span>
              <span className="grand">Rp {total.toLocaleString("id-ID")}</span>
            </div>
          </div>

          {/* Actions */}
          <div className="actions-stacked">
            <button className="btn btn-primary btn-lg btn-block" onClick={() => addToCart(paper, { format: selectedGsm, qty })}>
              Add to Cart · A3+ {selectedGsm !== 'default' ? selectedGsm + 'gsm · ' : ''}Rp {total.toLocaleString("id-ID")}
            </button>
            <button className="btn btn-outline btn-lg btn-block" onClick={() => { addSample(paper); navigate("/sample-request"); }}>
              Request Sample (Free)
            </button>
          </div>

          {/* Trust row */}
          <div className="trust-row">
            <Icon.Shield />
            <span><strong style={{color:"var(--ink)"}}>Fedrigoni Authorized Reseller</strong> · paper sampling tersedia · invoice resmi PT. Indie Kreasi Media</span>
          </div>

          {/* Tags */}
          <div className="tags-row">
            {paper.tags.map(t => <span key={t} className="tag">#{t}</span>)}
          </div>

          <a style={{fontSize:13, color:"var(--ink-meta)", borderBottom:"1px solid var(--ink-meta)", paddingBottom:2, alignSelf:"flex-start"}}>
            Ask a question →
          </a>
        </div>
      </div>

      {/* PixelIndie cross-link */}
      <div className="shell" style={{marginBlock: 32}}>
        <a className="pixelindie-link">
          <div className="px-logo"><img src="assets/pixelindie.png" alt="PixelIndie" /></div>
          <div className="pt">
            <div className="lbl">SISTER COMPANY · PIXELINDIE PRINT SHOP</div>
            <div className="ti">Mau langsung print {paper.name}? Order via PixelIndie — kertas pre-checked, lead time 2 hari kerja.</div>
          </div>
          <span className="arrow">→</span>
        </a>
      </div>

      {/* Full tech specs expand */}
      <div className="shell section" style={{paddingBlock:"32px"}}>
        <details className="expand-section">
          <summary>Full technical specs</summary>
          <div className="body">
            <dl className="tech-grid">
              <dt>Pulp source</dt><dd>{paper.eco ? "100% bamboo (FSC)" : "ECF wood pulp"}</dd>
              <dt>Opacity</dt><dd>{paper.gsm >= 200 ? "98%" : paper.gsm >= 120 ? "94%" : "88%"}</dd>
              <dt>Brightness (CIE)</dt><dd>{paper.color.includes("White") ? "145" : paper.color.includes("Cream") ? "118" : "90"}</dd>
              <dt>Bulk (cm³/g)</dt><dd>1.2</dd>
              <dt>Grain direction</dt><dd>Long grain (standard)</dd>
              <dt>pH</dt><dd>Neutral, acid-free</dd>
              <dt>ISO certification</dt><dd>9706 (long-life document)</dd>
              <dt>Ink absorption</dt><dd>{paper.finish === "Uncoated" ? "High — ideal for offset / letterpress" : "Medium — for offset & digital"}</dd>
            </dl>
          </div>
        </details>
      </div>

      {/* Related */}
      <section className="section" style={{paddingTop:0}}>
        <div className="shell">
          <div className="section-head">
            <h2>Papers that <em>pair well</em></h2>
            <a className="more">See all in {paper.brand} →</a>
          </div>
          <div className="related-grid">
            {related.map(p => (
              <PaperCard
                key={p.id}
                paper={p}
                onOpen={() => navigate("/product/" + p.id)}
                onAddCart={() => addToCart(p)}
                onToggleCompare={() => {}}
                isComparing={false}
                onRequestSample={(paper) => { addSample(paper); navigate("/sample-request"); }}
              />
            ))}
          </div>
        </div>
      </section>

      {/* Used by */}
      <section className="section" style={{paddingBlock: "0 32px"}}>
        <div className="shell">
          <div className="eyebrow" style={{marginBottom: 16}}>Used by</div>
          <div className="used-by">
            <span className="logo">studio·tertier</span>
            <span className="logo">KOPIKALYAN</span>
            <span className="logo">selasar.</span>
            <span className="logo">Pulang Books</span>
            <span className="logo">RUMA Atelier</span>
          </div>
        </div>
      </section>

      {/* Customer Q&A */}
      <section className="section">
        <div className="shell">
          <div className="section-head">
            <h2>Customer <em>Q&A</em></h2>
            <a className="more">Ask your own →</a>
          </div>
          <div className="qa">
            {QA_SAMPLES.map((qa, i) => (
              <div key={i} className="qa-item">
                <div className="q" onClick={() => setOpenQa(openQa === i ? -1 : i)}>
                  <span className="marker">Q · {String(i+1).padStart(2, "0")}</span>
                  <span style={{flex:1}}>{qa.q}</span>
                  <span style={{fontFamily:"var(--font-mono)", color:"var(--ink-meta)", fontSize:14}}>{openQa === i ? "−" : "+"}</span>
                </div>
                {openQa === i && (
                  <div className="a">
                    {qa.a}
                    <span className="by">— {qa.by}</span>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function shade2(hex, percent) {
  const h = hex.replace("#", "");
  const num = parseInt(h, 16);
  let r = (num >> 16) + Math.round(255 * percent / 100);
  let g = ((num >> 8) & 0xff) + Math.round(255 * percent / 100);
  let b = (num & 0xff) + Math.round(255 * percent / 100);
  r = Math.max(0, Math.min(255, r));
  g = Math.max(0, Math.min(255, g));
  b = Math.max(0, Math.min(255, b));
  return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
}

window.ProductPage = ProductPage;
