/* global React */
function DetailPage({ eaId, go, onBuy, user, onAuth }) {
  const [tick, setTick] = React.useState(0);
  const baseEA = (window.EAReports?.getById?.(eaId)) || window.EA_LIST.find(e => e.id === eaId) || window.EA_LIST[0];
  const [tab, setTab] = React.useState('overview');
  const ea = window.EAReports.effectiveEA(baseEA);
  const hasReport = !!ea._report;
  const r = ea._report;
  const isAdmin = window.__effAdminMode;
  const [editorOpen, setEditorOpen] = React.useState(false);

  // ── Ownership: admin sees all; otherwise check user's active orders for this EA ──
  const [owns, setOwns] = React.useState(false);
  React.useEffect(() => {
    if (isAdmin) { setOwns(true); return; }
    if (!user?.uid || !window.fb) { setOwns(false); return; }
    const unsub = window.fb.db.collection('orders')
      .where('userId', '==', user.uid)
      .where('eaId', '==', ea.id)
      .onSnapshot(snap => {
        const ok = snap.docs.some(d => {
          const o = d.data();
          return o.status === 'active' || (o.expertFiles && o.expertFiles.length > 0);
        });
        setOwns(ok);
      }, () => setOwns(false));
    return () => unsub();
  }, [user?.uid, ea.id, isAdmin]);

  // Re-render when admin overrides EAs from Firestore
  React.useEffect(() => {
    const handler = () => setTick(t => t + 1);
    window.addEventListener('eff_eas_changed', handler);
    return () => window.removeEventListener('eff_eas_changed', handler);
  }, []);

  // ── Reviews state (persisted per EA) ────────────────────────────────
  const reviewKey = `eff_reviews_${baseEA.id}`;
  const [userReviews, setUserReviews] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(reviewKey) || '[]'); }
    catch { return []; }
  });
  const [showForm, setShowForm] = React.useState(false);
  const [draftStars, setDraftStars] = React.useState(5);
  const [draftText, setDraftText] = React.useState('');

  function handleWriteClick() {
    if (!user) { onAuth?.('login'); return; }
    setShowForm(true);
  }
  function submitReview(e) {
    e.preventDefault();
    if (!draftText.trim()) return;
    const next = [{
      name: user.name || 'OPERATOR',
      stars: draftStars,
      text: draftText.trim(),
      date: 'just now',
      ts: Date.now(),
    }, ...userReviews];
    setUserReviews(next);
    localStorage.setItem(reviewKey, JSON.stringify(next));
    setDraftText(''); setDraftStars(5); setShowForm(false);
  }

  React.useEffect(() => {
    const onChange = (e) => { if (e.detail?.eaId === baseEA.id) setTick(t => t + 1); };
    const onAdminChange = () => setTick(t => t + 1);
    window.addEventListener('eff_report_changed', onChange);
    window.addEventListener('eff_admin_changed', onAdminChange);
    return () => {
      window.removeEventListener('eff_report_changed', onChange);
      window.removeEventListener('eff_admin_changed', onAdminChange);
    };
  }, [baseEA.id]);

  // Build analytics widgets from real report if available, otherwise mock
  const dailyBars = React.useMemo(() => {
    if (r?.dailyTrades && Object.keys(r.dailyTrades).length > 0) {
      const keys = Object.keys(r.dailyTrades).sort().slice(-7);
      return keys.map(k => ({ l: new Date(k).toLocaleDateString('en', { weekday: 'narrow' }), v: r.dailyTrades[k] }));
    }
    return [
      { l: 'M', v: 12 }, { l: 'T', v: 18 }, { l: 'W', v: 8 }, { l: 'T', v: 24 },
      { l: 'F', v: 16 }, { l: 'S', v: 4 }, { l: 'S', v: 0 },
    ];
  }, [r]);

  const heatmap = React.useMemo(() => {
    if (r?.symbolStats) {
      return Object.entries(r.symbolStats)
        .sort((a, b) => b[1].profit - a[1].profit)
        .slice(0, 8)
        .map(([pair, s]) => ({ pair, v: Math.max(0, Math.round(s.profit)) }));
    }
    return ea.pairs.map(p => ({ pair: p, v: Math.floor(450 + Math.random() * 800) }));
  }, [r, ea.pairs]);

  return (
    <div>
      {/* Header */}
      <section style={{ padding: '40px 0 24px' }}>
        <div className="container">
          <div className="flex gap-2 mb-4" style={{ fontSize: 12 }}>
            <a className="text-muted" onClick={() => go('marketplace')} style={{ cursor: 'pointer' }}>// Marketplace</a>
            <span className="text-muted">/</span>
            <span className="text-cyan font-mono">{ea.name.toUpperCase()}</span>
          </div>

          <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 32 }}>
            <div>
              <div className="flex gap-3 mb-4">
                <span className="tag">{ea.strategy}</span>
                {ea.badge && <span className="tag tag-magenta">{ea.badge}</span>}
                {hasReport
                  ? <span className="tag tag-green">VERIFIED BACKTEST · {r.dealCount?.toLocaleString()} trades</span>
                  : <span className="tag tag-green">VERIFIED BACKTEST</span>}
              </div>
              <h1 style={{ fontSize: 56, lineHeight: 1 }}>{ea.name}</h1>
              <p className="mt-4 text-muted" style={{ fontSize: 18 }}>{ea.tagline}</p>
              <div className="flex gap-2 mt-4" style={{ flexWrap: 'wrap' }}>
                {ea.pairs.map(p => <span key={p} className="font-mono" style={{ fontSize: 12, padding: '4px 10px', background: 'rgba(0,229,255,0.06)', borderRadius: 4, border: '1px solid var(--line)' }}>{p}</span>)}
              </div>

              {/* Hero EA image gallery */}
              <div className="mt-6">
                <EAImageGallery eaId={ea.id} name={ea.name} height={360}/>
              </div>
            </div>
            <div className="flex-col gap-4">
              <BuyWidget ea={ea} onBuy={onBuy}/>
              {isAdmin && (
                <>
                  <button className="btn btn-magenta btn-sheen" onClick={() => setEditorOpen(true)} style={{ width: '100%' }}>
                    ✎ Edit EA fields (admin)
                  </button>
                  <EAReportUploader ea={ea} onChange={() => setTick(t => t + 1)}/>
                </>
              )}
              {editorOpen && isAdmin && (
                <EAEditor ea={ea} onClose={() => setEditorOpen(false)}/>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Backtest snapshot — KPIs */}
      <section style={{ padding: '24px 0' }}>
        <div className="container">
          <InlineAnalytics ea={ea}/>
        </div>
      </section>

      {/* Tabs */}
      <section style={{ padding: '24px 0' }}>
        <div className="container">
          <div className="flex gap-2 mb-6" style={{ borderBottom: '1px solid var(--line)' }}>
            {['overview', 'analytics', 'parameters', 'reviews'].map(t => (
              <button key={t} className="btn btn-sm" style={{
                background: 'transparent', borderRadius: 0,
                borderBottom: tab === t ? '2px solid var(--cyan)' : '2px solid transparent',
                color: tab === t ? 'var(--cyan)' : 'var(--text-3)',
                padding: '12px 20px'
              }} onClick={() => setTab(t)}>{t}</button>
            ))}
          </div>

          {tab === 'overview' && (
            <div className="grid grid-2">
              <div className="panel panel-padded">
                <span className="eyebrow">STRATEGY</span>
                <h3 className="mt-4" style={{ fontSize: 22 }}>How it works</h3>
                <p className="mt-4 text-muted" style={{ whiteSpace: 'pre-wrap' }}>
                  {ea.overviewDescription || `${ea.name} runs a ${ea.strategy.toLowerCase()} approach on ${ea.pairs.join(', ')}. The system uses adaptive volatility filters (ATR + Bollinger) and an internal news avoidance window. Position sizing is calculated from your account equity with a hard floor at 0.01 lots.`}
                </p>
                <div className="divider"/>
                <h4 style={{ fontSize: 14, color: 'var(--cyan)', fontFamily: 'var(--font-mono)' }}>SPECIFICATIONS</h4>
                <div className="mt-4 flex-col gap-3">
                  {[
                    ['Platform', 'MetaTrader 5'],
                    ['Timeframe', r?.info?.period || 'H1 / H4'],
                    ['Min Deposit', '$500'],
                    ['Recommended', `$${(r?.initialBalance || 2000).toLocaleString()}+`],
                    ['Broker Type', r?.info?.broker || 'ECN / Raw Spread'],
                    ['Leverage', r?.info?.leverage || '1:100 → 1:500'],
                    ['VPS Required', 'Recommended for 24/7'],
                  ].map(([k, v]) => (
                    <div key={k} className="flex-between text-sm">
                      <span className="text-muted">{k}</span>
                      <span className="font-mono">{v}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="flex-col gap-4">
                <div className="panel panel-padded">
                  <span className="eyebrow">WHAT'S INCLUDED</span>
                  <div className="mt-4 flex-col gap-3">
                    {[
                      'Compiled .ex5 file (lifetime license)',
                      '.set files for each supported pair',
                      'Full backtest report (PDF + .csv)',
                      'AI Agent profile for this EA',
                      'Setup video walkthrough (12 min)',
                      'Priority support · 24h response',
                      'Free lifetime updates',
                    ].map(item => (
                      <div key={item} className="flex gap-3" style={{ alignItems: 'center' }}>
                        <span style={{ color: 'var(--green)', fontFamily: 'var(--font-mono)' }}>✓</span>
                        <span className="text-sm">{item}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="panel panel-padded">
                  <span className="eyebrow">SOCIAL PROOF</span>
                  <div className="grid grid-3 mt-4">
                    <div><div className="display text-cyan" style={{ fontSize: 24 }}><CountUp to={ea.users}/></div><div className="text-xs text-muted mt-2">Active users</div></div>
                    <div><div className="display text-green" style={{ fontSize: 24 }}><CountUp to={ea.trades}/></div><div className="text-xs text-muted mt-2">Total trades</div></div>
                    <div><div className="display" style={{ fontSize: 24, color: 'var(--magenta)' }}>{ea.age}</div><div className="text-xs text-muted mt-2">In production</div></div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {tab === 'analytics' && (
            <div className="grid grid-2">
              <div className="panel panel-padded">
                <div className="flex-between mb-4">
                  <div><span className="eyebrow">EQUITY CURVE · BACKTEST</span><div className="text-muted text-sm mt-2">{hasReport ? `${r.curveFull?.toLocaleString() || r.dealCount?.toLocaleString()} data points` : '12 months · ICMarkets tick data'}</div></div>
                  <span className="tag tag-green">{hasReport ? `${r.returnPct >= 0 ? '+' : ''}${r.returnPct.toFixed(1)}%` : `+${((ea.curve[ea.curve.length-1] / ea.curve[0] - 1) * 100).toFixed(1)}%`}</span>
                </div>
                <div style={{ height: 260 }}><EquityCurve data={ea.curve} height={260} showAxis animated={false}/></div>
                {hasReport && (
                  <div className="grid grid-4 mt-4" style={{ gap: 8 }}>
                    <div><div className="stat-label" style={{ fontSize: 9 }}>Initial</div><div className="font-mono text-cyan mt-1">${r.initialBalance.toFixed(2)}</div></div>
                    <div><div className="stat-label" style={{ fontSize: 9 }}>Final</div><div className="font-mono text-green mt-1">${r.finalBalance.toFixed(2)}</div></div>
                    <div><div className="stat-label" style={{ fontSize: 9 }}>Profit</div><div className="font-mono text-green mt-1">+${r.totalProfit.toFixed(2)}</div></div>
                    <div><div className="stat-label" style={{ fontSize: 9 }}>Sharpe</div><div className="font-mono mt-1" style={{ color: 'var(--magenta)' }}>{r.sharpe.toFixed(2)}</div></div>
                  </div>
                )}
              </div>
              <div className="panel panel-padded">
                <span className="eyebrow">TRADE DISTRIBUTION</span>
                <h4 className="mt-2 text-muted text-sm">By weekday{hasReport ? ` · last 7 days` : ` · ${dailyBars.reduce((s, d) => s + d.v, 0)}-trade sample`}</h4>
                <Bars data={dailyBars} height={220}/>
              </div>
              <div className="panel panel-padded">
                <span className="eyebrow">PROFIT BY PAIR</span>
                <h4 className="mt-2 text-muted text-sm">{hasReport ? `From real backtest · ${Object.keys(r.symbolStats).length} pair(s)` : 'Backtest split · supported pairs'}</h4>
                <div className="mt-4"><Heatmap data={heatmap}/></div>
              </div>
              <div className="panel panel-padded">
                <span className="eyebrow">METRICS</span>
                <div className="grid grid-2 mt-4" style={{ gap: 16 }}>
                  <div style={{ display: 'grid', placeItems: 'center' }}>
                    <Donut value={parseFloat(ea.winRate.toFixed(1))} color="#00E5FF" sub="Win Rate"/>
                  </div>
                  <div style={{ display: 'grid', placeItems: 'center' }}>
                    <Donut value={Math.min(99, ea.pf * 40)} color="#00FF94" sub="Profit Factor"/>
                  </div>
                </div>
                <div className="grid grid-2 mt-6">
                  <div><div className="stat-label">Avg Win</div><div className="font-mono text-green text-lg mt-2">+${(r?.avgWin || 42.18).toFixed(2)}</div></div>
                  <div><div className="stat-label">Avg Loss</div><div className="font-mono text-red text-lg mt-2">-${Math.abs(r?.avgLoss || 19.82).toFixed(2)}</div></div>
                  <div><div className="stat-label">Best Win</div><div className="font-mono text-green text-lg mt-2">+${(r?.bestWin || 287.40).toFixed(2)}</div></div>
                  <div><div className="stat-label">Worst Loss</div><div className="font-mono text-red text-lg mt-2">-${Math.abs(r?.worstLoss || 124.50).toFixed(2)}</div></div>
                </div>
                {hasReport && (
                  <>
                    <div className="divider"/>
                    <div className="grid grid-2" style={{ gap: 12 }}>
                      <div><div className="stat-label">Max consec. wins</div><div className="font-mono text-green text-lg mt-2">{r.maxConsecutiveWins}</div></div>
                      <div><div className="stat-label">Max consec. losses</div><div className="font-mono text-red text-lg mt-2">{r.maxConsecutiveLosses}</div></div>
                    </div>
                  </>
                )}
              </div>

              {/* Deals table if report */}
              {hasReport && r.deals?.length > 0 && (
                <div className="panel panel-padded" style={{ gridColumn: '1 / -1' }}>
                  <div className="flex-between mb-4">
                    <div>
                      <span className="eyebrow">DEAL HISTORY</span>
                      <h3 className="mt-2" style={{ fontSize: 18 }}>{r.dealCount?.toLocaleString()} closed deals · showing latest {r.deals.length}</h3>
                    </div>
                  </div>
                  <div style={{ overflowX: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                      <thead>
                        <tr style={{ borderBottom: '1px solid var(--line)' }}>
                          {['Time', 'Symbol', 'Type', 'Volume', 'Profit'].map(h => (
                            <th key={h} className="font-mono" style={{ textAlign: 'left', padding: '12px 8px', color: 'var(--text-3)', fontSize: 10, letterSpacing: '0.15em' }}>{h.toUpperCase()}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {r.deals.slice(-30).reverse().map((d, i) => (
                          <tr key={i} style={{ borderBottom: '1px solid var(--line-soft)' }}>
                            <td style={{ padding: '12px 8px' }} className="font-mono text-muted">{d.time instanceof Date ? d.time.toLocaleString('en', { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : String(d.time)}</td>
                            <td style={{ padding: '12px 8px', fontWeight: 600 }}>{d.symbol || '—'}</td>
                            <td style={{ padding: '12px 8px' }}><span className={`tag ${d.type === 'buy' ? 'tag-green' : 'tag-red'}`} style={{ fontSize: 9 }}>{(d.type || '—').toUpperCase()}</span></td>
                            <td style={{ padding: '12px 8px' }} className="font-mono">{d.volume ? d.volume.toFixed(2) : '—'}</td>
                            <td style={{ padding: '12px 8px' }} className={`font-mono ${d.profit >= 0 ? 'text-green' : 'text-red'}`}>{d.profit >= 0 ? '+' : ''}${d.profit.toFixed(2)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}
            </div>
          )}

          {tab === 'parameters' && (
            <div className="panel panel-padded-lg">
              <span className="eyebrow">DEFAULT PARAMETERS</span>
              <h3 className="mt-4" style={{ fontSize: 22 }}>.set file preview</h3>
              <p className="mt-2 text-muted text-sm">These ship as the recommended profile. The AI Agent will tune them to your account.</p>
              {(() => {
                const lockPill = (
                  <div className="lock-msg">
                    <span className="lock-pill">
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                      You don't have permission to view these settings until you own this EA.
                    </span>
                  </div>
                );

                if (ea.parametersText) {
                  const preBase = { background: 'rgba(0,0,0,0.5)', fontSize: 13, lineHeight: 1.8, color: 'var(--text)', whiteSpace: 'pre-wrap', overflow: 'auto', margin: 0 };
                  const lines = ea.parametersText.split('\n');
                  const head = lines.slice(0, 3).join('\n');
                  const rest = lines.slice(3).join('\n');
                  if (owns || !rest.trim()) {
                    return <pre className="font-mono mt-6" style={{ ...preBase, padding: 20, borderRadius: 8, border: '1px solid var(--line)' }}>{ea.parametersText}</pre>;
                  }
                  return (
                    <div className="mt-6" style={{ background: 'rgba(0,0,0,0.5)', borderRadius: 8, border: '1px solid var(--line)', overflow: 'hidden' }}>
                      <pre className="font-mono" style={{ ...preBase, padding: '20px 20px 6px' }}>{head}</pre>
                      <div className="locked-params">
                        <pre className="font-mono locked-blur" style={{ ...preBase, padding: '0 20px 20px' }}>{rest}</pre>
                        {lockPill}
                      </div>
                    </div>
                  );
                }

                const rows = [
                  { k: 'RiskPerTrade', v: '1.0' },
                  { k: 'LotSize', v: '0.01' },
                  { k: 'MaxLot', v: '2.0' },
                  { k: 'StopLoss', v: '250' },
                  { k: 'TakeProfit', v: '400' },
                  { k: 'UseTrailingStop', v: 'true', bool: true },
                  { k: 'TrailDistance', v: '120' },
                  { k: 'ATRPeriod', v: '14' },
                  { k: 'NewsFilter', v: 'true', bool: true },
                  { k: 'MagicNumber', v: '12345' },
                  { k: 'SlippagePoints', v: '30' },
                  { k: 'SpreadLimit', v: '25' },
                ];
                const Row = (row, i) => (
                  <div key={i}>
                    <span style={{ color: 'var(--cyan)' }}>{row.k}</span>
                    <span className="text-muted">=</span>
                    <span style={{ color: row.bool ? 'var(--magenta)' : 'var(--green)' }}>{row.v}</span>
                  </div>
                );
                return (
                  <div className="font-mono mt-6" style={{ background: 'rgba(0,0,0,0.5)', padding: 20, borderRadius: 8, fontSize: 13, border: '1px solid var(--line)', lineHeight: 1.8 }}>
                    <div><span className="text-muted">; {ea.name} v2.4 — recommended.set</span></div>
                    {rows.slice(0, 2).map(Row)}
                    {owns ? rows.slice(2).map(Row) : (
                      <div className="locked-params" style={{ marginTop: 2 }}>
                        <div className="locked-blur">{rows.slice(2).map(Row)}</div>
                        {lockPill}
                      </div>
                    )}
                  </div>
                );
              })()}
              <button className="btn btn-ghost mt-6">Download .set file</button>
            </div>
          )}

          {tab === 'reviews' && (
            <div>
              {/* Aggregate header + write CTA */}
              <div className="panel panel-padded mb-6">
                <div className="flex-between" style={{ flexWrap: 'wrap', gap: 16 }}>
                  <div>
                    <span className="eyebrow">CUSTOMER REVIEWS</span>
                    <h3 className="mt-2" style={{ fontSize: 22 }}>{(userReviews.length + 4)} reviews · <span className="text-amber">★ 4.8</span></h3>
                    <p className="text-muted text-sm mt-2">Verified from licensed traders</p>
                  </div>
                  <button className="btn btn-primary btn-sheen" onClick={handleWriteClick}>
                    {user ? '✎ Write a review' : '✎ Sign in to write a review'}
                  </button>
                </div>

                {/* Inline form (logged-in users) */}
                {showForm && user && (
                  <form onSubmit={submitReview} className="mt-6 panel" style={{ padding: 20, background: 'rgba(0,229,255,0.04)', borderColor: 'rgba(0,229,255,0.3)' }}>
                    <div className="flex-between mb-4">
                      <div className="flex gap-3" style={{ alignItems: 'center' }}>
                        <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--grad-1)', display: 'grid', placeItems: 'center', color: '#000', fontWeight: 700, fontFamily: 'var(--font-mono)', fontSize: 14 }}>{user.name[0]}</div>
                        <div>
                          <div style={{ fontWeight: 600 }}>{user.name}</div>
                          <div className="text-xs text-muted font-mono">Posting as {user.email}</div>
                        </div>
                      </div>
                      <button type="button" className="btn btn-ghost btn-sm" onClick={() => setShowForm(false)}>Cancel</button>
                    </div>
                    <div className="field mb-4">
                      <label>Rating</label>
                      <div className="flex gap-1" style={{ alignItems: 'center', marginTop: 4 }}>
                        {[1, 2, 3, 4, 5].map(n => (
                          <button key={n} type="button" onClick={() => setDraftStars(n)} style={{
                            background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, fontSize: 28, lineHeight: 1,
                            color: n <= draftStars ? 'var(--amber)' : 'var(--text-4)',
                            textShadow: n <= draftStars ? '0 0 8px rgba(255,184,0,0.5)' : 'none',
                            transition: 'all 0.15s',
                          }}>★</button>
                        ))}
                        <span className="font-mono text-xs text-muted ml-2" style={{ marginLeft: 12 }}>{draftStars}/5</span>
                      </div>
                    </div>
                    <div className="field">
                      <label>Your review</label>
                      <textarea
                        className="input"
                        rows="4"
                        placeholder={`How was ${ea.name}? Mention broker, account size, and what worked or didn't...`}
                        value={draftText}
                        onChange={(e) => setDraftText(e.target.value)}
                        required
                      />
                    </div>
                    <button className="btn btn-primary btn-sheen mt-4" type="submit" disabled={!draftText.trim()}>
                      Publish review →
                    </button>
                  </form>
                )}
              </div>

              {/* Review list */}
              <div className="grid grid-2">
                {[...userReviews, ...[
                  { name: 'Ahmed M.', stars: 5, text: 'Running this on prop firm account. Passed phase 1 in 11 days. The full backtest report sold me — every trade documented.', date: '2 days ago' },
                  { name: 'Linda B.', stars: 5, text: 'PF and DD match the marketplace claims exactly. I verified against my own MT5 logs.', date: '6 days ago' },
                  { name: 'Yuki T.', stars: 4, text: 'Great EA but watch the news filter on JPY pairs. Minor issue, AI Agent helped me tune it.', date: '2 weeks ago' },
                  { name: 'Faris A.', stars: 5, text: 'AWS VPS template installed in 4 minutes. EA was profitable on day 1.', date: '3 weeks ago' },
                ]].map((r, i) => (
                  <div key={i} className="panel panel-padded">
                    <div className="flex-between mb-4">
                      <div className="flex gap-3" style={{ alignItems: 'center' }}>
                        <div style={{ width: 32, height: 32, borderRadius: '50%', background: i < userReviews.length ? 'var(--grad-1)' : 'rgba(255,255,255,0.06)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 12, color: i < userReviews.length ? '#000' : 'var(--text-2)' }}>{r.name[0]}</div>
                        <div>
                          <div style={{ fontWeight: 600 }}>{r.name}</div>
                          <div className="text-xs text-muted font-mono">{r.date}</div>
                        </div>
                      </div>
                      <div style={{ color: 'var(--amber)' }}>{'★'.repeat(r.stars)}{'☆'.repeat(5 - r.stars)}</div>
                    </div>
                    <p className="text-sm">{r.text}</p>
                    {i < userReviews.length && <span className="tag tag-green mt-3" style={{ fontSize: 9 }}>NEW</span>}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* Bottom buy bar */}
      <section style={{ padding: '24px 0 80px' }}>
        <div className="container">
          <BuyWidget ea={ea} onBuy={onBuy}/>
        </div>
      </section>
    </div>
  );
}

window.DetailPage = DetailPage;
