// Step 4 — Results view (hero screen)
function StepResults({ product, onPersist, onBack, onNew }) {
  const prices = product.competitors.filter(c => c.price_thb).map(c => c.price_thb);
  const minP = Math.min(...prices), maxP = Math.max(...prices);
  const median = prices.sort((a,b)=>a-b)[Math.floor(prices.length/2)];
  const margin = ((product.recommended[0] - product.landed.landed_thb) / product.landed.landed_thb * 100).toFixed(0);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <Chip tone="red">STEP 04</Chip>
        <Label>SYNTHESIS RESULT</Label>
        <Chip tone="ink">{product.sku}</Chip>
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
          · generated 41.0s ago · ฿{product.cost.total_thb} spent · sonnet-4.5
        </span>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <Btn size="sm" variant="ghost" onClick={onBack}>← RE-RUN</Btn>
          <Btn size="sm" variant="ghost" onClick={onNew}>+ NEW QUERY</Btn>
          <Btn size="sm" variant="ghost">EXPORT JSON ⇩</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16 }}>
        {/* LEFT: Hero recommendation */}
        <div>
          <div className="brut" style={{ padding: 20, background: 'var(--paper)', position: 'relative' }}>
            <div style={{ position: 'absolute', top: -3, right: -3, background: 'var(--red)', color: '#fff',
              border: '3px solid var(--ink)', padding: '4px 10px', fontWeight: 800, fontSize: 11,
              letterSpacing: '0.08em', fontFamily: 'JetBrains Mono, monospace' }}>
              RECOMMENDATION
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '130px 1fr', gap: 18 }}>
              <ImgPlaceholder label={product.image} size={130} tone="red" />
              <div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{product.category.toUpperCase()}</div>
                <div className="big-num" style={{ fontSize: 24, marginTop: 2 }}>{product.resolvedName}</div>
                <div className="mono" style={{ fontSize: 12, marginTop: 4 }}>{product.thai} · SKU <b>{product.sku}</b></div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
                  <Chip>HS {product.hsCode}</Chip>
                  <Chip>BRAND · {product.brand}</Chip>
                  <Chip tone="ink">{product.tier}</Chip>
                </div>
              </div>
            </div>

            <hr className="divider" style={{ margin: '18px 0' }} />

            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 20, alignItems: 'start' }}>
              <div>
                <Label>RECOMMENDED RETAIL BAND</Label>
                <div className="big-num" style={{ fontSize: 52, lineHeight: 1, marginTop: 6 }}>
                  ฿{product.recommended[0].toLocaleString()}
                  <span style={{ fontSize: 26, color: 'var(--muted)' }}> &nbsp;→&nbsp; </span>
                  ฿{product.recommended[1].toLocaleString()}
                </div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 6 }}>
                  // Floor = official store anchor · Ceiling = reseller ceiling observed
                </div>

                {/* Price band viz */}
                <div style={{ marginTop: 18 }}>
                  <div style={{ position: 'relative', height: 80 }}>
                    {/* Axis */}
                    <div style={{ position: 'absolute', left: 0, right: 0, top: 40, height: 3, background: 'var(--ink)' }} />
                    {/* Landed marker */}
                    <PriceMarker label="LANDED" value={product.landed.landed_thb} minP={minP*0.6} maxP={maxP*1.1} color="var(--ink)" top />
                    {/* Competitors */}
                    {prices.map((p, i) => (
                      <PriceMarker key={i} label="" value={p} minP={minP*0.6} maxP={maxP*1.1} color="var(--blue)" tiny />
                    ))}
                    {/* Band */}
                    <PriceBand lo={product.recommended[0]} hi={product.recommended[1]} minP={minP*0.6} maxP={maxP*1.1} />
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10 }} className="mono">
                    <span>฿{Math.round(minP*0.6).toLocaleString()}</span>
                    <span>฿{Math.round((minP*0.6 + maxP*1.1)/2).toLocaleString()}</span>
                    <span>฿{Math.round(maxP*1.1).toLocaleString()}</span>
                  </div>
                </div>
              </div>

              <div className="brut-sm" style={{ padding: 12, background: 'var(--paper-2)' }}>
                <Label>MARGIN @ FLOOR</Label>
                <div className="big-num mono" style={{ fontSize: 30 }}>{margin}%</div>
                <hr className="divider-dashed" style={{ margin: '10px 0' }}/>
                <div style={{ fontSize: 11 }} className="mono">
                  <div style={{ display:'flex', justifyContent:'space-between' }}><span>LANDED</span><span>฿{product.landed.landed_thb}</span></div>
                  <div style={{ display:'flex', justifyContent:'space-between' }}><span>MEDIAN</span><span>฿{median}</span></div>
                  <div style={{ display:'flex', justifyContent:'space-between' }}><span>SPREAD</span><span>฿{maxP-minP}</span></div>
                  <div style={{ display:'flex', justifyContent:'space-between', fontWeight: 800, marginTop: 4, paddingTop: 4, borderTop: '2px solid var(--ink)' }}>
                    <span>COMPS</span><span>{prices.length}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Landed cost breakdown */}
          <div className="brut" style={{ padding: 16, marginTop: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <Chip tone="yellow">LANDED COST MATH</Chip>
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
                // FOB × (1 + duty + VAT + transport) + extras
              </span>
              <Chip tone="ink" style={{ marginLeft: 'auto' }}>THB · CNY · USD</Chip>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 0, border: '3px solid var(--ink)' }}>
              {[
                { l: 'FOB (¥)',       v: `¥${product.landed.fob_cny}`,        s: `$${product.landed.fob_usd}` },
                { l: 'FREIGHT',       v: `฿${product.landed.freight_thb}`,    s: 'TH warehouse' },
                { l: `DUTY ${product.landed.duty_pct}%`, v: `฿${Math.round((product.landed.fob_cny*5 + product.landed.freight_thb)*product.landed.duty_pct/100)}`, s: `HS ${product.hsCode}` },
                { l: `VAT ${product.landed.vat_pct}%`,   v: `฿${Math.round((product.landed.fob_cny*5 + product.landed.freight_thb)*product.landed.vat_pct/100)}`, s: 'standard' },
                { l: 'EXTRAS',        v: `฿${product.landed.extra_thb}`,      s: 'handling + pad' },
                { l: 'LANDED',        v: `฿${product.landed.landed_thb}`,     s: 'all-in', hero: true },
              ].map((row, i) => (
                <div key={i} style={{
                  padding: 10, borderRight: i < 5 ? '3px solid var(--ink)' : 'none',
                  background: row.hero ? 'var(--red)' : 'var(--paper)',
                  color: row.hero ? '#fff' : 'var(--ink)',
                }}>
                  <div className="mono" style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.1em', opacity: row.hero ? 0.9 : 0.6 }}>{row.l}</div>
                  <div className="big-num mono" style={{ fontSize: 18, marginTop: 2 }}>{row.v}</div>
                  <div className="mono" style={{ fontSize: 9, opacity: row.hero ? 0.8 : 0.5 }}>{row.s}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Competitor table */}
          <div className="brut" style={{ padding: 0, marginTop: 16, overflow: 'hidden' }}>
            <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '10px 14px', display: 'flex', alignItems: 'center' }}>
              <Label style={{ color: 'var(--paper)' }}>COMPETITOR LISTINGS &nbsp;·&nbsp; TH MARKET</Label>
              <span className="mono" style={{ fontSize: 11, marginLeft: 'auto' }}>{product.competitors.length} rows · sourced {new Date().toISOString().slice(0,16).replace('T',' ')}</span>
            </div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>SOURCE</th><th>SELLER</th><th>TYPE</th><th style={{ textAlign:'right' }}>PRICE (฿)</th>
                  <th style={{ textAlign:'right' }}>vs LANDED</th><th>STOCK</th><th>LISTINGS</th>
                </tr>
              </thead>
              <tbody>
                {product.competitors.map((c, i) => (
                  <tr key={i} style={{ background: i%2 ? 'var(--paper-2)' : 'var(--paper)' }}>
                    <td style={{ fontWeight: 700 }}>{c.source}</td>
                    <td>{c.seller}</td>
                    <td>
                      {c.seller_type === 'official'    && <Chip tone="green">OFFICIAL</Chip>}
                      {c.seller_type === 'reseller'    && <Chip tone="blue">RESELLER</Chip>}
                      {c.seller_type === 'drop-shipper'&& <Chip tone="yellow">DROPSHIP</Chip>}
                      {c.seller_type === '—'           && <Chip>—</Chip>}
                    </td>
                    <td style={{ textAlign:'right', fontWeight: 800 }}>
                      {c.price_thb ? `฿${c.price_thb.toLocaleString()}` : <span style={{ color: 'var(--red)' }}>NO MATCH</span>}
                    </td>
                    <td style={{ textAlign:'right' }}>
                      {c.price_thb ? `${((c.price_thb/product.landed.landed_thb - 1) * 100).toFixed(0)}%` : '—'}
                    </td>
                    <td>{c.stock}</td>
                    <td>{c.listings}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* RIGHT: Confidence + warnings + china side */}
        <div>
          <div className="brut" style={{ padding: 18, background: 'var(--paper)' }}>
            <ConfidenceViz data={product.confidence} big />
            <hr className="divider-dashed" style={{ margin: '14px 0' }} />
            <div className="mono" style={{ fontSize: 11, lineHeight: 1.6 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>WHY THIS SCORE</div>
              {product.confidence.overall < 0.75
                ? <>TH coverage drags the overall down — only <b>{product.competitors.filter(c=>c.price_thb).length}</b> TH listings, no TikTok Shop anchor. Product ID itself is solid ({(product.confidence.product_identification*100).toFixed(0)}%), so the <b>ceiling</b> is thin-market, not thin-intel. Below 75% threshold → <b>log only</b>.</>
                : <>Strong TH coverage ({(product.confidence.th_market_coverage*100).toFixed(0)}%) + exact variant match ({(product.confidence.variant_match*100).toFixed(0)}%) clear the 75% bar. Safe to auto-persist to Odoo pending-review queue.</>}
            </div>
          </div>

          {/* Warnings */}
          <div className="brut on-bright" style={{ padding: 14, marginTop: 12, background: 'var(--yellow)' }}>
            <Label>WARNINGS · {product.warnings.length}</Label>
            <div style={{ marginTop: 8 }}>
              {product.warnings.map((w, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, padding: '6px 0', borderBottom: i < product.warnings.length - 1 ? '2px dashed var(--ink)' : 'none', fontSize: 12 }}>
                  <span style={{ fontWeight: 800 }}>⚠</span>
                  <span>{w}</span>
                </div>
              ))}
            </div>
          </div>

          {/* China cost side */}
          <div className="brut" style={{ padding: 0, marginTop: 12, overflow: 'hidden' }}>
            <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '8px 12px' }}>
              <Label style={{ color: 'var(--paper)' }}>CHINA COST SIDE · FOB</Label>
            </div>
            <table className="tbl">
              <thead>
                <tr><th>SRC</th><th>SUPPLIER</th><th style={{textAlign:'right'}}>¥</th><th style={{textAlign:'right'}}>$</th><th>MOQ</th></tr>
              </thead>
              <tbody>
                {product.china.map((c, i) => (
                  <tr key={i}><td>{c.source}</td><td>{c.supplier}</td>
                    <td style={{textAlign:'right',fontWeight:700}}>¥{c.price_cny}</td>
                    <td style={{textAlign:'right'}}>${c.price_usd}</td><td>{c.moq}</td></tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Persist CTA */}
          <div className="brut" style={{ padding: 14, marginTop: 12,
            background: product.confidence.overall >= 0.75 ? 'var(--green)' : 'var(--paper-2)',
            color: product.confidence.overall >= 0.75 ? '#fff' : 'var(--ink)' }}>
            <Label style={{ color: product.confidence.overall >= 0.75 ? '#fff' : undefined }}>
              PERSIST DECISION
            </Label>
            <div style={{ fontWeight: 800, fontSize: 16, marginTop: 4 }}>
              {product.confidence.overall >= 0.75
                ? '✓ AUTO-PERSIST → ODOO PENDING-REVIEW'
                : '⊘ LOG ONLY · below 75% threshold'}
            </div>
            <div className="mono" style={{ fontSize: 11, marginTop: 6, opacity: 0.85 }}>
              {product.confidence.overall >= 0.75
                ? 'Queued for human reviewer before promotion to live catalog.'
                : 'App DB only. Product catalog untouched.'}
            </div>
            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              <Btn variant={product.confidence.overall >= 0.75 ? 'ink' : 'primary'} onClick={onPersist}>
                {product.confidence.overall >= 0.75 ? 'REVIEW IN ODOO →' : 'VIEW LOG ENTRY →'}
              </Btn>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PriceMarker({ label, value, minP, maxP, color, top, tiny }) {
  const pct = ((value - minP) / (maxP - minP)) * 100;
  return (
    <div style={{
      position: 'absolute', left: `${pct}%`, transform: 'translateX(-50%)',
      top: top ? 0 : 28,
    }}>
      {tiny ? (
        <div style={{ width: 8, height: 24, background: color, border: '2px solid var(--ink)', marginTop: 16 }} />
      ) : (
        <>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700, whiteSpace: 'nowrap', background: 'var(--paper)', border: '2px solid var(--ink)', padding: '1px 4px' }}>
            {label} ฿{value}
          </div>
          <div style={{ width: 2, height: 30, background: color, margin: '2px auto 0' }} />
        </>
      )}
    </div>
  );
}
function PriceBand({ lo, hi, minP, maxP }) {
  const loPct = ((lo - minP) / (maxP - minP)) * 100;
  const hiPct = ((hi - minP) / (maxP - minP)) * 100;
  return (
    <div className="hatch-red" style={{
      position: 'absolute', left: `${loPct}%`, width: `${hiPct - loPct}%`,
      top: 30, height: 24, border: '3px solid var(--ink)',
    }} />
  );
}

window.StepResults = StepResults;
