/* Screen C — Prepared Outreach */
const { useState: oS } = React;

const CORR = ['Recipient', 'Facts', 'Tone', 'Timing', 'Missing context', 'Incorrect condition', 'Consolidation', 'Compliance language', 'Other'];

function OutreachCard({ d, brief }) {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const r = MD.byId[d.renewal];
  const a = r ? AG.advOf(r) : null;
  const [open, setOpen] = oS(false);
  const [body, setBody] = oS(d.body);
  const [to, setTo] = oS(d.to);
  const [subject, setSubject] = oS(d.subject);
  const [corr, setCorr] = oS(null);
  const [pending, setPending] = oS(false);
  const dirty = body !== d.body || to !== d.to || subject !== d.subject;
  const inferred = to !== d.to ? 'Recipient' : body.length > d.body.length + 60 ? 'Missing context' : subject !== d.subject ? 'Facts' : 'Tone';
  const c = r ? AG.openC(r)[0] : null;
  const sent = d.state === 'sent';
  const send = () => { if (dirty && !pending) { setPending(true); setCorr(inferred); return; } app.sendDraft(d.id, { to, cc: d.cc, subject, body, correction: dirty ? corr : null }); setPending(false); setOpen(false); };

  return <div className={'ocard' + (open ? ' on' : '')}>
    <div className="ocard-h" onClick={() => setOpen(!open)}>
      <div className="ob">
        <div className="row" style={{ gap: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{r ? r.account : d.to}</span>
          <span className="sm dim">{a ? a.name : d.internal ? 'internal' : 'no advisor'}{r ? ' · ' + r.policy : ''}</span>
          {d.consolidateWith ? <span className="pill t-purple"><Icon n="layers" s={10} />Consolidation recommended</span> : null}
        </div>
        <div className="decision">{d.internal ? 'Raise ' + (c ? c.cat : '') + ' internally — ' + d.subject.split('—').pop().trim() : 'Ask ' + (to === (a && a.email) ? (a ? a.name.split(' ')[0] : 'the advisor') : (r ? r.contact.name.split(' ')[0] : 'the client')) + ' for ' + (c ? c.item.toLowerCase() : d.category.toLowerCase())}</div>
        <div className="why"><b>Why the agent prepared this.</b> {d.reason}{d.warn ? ' ' + d.warn : ''}</div>
        <div className="dcard-chips">
          {c ? <span className={'chip ' + (c.pressure === 'crit' || c.pressure === 'overdue' ? 'red' : 'amber')}><i className="cd" />{c.cat} · {c.age} days</span> : null}
          {c ? <span className="chip"><i className="cd" />{c.owing} owes it</span> : null}
          {c ? <span className="chip"><i className="cd" />{c.attempts} prior attempt{c.attempts === 1 ? '' : 's'}</span> : null}
          <span className="chip blue"><i className="cd" />{d.category}</span>
        </div>
      </div>
      <div className="or">
        <AutoTag v={d.state === 'ready' ? 'prepared' : d.state === 'held' ? 'monitor' : d.state === 'suppressed' ? 'handled' : 'handled'} />
        <span className="reasoning-link">{open ? 'Hide message' : 'Review message'}<Icon n={open ? 'chevron-up' : 'arrow-right'} s={13} /></span>
        {sent ? <span className="pill t-green"><Icon n="check" s={10} />Sent {rel(d.sentAt)}</span> : null}
      </div>
    </div>
    {d.state === 'suppressed' ? <div className="rpanel" style={{ paddingTop: 14, paddingBottom: 14 }}><div className="note"><Icon n="ban" s={15} style={{ color: 'var(--text-muted)' }} /><span><b>Suppressed — nothing was sent.</b> {d.suppressedBy}</span></div></div> : null}
    {d.state === 'held' ? <div className="rpanel" style={{ paddingTop: 14, paddingBottom: 14 }}><div className="note amber"><Icon n="pause" s={15} /><span><b>Held deliberately.</b> {d.heldReason}</span></div></div> : null}
    {open ? <div className="mail">
      <div className="mailmeta">
        <span className="l">To</span><input className="mailf" value={to} onChange={(e) => setTo(e.target.value)} />
        <span className="l">CC</span><input className="mailf" value={d.cc || ''} readOnly placeholder="—" />
        <span className="l">Subject</span><input className="mailf" value={subject} onChange={(e) => setSubject(e.target.value)} />
      </div>
      <textarea className="mailbody" value={body} onChange={(e) => setBody(e.target.value)} spellCheck={false} />
      {pending ? <div style={{ padding: '12px 20px 0' }}><div className="note blue">
        <Icon n="edit" s={15} />
        <span className="grow">You changed the prepared message. Recorded as
          <select className="mailf" style={{ width: 180, display: 'inline-block', margin: '0 8px', height: 26, padding: '0 8px' }} value={corr} onChange={(e) => setCorr(e.target.value)}>{CORR.map((x) => <option key={x}>{x}</option>)}</select>
          — the agent uses this to compose the next <b>{d.category}</b>.</span>
        <button className="btn p sm" onClick={send}>Confirm and send</button>
      </div></div> : null}
      <div className="dbar" style={{ marginTop: 14 }}>
        {sent ? <span className="decided approved"><Icon n="check" s={15} />Sent to {d.to}</span> : <>
          <Gated action="send" label="Send"><button className="btn p" onClick={send}><Icon n="send" s={14} />{dirty && !pending ? 'Review change and send' : 'Approve and send'}</button></Gated>
          <Gated action="discard" label="Discard"><button className="btn d" onClick={() => app.discardDraft(d.id)}>Discard</button></Gated>
          <Gated action="hold" label="Hold"><button className="btn" onClick={() => app.holdDraft(d.id)}><Icon n="pause" s={13} />Hold</button></Gated>
          {r ? <button className="btn" onClick={() => app.nav('#/renewal/' + r.id)}>Open briefing</button> : null}
          <span className="note">Also in the reviewer's Outlook drafts folder · one outstanding touch per renewal per party</span>
        </>}
      </div>
    </div> : null}
  </div>;
}

function BriefCard({ g }) {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const [open, setOpen] = oS(false);
  const [done, setDone] = oS(false);
  const covers = g.drafts.map((d) => MD.byId[d.renewal]).filter(Boolean);
  const a = g.advisor;
  const text = 'Dear ' + a.name.split(' ')[0] + ',\n\nHere is where your Madison renewals stand as of ' + dt(new Date(MD.TODAY).toISOString(), false) + '. ' + covers.length + ' of your ' + a.policies.length + ' active renewals need something this week.\n\n' +
    covers.map((r, i) => (i + 1) + '. ' + r.account + ' (' + r.policy + ')\n' + AG.openC(r).map((c) => '   · ' + c.item + ' — owing ' + c.owing + ', open ' + c.age + ' days' + (c.daysTo < 0 ? ', ' + Math.abs(c.daysTo) + ' days past the ' + c.dl + ' deadline' : ', ' + c.daysTo + ' days to the ' + c.dl + ' deadline')).join('\n')).join('\n\n') +
    '\n\nSelection closes ' + MD.dl('selection') + '. If any of these are stuck on your side, tell me which and I will work the sequence with you rather than sending separate reminders.\n\nAlex Reyes\nMadison Insurance Group';
  return <div className={'ocard' + (open ? ' on' : '')}>
    <div className="ocard-h" onClick={() => setOpen(!open)}>
      <div className="ob">
        <div className="row" style={{ gap: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{a.name}</span>
          <span className="sm dim">{a.firm} · {a.policies.length} policies · last touch {rel(a.lastTouch)}</span>
          <span className="pill t-purple"><Icon n="layers" s={10} />Advisor book brief</span>
        </div>
        <div className="decision">Combine {covers.length} renewal requests into one advisor update</div>
        <div className="why"><b>Why the agent prepared this.</b> Sent separately, {a.name.split(' ')[0]} would receive <b>{covers.length} engine messages today</b> across unrelated accounts. The brief keeps each account in its own section so nothing loses its specific ask.</div>
        <div className="dcard-chips">{covers.map((r) => <span className="chip" key={r.id}><i className="cd" />{r.account}</span>)}</div>
      </div>
      <div className="or"><AutoTag v="prepared" /><span className="reasoning-link">{open ? 'Hide brief' : 'Review brief'}<Icon n={open ? 'chevron-up' : 'arrow-right'} s={13} /></span></div>
    </div>
    {open ? <div className="mail">
      <div className="covered">{covers.map((r) => <div className="cv" key={r.id}>
        <b style={{ flex: '0 0 220px' }}>{r.account}</b>
        <span className="sm mut trunc">{AG.openC(r).map((c) => c.item).join(' · ') || 'no open condition'}</span>
        <span className="cx">{(AG.prim(r) || {}).owing || '—'} · {(AG.prim(r) || {}).age || 0}d</span>
      </div>)}</div>
      <textarea className="mailbody" defaultValue={text} spellCheck={false} />
      <div className="dbar" style={{ marginTop: 14 }}>
        {done ? <span className="decided approved"><Icon n="check" s={15} />Sent · {covers.length} individual drafts closed</span> : <>
          <Gated action="send" label="Approve brief"><button className="btn p" onClick={() => { app.sendBrief(a.id, covers.map((r) => r.id)); setDone(true); }}><Icon n="send" s={14} />Approve and send brief</button></Gated>
          <button className="btn" onClick={() => app.nav('#/renewal/' + covers[0].id)}>Open first renewal</button>
          <span className="note">Approving closes the {covers.length} individual drafts this replaces</span>
        </>}
      </div>
    </div> : null}
  </div>;
}

function OutreachScreen() {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const ready = MD.drafts.filter((d) => d.state === 'ready');
  const groups = AG.consolidationGroups();
  const held = MD.drafts.filter((d) => d.state === 'held');
  const supp = MD.drafts.filter((d) => d.state === 'suppressed');
  const sent = MD.drafts.filter((d) => d.state === 'sent');
  const client = ready.filter((d) => !d.internal && !d.consolidateWith);
  const consolidatable = ready.filter((d) => d.consolidateWith);
  const internal = ready.filter((d) => d.internal);

  return <div className="ag-canvas">
    <div className="ph">
      <div className="ph-row">
        <div className="grow">
          <h1>Prepared outreach</h1>
          <p className="sub">The agent prepared <b>{ready.length + held.length} communications</b> this morning, <b>consolidated {groups.length} advisor book{groups.length === 1 ? '' : 's'}</b>, and <b>withheld {supp.length}</b> that would have duplicated a message already in flight. Each one leads with the decision it represents — the message is underneath.</p>
        </div>
        <span className="ph-badge"><Icon n="mail" s={14} />{ready.length} awaiting approval</span>
      </div>
    </div>

    {groups.length ? <div className="secwrap">
      <div className="sec"><span className="st">Advisor consolidations</span><span className="sn">{groups.length}</span><span className="snote">One advisor, one message per day</span></div>
      {groups.map((g) => <BriefCard key={g.advisor.id} g={g} />)}
    </div> : null}

    <div className="secwrap">
      <div className="sec"><span className="st">Needs approval</span><span className="sn">{client.length + consolidatable.length}</span><span className="snote">Client and advisor outreach</span></div>
      {consolidatable.length ? <div className="note purple" style={{ marginBottom: 12 }}><Icon n="layers" s={15} /><span>{consolidatable.length} of these are already covered by an advisor brief above. Sending one individually is available, but it breaks the same-day consolidation.</span></div> : null}
      {client.concat(consolidatable).map((d) => <OutreachCard key={d.id} d={d} />)}
      {!client.length && !consolidatable.length ? <div className="empty"><div className="ei"><Icon n="check" s={17} /></div><b>Nothing waiting for approval</b>Every prepared message has been approved, held, or discarded.</div> : null}
    </div>

    {internal.length ? <div className="secwrap">
      <div className="sec"><span className="st">Internal notes</span><span className="sn">{internal.length}</span><span className="snote">Underwriting and AmRisk · no client contact implied</span></div>
      {internal.map((d) => <OutreachCard key={d.id} d={d} />)}
    </div> : null}

    {held.length ? <div className="secwrap">
      <div className="sec"><span className="st">Held by the agent</span><span className="sn">{held.length}</span><span className="snote">Prepared, then deliberately not sent</span></div>
      {held.map((d) => <OutreachCard key={d.id} d={d} />)}
    </div> : null}

    {supp.length ? <div className="secwrap">
      <div className="sec"><span className="st">Withheld automatically</span><span className="sn">{supp.length}</span><span className="snote">The agent stopped these before they reached anyone</span></div>
      {supp.map((d) => <OutreachCard key={d.id} d={d} />)}
    </div> : null}

    {sent.length ? <div className="secwrap">
      <div className="sec"><span className="st">Approved and sent today</span><span className="sn">{sent.length}</span></div>
      <div className="ledger">{sent.map((d) => <div className="lrow" key={d.id} onClick={() => app.nav('#/renewal/' + d.renewal)}>
        <span className="li"><Icon n="send" s={14} /></span>
        <div className="grow"><div className="lt"><b>{AG.acct(d.renewal)}</b> — {d.subject}</div><div className="lm">{d.category} · to {d.to} · {rel(d.sentAt)}{d.corrections && d.corrections.length ? ' · edited before send (' + d.corrections[d.corrections.length - 1].cat + ')' : ' · sent unchanged'}</div></div>
        <span className="pill t-green"><Icon n="check" s={10} />Sent</span>
      </div>)}</div>
    </div> : null}
  </div>;
}

Object.assign(window, { OutreachScreen, OutreachCard, BriefCard });
