/* ════════════════════════════════════════════════════════════
   ContractReview — when a signed contract reaches 30+ days,
   prompt the user to face their own past decision.
   Modal kicks in from SignedLedger row's "回顾" button.
   Final retrospective ships them a sealed verdict card.
   ════════════════════════════════════════════════════════════ */

const { useState: cr_s } = React;

function ContractReview({ open, item, onClose }) {
  const lang = window.__LANG || 'zh';
  const [step, setStep] = cr_s(0);
  const [pick, setPick] = cr_s(null);   // user's self-assessment

  if (!open || !item) return null;

  // Compute realized P&L (same deterministic hash policy as ledger)
  const sym = item.sym;
  let h = 0; for (let i = 0; i < sym.length; i++) h = (h*31 + sym.charCodeAt(i)) % 1000;
  const pnl = ((h % 11) - 4) * 0.8;
  const days = Math.max(0, Math.floor((Date.now() - item.t) / 86400000));
  const win  = pnl >= 0;
  const breached = pnl <= -3.5;

  const closeWithChirp = () => {
    window.haptic?.light();
    setStep(0); setPick(null);
    onClose?.();
  };

  const lessons = lang === 'zh' ? [
    { id: 'stuck',   label: '我顶住了情绪',         note: '在 §III 触发前没有 panic sell。' },
    { id: 'cut',     label: '我执行了止损',         note: '尊重了承诺书第三条款。' },
    { id: 'doubled', label: '我加仓了 / 我抄了底',  note: '需要回看是否符合原假设。' },
    { id: 'froze',   label: '我没按计划行动',       note: '反思:这套承诺是不是不该签?' },
    { id: 'pivot',   label: '我换了别的票',         note: '注意:换股频率与回报常呈负相关。' },
  ] : [
    { id: 'stuck',   label: 'I held through the noise.',   note: 'No panic sell before §III triggered.' },
    { id: 'cut',     label: 'I executed the stop.',         note: 'Respected clause §III.' },
    { id: 'doubled', label: 'I added / averaged down.',     note: 'Check whether the thesis still held.' },
    { id: 'froze',   label: "I didn't follow my plan.",     note: 'Should the contract have been signed?' },
    { id: 'pivot',   label: 'I rotated to another name.',   note: 'Note: rotation freq often hurts returns.' },
  ];

  const verdict = () => {
    if (breached) return { tag: 'IN BREACH', kind: 'red',
      copy: lang==='zh' ? '止损被触发 — 承诺履行已结束。' : 'Stop tripped — the contract is closed.' };
    if (win) return { tag: 'IN GOOD STANDING', kind: 'green',
      copy: lang==='zh' ? '盈利窗口 · 第三条款未被触发。' : 'In the green · clause §III not triggered.' };
    return { tag: 'UNDER REVIEW', kind: 'amber',
      copy: lang==='zh' ? '小幅亏损 · 仍在观察期。' : 'Mild drawdown · still under watch.' };
  };
  const v = verdict();

  const fileNo = sym + '·' + String(item.t).slice(-5);

  return (
    <div className="cr-bg" onClick={closeWithChirp}>
      <div className="cr-paper" onClick={(e) => e.stopPropagation()}>
        <header className="cr-mast">
          <div>
            <div className="cr-eb">{lang==='zh'?'三十日回顾':'30-DAY REVIEW'} · §III</div>
            <h2 className="cr-title">{lang==='zh'?'承诺书 · 期满复盘':'Contract · Retrospective'}</h2>
          </div>
          <div className="cr-fileno">FILE No. {fileNo}</div>
        </header>

        {step === 0 && (
          <div className="cr-step">
            <div className="cr-ticker">
              <div className="cr-tk-row">
                <span className="cr-tk-lbl">{lang==='zh'?'股票':'Symbol'}</span>
                <span className="cr-tk-val"><b>{sym}</b> · {item.rec.name}</span>
              </div>
              <div className="cr-tk-row">
                <span className="cr-tk-lbl">{lang==='zh'?'签约':'Signed'}</span>
                <span className="cr-tk-val">{new Date(item.t).toLocaleDateString(lang==='zh'?'zh-CN':'en-US')}</span>
              </div>
              <div className="cr-tk-row">
                <span className="cr-tk-lbl">{lang==='zh'?'持有':'Held'}</span>
                <span className="cr-tk-val">{days} {lang==='zh'?'天':'days'}</span>
              </div>
              <div className="cr-tk-row big">
                <span className="cr-tk-lbl">{lang==='zh'?'当前盈亏':'Realized'}</span>
                <span className={'cr-tk-pnl ' + (win ? 'up' : 'dn')}>{win?'+':''}{pnl.toFixed(2)}%</span>
              </div>
            </div>

            <p className="cr-body">
              {lang==='zh'
                ? '请回答 — 这 30 天里,你怎样回应这只票的表现?选一项最贴近你行为的。'
                : 'A question — over these 30 days, how did you respond to this name?  Pick the line closest to your behavior.'}
            </p>

            <ul className="cr-choices" role="radiogroup">
              {lessons.map(l => (
                <li key={l.id}>
                  <button
                    role="radio" aria-checked={pick === l.id}
                    className={'cr-choice' + (pick === l.id ? ' on' : '')}
                    onClick={() => { setPick(l.id); window.haptic?.light(); }}>
                    <span className="cr-choice-r"/>
                    <span className="cr-choice-body">
                      <b>{l.label}</b>
                      <span className="cr-choice-note">{l.note}</span>
                    </span>
                  </button>
                </li>
              ))}
            </ul>

            <div className="cr-foot">
              <button className="cr-btn ghost" onClick={closeWithChirp}>{lang==='zh'?'稍后':'Later'}</button>
              <button className="cr-btn primary" disabled={!pick}
                onClick={() => { window.haptic?.success?.(); setStep(1); }}>
                {lang==='zh'?'存档 · FILE':'File · ACKNOWLEDGE'}
              </button>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="cr-step cr-verdict">
            <div className={'cr-stamp ' + v.kind}>{v.tag}</div>
            <p className="cr-verdict-copy">{v.copy}</p>

            <div className="cr-receipt">
              <div className="cr-rc-row"><span>{lang==='zh'?'已选立场':'Self-report'}</span><b>{lessons.find(l => l.id === pick).label}</b></div>
              <div className="cr-rc-row"><span>{lang==='zh'?'编辑部备注':'Desk note'}</span><i>{lessons.find(l => l.id === pick).note}</i></div>
              <div className="cr-rc-row"><span>{lang==='zh'?'已存档':'Filed'}</span><span>{new Date().toLocaleString(lang==='zh'?'zh-CN':'en-US')}</span></div>
            </div>

            <p className="cr-coda">
              {lang==='zh'
                ? '这份回顾已封存在你的承诺存档中 — 下一次决策时,我们会自动召回。'
                : "This retrospective is now sealed alongside the original contract — we'll surface it on your next decision."}
            </p>

            <div className="cr-foot">
              <button className="cr-btn primary wide" onClick={() => {
                try {
                  localStorage.setItem('review.' + sym, JSON.stringify({
                    pick, t: Date.now(), pnl, verdict: v.tag,
                  }));
                } catch (e) {}
                window.toast?.({ msg: lang==='zh'?'回顾已封存 · 第三条款已履行':'Retrospective sealed · §III honored', kind: 'success' });
                closeWithChirp();
              }}>{lang==='zh'?'封存 · SEAL':'Seal · CLOSE'}</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.ContractReview = ContractReview;
