// outreach-seq-editor.jsx — Outreach › Sequences.
// Per ICP: the key pain points (anchor the messaging) + the message list
// (day · channel · email + text). Source of the words + timing. Editing changes
// future plans; people already on a sequence keep their current messages.
const { useState: useStateSE, useEffect: useEffectSE } = React;
const RSse = window.RaiseShell;
const SE_CH = [['email', 'Email'], ['text', 'Text (LinkedIn / SMS / WeChat)']];

function OXSeq() {
  const LD = window.RaiseLiveData, R = window.RAISE;
  const [, bump] = useStateSE(0);
  useEffectSE(() => {
    const h = () => bump(x => x + 1);
    window.addEventListener('raise-livedata', h);
    if (LD && !LD.isSequenceTemplatesLive()) LD.loadSequenceTemplates();
    return () => window.removeEventListener('raise-livedata', h);
  }, []);
  // The 7 LP ICPs + RE partner + every custom role (each track independent).
  const order = (R && R.trackEditableKeys) ? R.trackEditableKeys() : ((R && R.ICP_ORDER) || []);
  const [icp, setIcp] = useStateSE(order[0] || 'FO');
  const [edits, setEdits] = useStateSE({});   // icp → { touches, pains } (unsaved)
  const [busy, setBusy] = useStateSE(false);
  // Let Settings › Roles deep-link straight to a role's talk track.
  useEffectSE(() => { window.__oxSeqSelect = (k) => { if (k) setIcp(k); };
    return () => { if (window.__oxSeqSelect) delete window.__oxSeqSelect; }; });

  const stored = (LD && LD.sequenceTemplateFor(icp)) || { touches: [], pains: [] };
  const draft = edits[icp] || { touches: stored.touches || [], pains: stored.pains || [] };
  const touches = draft.touches, pains = draft.pains;
  const dirty = !!edits[icp];
  const setDraft = (next) => setEdits(e => ({ ...e, [icp]: next }));
  const setTouches = (next) => setDraft({ ...draft, touches: next });
  const setPains = (next) => setDraft({ ...draft, pains: next });

  const setT = (i, k, v) => setTouches(touches.map((t, j) => j === i ? { ...t, [k]: v } : t));
  const addT = () => { const last = touches[touches.length - 1]; setTouches([...touches, { seq: touches.length + 1, day: last ? (last.day || 0) + 7 : 0, channel: 'email', label: 'Touch', email: 'Hi {first}, …', text: 'Hi {first}, …' }]); };
  const delT = (i) => setTouches(touches.filter((_, j) => j !== i).map((t, j) => ({ ...t, seq: j + 1 })));
  const move = (i, dir) => { const j = i + dir; if (j < 0 || j >= touches.length) return; const a = touches.slice(); [a[i], a[j]] = [a[j], a[i]]; setTouches(a.map((t, k) => ({ ...t, seq: k + 1 }))); };
  const setPain = (i, v) => setPains(pains.map((p, j) => j === i ? v : p));
  const addPain = () => setPains([...pains, '']);
  const delPain = (i) => setPains(pains.filter((_, j) => j !== i));

  const revert = () => setEdits(e => { const n = { ...e }; delete n[icp]; return n; });
  const save = async () => {
    setBusy(true);
    const cleanT = touches.map((t, i) => ({ seq: i + 1, day: +t.day || 0, channel: t.channel === 'text' ? 'text' : 'email', label: t.label || 'Touch', email: t.email != null ? t.email : (t.message || ''), text: t.text != null ? t.text : (t.message || '') }));
    const cleanP = pains.map(p => (p || '').trim()).filter(Boolean);
    const r = await LD.patchSequenceTemplate(icp, { touches: cleanT, pains: cleanP });
    setBusy(false);
    if (r && r.ok) { RSse.toast('Sequence saved · ' + (R.icpMeta(icp) ? R.icpMeta(icp).short : icp)); revert(); }
    else RSse.toast('Save failed' + (r && r.error ? ' — ' + r.error : ''));
  };

  return (
    <div className="seqed scroll">
      <div className="seqed-intro"><i className="ti ti-list-details" aria-hidden="true" /> Each role has its own pain points and message sequence. Set a contact's ICP + Tier in the pipeline and this becomes their plan, with dates filled in. Pains anchor the messaging and feed the AI rewrites.</div>

      <div className="seqed-icps">
        {order.map(k => { const m = R.icpMeta(k); return (
          <button key={k} className={'seqed-icp' + (icp === k ? ' on' : '')}
            style={icp === k && m ? { borderColor: m.color, color: m.color, background: m.tint } : null}
            onClick={() => setIcp(k)}>{m ? m.short : k}</button>); })}
      </div>

      <div className="seqed-meta">
        <b>{R.icpMeta(icp) ? R.icpMeta(icp).label : icp}</b>
        <span className="seqed-sum">{touches.length} touches over {touches.length ? Math.max(...touches.map(t => +t.day || 0)) : 0} days</span>
        {dirty && <span className="seqed-dirty">unsaved</span>}
      </div>

      <div className="seqed-section">Key pain points <span className="seqed-hint">— what this role cares about; anchors every message</span></div>
      <div className="seqed-pains">
        {pains.map((p, i) => (
          <div className="seqed-pain" key={i}>
            <span className="seqed-pain-dot" />
            <input className="seqed-pain-inp" value={p} onChange={e => setPain(i, e.target.value)} placeholder="A pain this role feels" />
            <button className="seqed-tool del" onClick={() => delPain(i)} title="Delete">✕</button>
          </div>
        ))}
        <button className="seqed-add" onClick={addPain}>＋ Add pain point</button>
      </div>

      <div className="seqed-section">Sequence</div>
      <div className="seqed-list">
        {touches.map((t, i) => (
          <div className="seqed-touch" key={i}>
            <div className="seqed-touch-hd">
              <span className="seqed-seq mono">{i + 1}</span>
              <label className="seqed-lab">Day</label>
              <input type="number" min="0" className="seqed-day" value={t.day || 0} onChange={e => setT(i, 'day', Math.max(0, +e.target.value || 0))} />
              <select className="seqed-ch" value={t.channel === 'text' ? 'text' : 'email'} onChange={e => setT(i, 'channel', e.target.value)} title="Default medium">
                {SE_CH.map(([v, lab]) => <option key={v} value={v}>{lab}</option>)}
              </select>
              <input className="seqed-label" value={t.label || ''} onChange={e => setT(i, 'label', e.target.value)} placeholder="Label" />
              <button className="seqed-tool" disabled={i === 0} onClick={() => move(i, -1)} title="Up">↑</button>
              <button className="seqed-tool" disabled={i === touches.length - 1} onClick={() => move(i, 1)} title="Down">↓</button>
              <button className="seqed-tool del" onClick={() => delT(i)} title="Delete">✕</button>
            </div>
            <div className="seqed-var"><span className="seqed-var-lab">Email</span><textarea className="seqed-msg" rows={3} value={t.email != null ? t.email : (t.message || '')} onChange={e => setT(i, 'email', e.target.value)} placeholder="Email version…" /></div>
            <div className="seqed-var"><span className="seqed-var-lab">Text</span><textarea className="seqed-msg" rows={2} value={t.text != null ? t.text : (t.message || '')} onChange={e => setT(i, 'text', e.target.value)} placeholder="Short text version (LinkedIn / SMS / WeChat)…" /></div>
          </div>
        ))}
        <button className="seqed-add" onClick={addT}>＋ Add touch</button>
      </div>

      <div className="seqed-tokens">Tokens: <code>{'{first}'}</code> <code>{'{firm}'}</code> <code>{'{commonality}'}</code></div>

      <div className="seqed-foot">
        <span className="seqed-hint">Editing changes future plans; people already on this sequence keep their current messages.</span>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <button className="btn sm" disabled={!dirty || busy} onClick={revert}>Revert</button>
          <button className="btn primary sm" disabled={!dirty || busy} onClick={save}>Save sequence</button>
        </div>
      </div>
    </div>
  );
}

window.OXSeq = OXSeq;
