// ============================================================
// LOG TRADE — 3-step side sheet, + Trade detail ticket.
// ============================================================
const { useState: useStateL } = React;

function LogTrade({ confluences, user, onClose, onSave }) {
  const { Btn, Icon, ConfChip, ThresholdPips, nameOf, t } = { ...window.CJUI, nameOf: window.CJData.nameOf };
  const [step, setStep] = useStateL(0);
  const [instrument, setInstrument] = useStateL('NQ');
  const [direction, setDirection] = useStateL('Long');
  const [sign, setSign] = useStateL(1);
  const [amount, setAmount] = useStateL('');
  const [shots, setShots] = useStateL([]); // [{ path, url }]
  const [uploading, setUploading] = useStateL(false);
  const fileRef = React.useRef(null);
  const [conf, setConf] = useStateL([]);
  const [note, setNote] = useStateL('');

  const onFile = async (e) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setUploading(true);
    for (const file of files) {
      const path = await window.CJSupa.uploadScreenshot(file);
      if (path) { const url = await window.CJSupa.screenshotUrl(path); setShots((s) => [...s, { path, url }]); }
    }
    setUploading(false);
    e.target.value = ''; // allow re-picking the same file
  };
  const removeShot = (path) => setShots((s) => s.filter((x) => x.path !== path));

  const toggle = (id) => setConf((c) => (c.includes(id) ? c.filter((x) => x !== id) : [...c, id]));
  const below = conf.length < user.minConfluences;
  const canNext = step === 0 ? amount !== '' : true;

  const save = () => {
    onSave({ instrument, direction, pnl: sign * (parseInt(amount, 10) || 0), conf, note: note.trim(), shotPaths: shots.map((s) => s.path) });
  };

  const titles = [t('log.setup'), t('log.confluences'), t('log.note')];

  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-head">
          <div>
            <div className="kicker">{t('log.newTrade', { n: step + 1 })}</div>
            <h2 style={{ marginTop: 4 }}>{titles[step]}</h2>
          </div>
          <button className="iconbtn" onClick={onClose}><Icon d="x" size={16} /></button>
        </div>
        <div className="steps">
          {[0, 1, 2].map((i) => <span key={i} className={'step-dot ' + (i < step ? 'done' : i === step ? 'cur' : '')} />)}
        </div>

        <div className="sheet-body">
          {step === 0 && (
            <div style={{ display: 'grid', gap: 26 }}>
              <div>
                <span className="field-label">{t('log.instrument')}</span>
                <div className="seg three">
                  {['ES', 'NQ'].map((x) => (
                    <button key={x} className={'optbtn' + (instrument === x ? ' sel' : '')} onClick={() => setInstrument(x)}>
                      {x}<span className="om">{x === 'ES' ? 'S&P 500' : 'Nasdaq 100'}</span>
                    </button>
                  ))}
                  <button className={'optbtn' + (instrument === 'MNQ' ? ' sel' : '')} onClick={() => setInstrument('MNQ')}>
                    MNQ<span className="om">Micro</span>
                  </button>
                </div>
              </div>
              <div>
                <span className="field-label">{t('log.direction')}</span>
                <div className="seg two">
                  <button className={'optbtn' + (direction === 'Long' ? ' sel long' : '')} onClick={() => setDirection('Long')}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon d="up" size={15} sw={2.4} />{t('log.long')}</span>
                  </button>
                  <button className={'optbtn' + (direction === 'Short' ? ' sel short' : '')} onClick={() => setDirection('Short')}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon d="down" size={15} sw={2.4} />{t('log.short')}</span>
                  </button>
                </div>
              </div>
              <div>
                <span className="field-label">{t('log.realized')}</span>
                <div className="pnl-input">
                  <div className="pnl-sign">
                    <button className={'plus' + (sign === 1 ? ' on' : '')} onClick={() => setSign(1)}>+</button>
                    <button className={'minus' + (sign === -1 ? ' on' : '')} onClick={() => setSign(-1)}>−</button>
                  </div>
                  <span className="cur">$</span>
                  <input type="number" inputMode="numeric" placeholder="0" value={amount} onChange={(e) => setAmount(e.target.value)} autoFocus />
                </div>
              </div>
              <div>
                <span className="field-label">{t('log.screenshot')}</span>
                <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={onFile} />
                {shots.length ? (
                  <div className="shot-grid">
                    {shots.map((s) => (
                      <div className="shot-thumb" key={s.path}>
                        {s.url ? <img src={s.url} alt="" /> : <div className="bar" />}
                        <button type="button" className="shot-rm" onClick={() => removeShot(s.path)} aria-label={t('log.removeShot')}><Icon d="x" size={12} /></button>
                      </div>
                    ))}
                    <button type="button" className="shot-add" onClick={() => fileRef.current && fileRef.current.click()}>
                      <Icon d="plus" size={18} /><span>{uploading ? t('log.uploading') : t('log.addShot')}</span>
                    </button>
                  </div>
                ) : (
                  <div className="drop" onClick={() => fileRef.current && fileRef.current.click()}>
                    <div className="ph"><span className="lab">{t('log.chartShot')}</span></div>
                    <Icon d="upload" size={18} /><div style={{ marginTop: 6, fontSize: 13 }}>{uploading ? t('log.uploading') : t('log.dropHint')}</div>
                  </div>
                )}
              </div>
            </div>
          )}

          {step === 1 && (
            <div>
              <div className="confcount">
                <div>
                  <div className="kicker">{t('log.selected')}</div>
                  <div className="big" style={{ color: below ? 'var(--warn)' : 'var(--ink)' }}>{conf.length}<span style={{ color: 'var(--faint)', fontSize: 18 }}> / {confluences.length}</span></div>
                </div>
                {below && <span className="warnflag">▼ {t('log.belowThr', { n: user.minConfluences })}</span>}
              </div>
              <div className="conf-grid">
                {confluences.map((c) => (
                  <ConfChip key={c.id} big on={conf.includes(c.id)} onClick={() => toggle(c.id)}>{c.name}</ConfChip>
                ))}
              </div>
              <p style={{ marginTop: 18, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.6 }}>
                {t('log.tapToggle')}
              </p>
            </div>
          )}

          {step === 2 && (
            <div>
              <span className="field-label">{t('log.why')} <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--faint)' }}>{t('log.optional')}</span></span>
              <textarea className="note" placeholder={t('log.notePh')} value={note} onChange={(e) => setNote(e.target.value)} autoFocus />
              <div style={{ marginTop: 18, padding: 16, background: 'var(--inset)', borderRadius: 6, border: '1px solid var(--border)' }}>
                <div className="kicker" style={{ marginBottom: 10 }}>{t('log.preview')}</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{instrument} · {direction}</span>
                  <span className={'mono ' + (sign >= 0 ? 'pos' : 'neg')} style={{ fontWeight: 600, fontSize: 16 }}>{sign < 0 ? '−' : '+'}${Math.abs(parseInt(amount, 10) || 0).toLocaleString()}</span>
                </div>
                <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8, color: 'var(--muted)', fontSize: 12.5, fontFamily: 'var(--font-mono)' }}>
                  <ThresholdPips count={conf.length} threshold={user.minConfluences} /> {t('log.confCount', { n: conf.length })} {below ? '· ' + t('log.belowWord') : '· ' + t('log.met')}
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="sheet-foot">
          {step > 0 ? (
            <Btn kind="quiet" icon="arrowL" onClick={() => setStep((s) => s - 1)}>{t('common.back')}</Btn>
          ) : (
            <Btn kind="quiet" onClick={onClose}>{t('common.cancel')}</Btn>
          )}
          <div style={{ flex: 1 }} />
          {step < 2 ? (
            <Btn kind="primary" iconR="arrowR" disabled={!canNext} onClick={() => setStep((s) => s + 1)}>{t('common.continue')}</Btn>
          ) : (
            <Btn kind="primary" icon="check" onClick={save}>{t('log.saveTrade')}</Btn>
          )}
        </div>
      </div>
    </div>
  );
}

