// ============================================================
// ANALYSE — five stats. Discipline ring, win rate by count,
// best combos, frequency, equity vs discipline.
// ============================================================
const { useMemo: useMemoAn } = React;

function AnalyseScreen({ trades, confluences, user, onShare }) {
  const { Btn, Icon, ConfChip, nameOf, t } = { ...window.CJUI, nameOf: window.CJData.nameOf };
  const D = window.CJData;

  const stats = useMemoAn(() => ({
    discipline: D.disciplineScore(trades, user.minConfluences),
    byCount: D.winRateByCount(trades),
    combos: D.bestCombinations(trades),
    freq: D.confluenceFrequency(trades, confluences),
    equity: D.equityCurve(trades, user.minConfluences),
  }), [trades, confluences, user]);

  if (trades.length === 0) {
    return <div className="empty" style={{ marginTop: 40 }}><h3>{t('an.empty')}</h3><p>{t('an.emptyP')}</p></div>;
  }

  return (
    <div className="fade-in" style={{ paddingTop: 26 }}>
      <div className="an-grid">
        {/* 1 — Discipline ring */}
        <Panel title={t('an.disc')} hint={t('an.discHint')}>
          <Ring value={stats.discipline} threshold={user.minConfluences} />
        </Panel>

        {/* 2 — Win rate by confluence count */}
        <Panel title={t('an.byCount')} hint={t('an.byCountHint')}>
          <WinRate data={stats.byCount} threshold={user.minConfluences} />
        </Panel>

        {/* 3 — Best combinations */}
        <Panel title={t('an.combos')} hint={t('an.combosHint')} className="span2">
          <Combos combos={stats.combos} nameOf={nameOf} />
        </Panel>

        {/* 4 — Frequency */}
        <Panel title={t('an.freq')} hint={t('an.freqHint')}>
          <Frequency rows={stats.freq} />
        </Panel>

        {/* 5 — Equity vs discipline */}
        <Panel title={t('an.equity')} hint={t('an.equityHint')}>
          <Equity data={stats.equity} />
        </Panel>
      </div>

      <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 22px', background: 'var(--clay-bg)', border: '1px solid color-mix(in oklab, var(--clay) 30%, transparent)', borderRadius: 8 }}>
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{t('an.shareTitle')}</div>
          <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 3 }}>{t('an.shareP')}</div>
        </div>
        <Btn kind="primary" icon="share" onClick={onShare}>{t('an.shareBtn')}</Btn>
      </div>
    </div>
  );
}

function Panel({ title, hint, className, children }) {
  return (
    <section className={'panel' + (className ? ' ' + className : '')}>
      <div className="panel-head">
        <span className="panel-title">{title}</span>
        <span className="panel-hint">{hint}</span>
      </div>
      <div className="panel-body">{children}</div>
    </section>
  );
}

// 1 — discipline ring
function Ring({ value, threshold }) {
  const t = window.CJUI.t;
  const color = value >= 80 ? 'var(--long)' : value >= 60 ? 'var(--warn)' : 'var(--short)';
  const r = 52, c = 2 * Math.PI * r, off = c * (1 - value / 100);
  const verdict = value >= 80 ? t('an.verdictGood') : value >= 60 ? t('an.verdictMid') : t('an.verdictBad');
  return (
    <div className="ring-wrap">
      <svg width="128" height="128" viewBox="0 0 128 128">
        <circle cx="64" cy="64" r={r} fill="none" stroke="var(--inset)" strokeWidth="8" />
        <circle cx="64" cy="64" r={r} fill="none" stroke={color} strokeWidth="8" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={off} transform="rotate(-90 64 64)" />
        <text x="64" y="60" textAnchor="middle" fontSize="25" fontWeight="600" fill="var(--ink)" fontFamily="var(--font-mono)">{value}%</text>
        <text x="64" y="79" textAnchor="middle" fontSize="9" fill="var(--muted)" fontFamily="var(--font-mono)" letterSpacing="1.2">{t('an.followed')}</text>
      </svg>
      <div className="ring-legend">
        <div style={{ color, fontWeight: 700, fontSize: 15, fontFamily: 'var(--font-mono)' }}>{verdict}</div>
        <div style={{ marginTop: 8 }}>{t('an.ringBody', { v: value, t: threshold })}</div>
      </div>
    </div>
  );
}

