// ============================================================
// ONBOARDING — 4 steps, shown once. Instrument, session,
// confluences, threshold.
// ============================================================
const { useState: useStateO } = React;

function Onboarding({ confluences, onDone, onClose }) {
  const { Btn, Icon, ConfChip, t } = window.CJUI;
  const { SESSIONS } = window.CJData;
  const [step, setStep] = useStateO(0);
  const [instrument, setInstrument] = useStateO('NQ');
  const [sessions, setSessions] = useStateO(['open']);
  const [conf, setConf] = useStateO(confluences.slice(0, 6).map((c) => c.id));
  const [custom, setCustom] = useStateO('');
  const [extra, setExtra] = useStateO([]);
  const [threshold, setThreshold] = useStateO(3);

  const allConf = [...confluences, ...extra];
  const toggleS = (id) => setSessions((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id]));
  const toggleC = (id) => setConf((c) => (c.includes(id) ? c.filter((x) => x !== id) : [...c, id]));
  const addCustom = () => { const n = custom.trim(); if (!n) return; const id = 'x' + Date.now(); setExtra((e) => [...e, { id, name: n }]); setConf((c) => [...c, id]); setCustom(''); };

  const steps = [
    { k: t('onb.s0k'), q: t('onb.s0q'), s: t('onb.s0s') },
    { k: t('onb.s1k'), q: t('onb.s1q'), s: t('onb.s1s') },
    { k: t('onb.s2k'), q: t('onb.s2q'), s: t('onb.s2s') },
    { k: t('onb.s3k'), q: t('onb.s3q'), s: t('onb.s3s') },
  ];
  const cur = steps[step];
  const next = () => (step < 3 ? setStep(step + 1) : onDone({ instrument, sessions, conf: conf, threshold, extra }));

  return (
    <div className="onb">
      <div className="onb-card">
        <div className="onb-kicker">
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <div className="brand-mark" style={{ width: 24, height: 24, fontSize: 13 }}>C</div>
            <span className="kicker">{t('onb.setup')}</span>
          </div>
          <span className="kicker">{t('onb.counter', { n: step + 1 })}</span>
        </div>

        <div className="kicker" style={{ color: 'var(--clay)', marginBottom: 10 }}>{cur.k}</div>
        <h1 className="onb-q">{cur.q}</h1>
        <p className="onb-sub">{cur.s}</p>

        {step === 0 && (
          <div className="seg three">
            {[['ES', 'S&P 500'], ['NQ', 'Nasdaq 100'], ['Both', t('onb.bothLabel')]].map(([v, l]) => (
              <button key={v} className={'optbtn' + (instrument === v ? ' sel' : '')} style={{ padding: 22 }} onClick={() => setInstrument(v)}>
                <span style={{ fontSize: 18 }}>{v}</span><span className="om">{l}</span>
              </button>
            ))}
          </div>
        )}

        {step === 1 && (
          <div className="seg two">
            {SESSIONS.map((s) => (
              <button key={s.id} className={'optbtn' + (sessions.includes(s.id) ? ' sel' : '')} style={{ alignItems: 'flex-start', padding: 16 }} onClick={() => toggleS(s.id)}>
                <span style={{ display: 'flex', width: '100%', justifyContent: 'space-between', alignItems: 'center' }}>
                  {t('sess.' + s.id)}{sessions.includes(s.id) && <Icon d="check" size={15} />}
                </span>
                <span className="om">{s.time}</span>
              </button>
            ))}
          </div>
        )}

        {step === 2 && (
          <div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {allConf.map((c) => <ConfChip key={c.id} big on={conf.includes(c.id)} onClick={() => toggleC(c.id)}>{c.name}</ConfChip>)}
            </div>
            <div className="addconf" style={{ marginTop: 16 }}>
              <input placeholder={t('onb.addOwn')} value={custom} onChange={(e) => setCustom(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addCustom()} />
              <Btn kind="ghost" icon="plus" onClick={addCustom}>{t('set.add')}</Btn>
            </div>
            <p style={{ marginTop: 14, fontSize: 12, color: 'var(--muted)' }}>{t('onb.selected', { n: conf.length })}</p>
          </div>
        )}

        {step === 3 && (
          <div className="seg three">
            {[2, 3, 4].map((n) => (
              <button key={n} className={'optbtn' + (threshold === n ? ' sel' : '')} style={{ padding: 22 }} onClick={() => setThreshold(n)}>
                <span style={{ fontSize: 22, fontFamily: 'var(--font-mono)' }}>{n === 4 ? '4+' : n}</span>
                <span className="om">{n === 2 ? t('set.looser') : n === 3 ? t('set.balanced') : t('set.strict')}</span>
              </button>
            ))}
          </div>
        )}

        <div className="onb-foot">
          <div className="onb-steps">
            {[0, 1, 2, 3].map((i) => <span key={i} className={'d ' + (i < step ? 'done' : i === step ? 'on' : '')} />)}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            {step > 0 && <Btn kind="quiet" icon="arrowL" onClick={() => setStep(step - 1)}>{t('common.back')}</Btn>}
            <Btn kind="primary" iconR={step < 3 ? 'arrowR' : 'check'} onClick={next} disabled={step === 1 && sessions.length === 0}>
              {step < 3 ? t('common.continue') : t('onb.enter')}
            </Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Onboarding = Onboarding;