// -------------------- Trade detail ticket --------------------
function TradeDetail({ trade, user, onClose, onDelete }) {
  const { Btn, Icon, DirTag, ConfChip, ThresholdPips, fmtUSD, nameOf, t } = { ...window.CJUI, nameOf: window.CJData.nameOf };
  const below = trade.conf.length < user.minConfluences;
  const d = new Date(trade.ts);
  const [shotUrls, setShotUrls] = React.useState([]);
  React.useEffect(() => {
    let alive = true;
    const paths = trade.shotPaths || [];
    Promise.all(paths.map((p) => window.CJSupa.screenshotUrl(p))).then((urls) => { if (alive) setShotUrls(urls.filter(Boolean)); });
    return () => { alive = false; };
  }, [trade]);
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-head">
          <div>
            <div className="kicker">{t('det.ticket')}</div>
            <h2 style={{ marginTop: 4, display: 'flex', alignItems: 'center', gap: 10 }}>{trade.instrument} <DirTag dir={trade.direction} /></h2>
          </div>
          <button className="iconbtn" onClick={onClose}><Icon d="x" size={16} /></button>
        </div>
        <div className="sheet-body">
          <div className={'detail-pnl ' + (trade.pnl >= 0 ? 'pos' : 'neg')}>{fmtUSD(trade.pnl)}</div>
          <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 8, fontFamily: 'var(--font-mono)' }}>
            {d.toLocaleDateString(window.CJI18n.locale, { weekday: 'short', month: 'short', day: '2-digit', year: 'numeric' })} · {d.toLocaleTimeString(window.CJI18n.locale, { hour: '2-digit', minute: '2-digit', hour12: false })}
          </div>

          {shotUrls.length ? (
            <div className="detail-shots" style={{ marginTop: 22 }}>
              {shotUrls.map((u, i) => (
                <a key={i} href={u} target="_blank" rel="noreferrer" className="detail-shot-item"><img src={u} alt="" /></a>
              ))}
            </div>
          ) : (
            <div style={{ marginTop: 22 }} className="detail-shot">
              <span className="lab kicker">{(trade.shotPaths || []).length ? t('log.uploading') : t('det.noShot')}</span>
            </div>
          )}

          <div style={{ marginTop: 22 }}>
            <div className="detail-row">
              <span className="detail-k">{t('det.confluences')}</span>
              <span className="detail-v" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <ThresholdPips count={trade.conf.length} threshold={user.minConfluences} />
                {trade.conf.length} / {user.minConfluences} {below ? <span className="t-flag below" style={{ marginLeft: 4 }}>{t('det.below')}</span> : <span className="t-flag" style={{ color: 'var(--long)', marginLeft: 4 }}>{t('det.metFlag')}</span>}
              </span>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
            {trade.conf.map((id) => <ConfChip key={id} on>{nameOf(id)}</ConfChip>)}
            {trade.conf.length === 0 && <span style={{ color: 'var(--muted)', fontSize: 13 }}>{t('det.none')}</span>}
          </div>

          {trade.note && (
            <div style={{ marginTop: 24 }}>
              <div className="detail-k" style={{ marginBottom: 10 }}>{t('det.note')}</div>
              <div className="detail-note">{trade.note}</div>
            </div>
          )}
        </div>
        <div className="sheet-foot">
          <Btn kind="danger" icon="x" onClick={() => onDelete(trade.id)}>{t('common.delete')}</Btn>
          <div style={{ flex: 1 }} />
          <Btn kind="ghost" onClick={onClose}>{t('common.close')}</Btn>
        </div>
      </div>
    </div>
  );
}

window.LogTrade = LogTrade;
window.TradeDetail = TradeDetail;