// 2 — win rate by count bars
function WinRate({ data, threshold }) {
  const t = window.CJUI.t;
  const max = 100;
  return (
    <div>
      {data.map((d) => {
        const isThr = (d.label === '4+' && threshold >= 4) || String(threshold) === d.label;
        const col = d.trades === 0 ? 'var(--border)' : d.winRate >= 55 ? 'var(--long)' : d.winRate >= 45 ? 'var(--warn)' : 'var(--short)';
        return (
          <div className="bar-row" key={d.label}>
            <span className="lab">{d.label}{isThr && <span style={{ color: 'var(--clay)', marginLeft: 5 }}>◆</span>}</span>
            <div className="bar-track">
              <div className="bar-fill" style={{ width: Math.max(2, (d.winRate / max) * 100) + '%', background: col }} />
            </div>
            <span className="val">{d.trades ? d.winRate + '%' : '—'} <span style={{ color: 'var(--faint)' }}>· {d.trades}t</span></span>
          </div>
        );
      })}
      <p style={{ marginTop: 12, fontSize: 12, color: 'var(--muted)' }}><span style={{ color: 'var(--clay)' }}>◆</span> {t('an.thrNote')}</p>
    </div>
  );
}

// 3 — best combos
function Combos({ combos, nameOf }) {
  const t = window.CJUI.t;
  if (!combos.length) return <p style={{ color: 'var(--muted)', fontSize: 13 }}>{t('an.noCombo')}</p>;
  return (
    <div>
      {combos.map((c, i) => (
        <div className="combo" key={c.label}>
          <span className="combo-rank">{['01', '02', '03'][i]}</span>
          <div className="combo-names">
            {c.ids.map((id) => <span key={id} className="cchip">{nameOf(id)}</span>)}
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="combo-wr pos">{c.winRate}%</div>
            <div className="combo-n">{c.trades} trades</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// 4 — frequency
function Frequency({ rows }) {
  const max = Math.max(1, ...rows.map((r) => r.uses));
  return (
    <div>
      {rows.slice(0, 7).map((r) => (
        <div className="freq-row" key={r.id}>
          <span className="lab">{r.name}</span>
          <div className="freq-track"><div className="freq-fill" style={{ width: (r.uses / max) * 100 + '%' }} /></div>
          <span className="val">{r.uses}× · {r.share}%</span>
        </div>
      ))}
    </div>
  );
}

// 5 — equity curve with discipline-colored markers
function Equity({ data }) {
  const t = window.CJUI.t;
  const W = 460, H = 180, pad = 8;
  const eqs = data.map((d) => d.equity);
  const min = Math.min(0, ...eqs), max = Math.max(...eqs);
  const span = max - min || 1;
  const x = (i) => pad + (i / (data.length - 1 || 1)) * (W - pad * 2);
  const y = (v) => H - pad - ((v - min) / span) * (H - pad * 2);
  const path = data.map((d, i) => (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(d.equity).toFixed(1)).join(' ');
  const area = path + ` L ${x(data.length - 1)} ${H - pad} L ${x(0)} ${H - pad} Z`;
  const zeroY = y(0);
  return (
    <div className="eq-wrap">
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', overflow: 'visible' }}>
        <defs>
          <linearGradient id="eqg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="var(--clay)" stopOpacity="0.22" />
            <stop offset="1" stopColor="var(--clay)" stopOpacity="0" />
          </linearGradient>
        </defs>
        <line x1={pad} y1={zeroY} x2={W - pad} y2={zeroY} stroke="var(--border)" strokeWidth="1" strokeDasharray="3 4" />
        <path d={area} fill="url(#eqg)" />
        <path d={path} fill="none" stroke="var(--clay)" strokeWidth="1.8" />
        {data.map((d, i) => (
          <circle key={i} cx={x(i)} cy={y(d.equity)} r="3" fill={d.disciplined ? 'var(--long)' : 'var(--short)'} stroke="var(--panel)" strokeWidth="1.5" />
        ))}
      </svg>
      <div className="eq-legend">
        <span><span style={{ width: 8, height: 8, borderRadius: 9, background: 'var(--long)', display: 'inline-block', marginRight: 6 }} />{t('an.metShort')}</span>
        <span><span style={{ width: 8, height: 8, borderRadius: 9, background: 'var(--short)', display: 'inline-block', marginRight: 6 }} />{t('an.belowShort')}</span>
      </div>
    </div>
  );
}

window.AnalyseScreen = AnalyseScreen;
