/* Screen B — Renewal Agent Briefing */
const { useState: bS } = React;

function ActionBlock({ r }) {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const [open, setOpen] = bS(null);
  const [done, setDone] = bS(null);
  const rec = r.rec; if (!rec) return null;
  const draft = MD.drafts.find((d) => d.renewal === r.id && (d.state === 'ready' || d.state === 'held'));
  const p = AG.prim(r);
  const dec = window.AG.decisions().find((d) => d.renewal === r.id);
  const tone = rec.action === 'Hold' || rec.action === 'Review exception' ? 'blocked' : p && (p.pressure === 'crit' || p.pressure === 'overdue') ? 'today' : 'week';
  const autonomy = rec.action === 'Hold' || rec.action === 'Review exception' ? 'blocked' : rec.action === 'Draft outreach' || rec.action === 'Consolidate' ? 'prepared' : rec.action === 'Await external response' || rec.action === 'No action required' ? 'monitor' : 'recommends';
  const reasoning = dec ? dec.reasoning : {
    condition: p ? p.cat + ' · ' + p.item : 'No open condition',
    age: p ? p.age + ' days' : '—',
    attempts: p ? (p.attempts || 'none') + (p.lastAttempt !== null ? ' · last ' + (p.lastAttempt === 0 ? 'today' : p.lastAttempt + 'd ago') : '') : '—',
    response: p && p.lastAttempt !== null ? 'None observed since the last attempt' : 'No attempt made yet',
    deadline: p ? (p.daysTo < 0 ? Math.abs(p.daysTo) + ' days past the ' + p.dl + ' deadline' : p.daysTo + ' days to the ' + p.dl + ' deadline') : '—',
    conclusion: rec.why.join(' '),
    alt: rec.ifNothing ? 'If nothing happens: ' + rec.ifNothing : '',
  };
  return <div className={'dcard ' + tone} style={{ marginBottom: 20 }}>
    <div className="acc" />
    <div className="grow" style={{ minWidth: 0 }}>
      <div style={{ display: 'flex' }}>
        <div className="dcard-b">
          <div className="dcard-h"><span className="eyebrow">Recommended next action</span></div>
          <div className="verb">{rec.action === 'Draft outreach' ? (draft ? 'Send the prepared message to ' + draft.to.split('@')[0].replace(/[._]/g, ' ') : 'Send prepared outreach') : rec.action}</div>
          <div className="body">{rec.target !== '—' ? <><b>Target.</b> {rec.target}<br /></> : null}<b>Why now.</b> {rec.why[0]}</div>
          <div className="dcard-chips">
            {p ? <span className="chip red"><i className="cd" />{p.cat} · {p.age} days</span> : null}
            {p ? <span className={'chip ' + (p.daysTo < 0 ? 'red' : p.daysTo <= 14 ? 'amber' : '')}><i className="cd" />{p.daysTo < 0 ? Math.abs(p.daysTo) + ' days past ' + p.dl : p.daysTo + ' days to ' + p.dl}</span> : null}
            <span className="chip"><i className="cd" />{rec.urgency}</span>
          </div>
        </div>
        <div className="dcard-r">
          <span className="when">{rec.approval === 'None' || rec.approval === 'No action required' ? 'No approval needed' : rec.approval}</span>
          <AutoTag v={autonomy} />
          <button className="reasoning-link" onClick={() => setOpen(open === 'r' ? null : 'r')}>{open === 'r' ? 'Hide reasoning' : 'Open reasoning'}<Icon n={open === 'r' ? 'chevron-up' : 'arrow-right'} s={13} /></button>
        </div>
      </div>
      {open === 'r' ? <Reasoning d={{ renewal: r.id, reasoning }} /> : null}
      {open === 'm' && draft ? <div className="rpanel">
        <div className="row" style={{ marginBottom: 10 }}><span className="eyebrow">Prepared message</span><span className="grow" /><span className="sm mut">{draft.category}</span></div>
        <div className="kv" style={{ gridTemplateColumns: '56px 1fr', marginBottom: 10 }}>
          <span className="k">To</span><span className="v">{draft.to}</span><span className="k">CC</span><span className="v">{draft.cc || '—'}</span>
          <span className="k">Subject</span><span className="v" style={{ fontWeight: 600 }}>{draft.subject}</span>
        </div>
        <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '14px 16px', fontSize: 13.5, lineHeight: 1.68, whiteSpace: 'pre-wrap', color: 'var(--text-2)', maxHeight: 260, overflow: 'auto' }}>{draft.body}</div>
      </div> : null}
      <div className="dbar">
        {done ? <><span className="decided approved"><Icon n="check" s={15} />{done}</span><span className="note">Recorded by {app.user.name}</span></>
          : <>
            {draft ? <Gated action="send" label="Approve and send"><button className="btn p" onClick={() => { app.sendDraft(draft.id); setDone('Approved · sent to ' + draft.to); }}>Approve and send</button></Gated>
              : <Gated action="hold" label="Approve"><button className="btn p" onClick={() => { app.humanAction(r, 'classify', rec.action); setDone(rec.action + ' recorded'); }}>Approve recommendation</button></Gated>}
            {draft ? <button className="btn" onClick={() => setOpen(open === 'm' ? null : 'm')}><Icon n="eye" s={13} />{open === 'm' ? 'Hide message' : 'Read the message'}</button> : null}
            {draft ? <button className="btn" onClick={() => app.nav('#/outreach')}><Icon n="edit" s={13} />Adjust</button> : null}
            <button className="btn" onClick={() => { app.humanAction(r, 'hold', 'Held from the briefing'); setDone('Held · no message sent'); }}><Icon n="pause" s={13} />Hold</button>
            <span className="note">{autonomy === 'monitor' ? 'The agent is watching this and does not recommend contact today.' : 'Nothing sends until you approve.'}</span>
          </>}
      </div>
    </div>
  </div>;
}

function BriefingScreen({ id }) {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const r = MD.byId[id];
  const [tab, setTab] = bS('timeline');
  const [ev, setEv] = bS(null);
  if (!r) return <div className="ag-canvas"><div className="empty"><div className="ei"><Icon n="search" s={17} /></div><b>Renewal not found</b>No renewal with id {id} in this cycle.</div></div>;
  const a = AG.advOf(r);
  const oc = AG.openC(r);
  const res = r.conditions.filter((c) => c.status === 'resolved').concat(r.resolvedConds || []);
  const [lead, detail, close] = AG.assess(r);
  const ranked = oc.slice().sort((x, y) => { const p = { overdue: 0, crit: 1, tight: 2, ok: 3 }; return (p[x.pressure] - p[y.pressure]) || (y.age - x.age); });
  const emails = (r.timeline || []).filter((e) => e.src === 'email');

  return <div className="ag-canvas">
    <div className="ph">
      <div className="ph-row">
        <div className="grow">
          <h1>{r.account}</h1>
          <p className="sub" style={{ fontSize: 13.5, marginTop: 7 }}>{r.policy} · {a ? a.name + ' · ' + a.firm : 'No referring advisor on record'} · Salesforce position <b>{r.stage}</b> for {Math.round((MD.TODAY - new Date(r.stageSince)) / MD.DAY)} days</p>
        </div>
        <span className="ph-badge" style={oc.length > 1 ? { background: 'var(--tint-red)', borderColor: 'rgba(229,107,111,.25)', color: 'var(--red-deep)' } : null}>
          <Icon n={oc.length ? 'alert' : 'check'} s={14} />{oc.length ? oc.length + ' condition' + (oc.length > 1 ? 's' : '') + ' active' : 'Nothing blocking'}
        </span>
      </div>
    </div>

    <div className="assess">
      <div className="head">
        <span className="li" style={{ width: 32, height: 32, borderRadius: 999, background: 'var(--tint-purple)', color: 'var(--purple-deep)', display: 'grid', placeItems: 'center' }}><Icon n="activity" s={15} /></span>
        <div className="grow"><span className="eyebrow">Agent assessment</span><h2 style={{ marginTop: 3 }}>{lead}</h2></div>
        <span className="src engine" style={{ flex: '0 0 auto' }}><i className="sd" />Evaluated {rel(r.lastEval)}</span>
      </div>
      <p className="prose" dangerouslySetInnerHTML={{ __html: detail }} />
      <p className="prose" dangerouslySetInnerHTML={{ __html: close }} />
      <div className="profile-strip" style={{ marginTop: 18 }}>
        {[['Submission', MD.dl('submission'), MD.daysTo(MD.dl('submission'))], ['Selection', MD.dl('selection'), MD.daysTo(MD.dl('selection'))], ['Payment', MD.dl('payment'), MD.daysTo(MD.dl('payment'))]].map((d) => <div className="ps-cell" key={d[0]}>
          <div className="ps-l">{d[0]} deadline</div>
          <div className="ps-v" style={{ color: d[2] < 0 ? 'var(--red-deep)' : d[2] <= 14 ? 'var(--amber-deep)' : 'var(--text)' }}>{d[2] < 0 ? Math.abs(d[2]) + ' days over' : d[2] + ' days'}</div>
          <div className="xs dim" style={{ marginTop: 2 }}>{d[1]}</div>
        </div>)}
        <div className="ps-cell"><div className="ps-l">Prior premium</div><div className="ps-v">{money(r.premiumPrior)}</div><div className="xs dim" style={{ marginTop: 2 }}>2025 term</div></div>
        <div className="ps-cell"><div className="ps-l">Last touch</div><div className="ps-v" style={{ fontSize: 14 }}>{rel(r.lastTouch)}</div><div className="xs dim" style={{ marginTop: 2 }}>{a ? 'advisor ' + rel(a.lastTouch) : 'no advisor'}</div></div>
      </div>
    </div>

    <ActionBlock r={r} />

    <div className="secwrap">
      <div className="sec"><span className="st">Active conditions</span><span className="sn">{oc.length}</span><span className="snote">Ranked by what actually needs action — not all equal</span></div>
      <div className="signals">
        {ranked.map((c, i) => <div className={'sig' + (i === 0 ? ' rank1' : '')} key={c.id}>
          <div className="st"><span className="bcode">{c.cat}</span>
            <span className={'pill ' + (c.pressure === 'overdue' || c.pressure === 'crit' ? 't-red' : c.internal ? 't-slate' : 't-amber')}>{c.internal ? 'Monitoring' : c.pressure === 'overdue' ? 'Critical' : c.pressure === 'crit' ? 'Critical' : 'Waiting'}</span>
            {i === 0 && !c.internal ? <span className="grow" /> : null}
            {i === 0 && !c.internal ? <span className="xs" style={{ color: 'var(--red-deep)', fontWeight: 700 }}>ACTION</span> : null}
          </div>
          <div className="sname">{c.item}</div>
          <div className="smeta">{c.owing} · open {c.age} days · {c.attempts} attempt{c.attempts === 1 ? '' : 's'} · {c.daysTo < 0 ? Math.abs(c.daysTo) + 'd past ' + c.dl : c.daysTo + 'd to ' + c.dl}</div>
          <div className="sfoot row" style={{ gap: 8 }}>
            <span className="grow trunc" style={{ color: 'var(--text-muted)' }}>{c.override ? 'Held: ' + c.override.reason : c.next}</span>
            <button className="reasoning-link" style={{ fontSize: 12 }} onClick={() => setEv(ev === c.id ? null : c.id)}>{ev === c.id ? 'Hide' : 'Why'}</button>
          </div>
          {ev === c.id ? <div style={{ marginTop: 11, borderTop: '1px dashed var(--line-2)', paddingTop: 10 }}>
            {c.evidence.map((e) => <div className="evline" key={e.id} style={{ padding: '7px 0' }}>
              <div className="grow"><div className="row" style={{ gap: 6 }}><b style={{ fontSize: 12 }}>{e.label}</b><span className={'evtag ' + e.type}>{e.type}</span></div><p style={{ fontSize: 12 }}>{e.detail}</p></div>
            </div>)}
          </div> : null}
        </div>)}
        {!oc.length ? <div className="note" style={{ gridColumn: '1/-1' }}><Icon n="check" s={15} style={{ color: 'var(--green-deep)' }} /><span>No open conditions. The agent checked this renewal during the morning run and found nothing obstructing it.</span></div> : null}
      </div>
      {res.length ? <div className="note" style={{ marginTop: 10 }}><Icon n="check" s={15} style={{ color: 'var(--green-deep)' }} /><span><b>{res.length} condition{res.length > 1 ? 's' : ''} resolved automatically</b> — {res.map((c) => c.cat + ' (' + (c.resolved ? c.resolved.how.toLowerCase() : 'resolved') + ')').join('; ')}.</span></div> : null}
    </div>

    {r.close ? <div className="secwrap">
      <div className="sec"><span className="st">Close Chain</span><span className="snote">2026 shadow — stage and compare only, no production writes</span></div>
      <div className="note purple" style={{ display: 'block' }}>
        <div className="row" style={{ gap: 10, marginBottom: 9 }}><Icon n="layers" s={15} /><b>{CLOSE_LABEL[r.close.state] || r.close.state}</b>
          <span className="grow" />
          <span className="pill t-amber">2026 SHADOW</span>
        </div>
        <div className="kv" style={{ gridTemplateColumns: '190px 1fr', color: 'var(--text-2)' }}>
          <span className="k">Client worksheet</span><span className="v">{r.close.worksheet ? r.close.worksheet.name + ' · ' + (r.close.worksheet.parse === 'failed' ? 'parse failed' : 'parsed') : 'not received'}</span>
          <span className="k">AmRisk locked selection</span><span className="v">{r.close.lock ? r.close.lock.name + ' · authoritative' : 'awaiting AmRisk'}</span>
          <span className="k">Release gate</span><span className="v">{gateOpen(r.close.gates) ? 'Eligible at cutover — Phase One takes no action' : 'Blocked · ' + gateReason(r.close.gates)}</span>
        </div>
      </div>
    </div> : null}

    <div className="secwrap">
      <div className="sec"><span className="st">The underlying record</span><span className="snote">The agent's synthesis comes first. This is what it read.</span></div>
      <div className="detail-tabs">
        {[['timeline', 'Timeline', (r.timeline || []).length], ['mail', 'Correspondence', emails.length], ['docs', 'Documents', r.artifacts.length], ['sf', 'Salesforce state', '']].map((t) => <button key={t[0]} className={'tabbtn' + (tab === t[0] ? ' on' : '')} onClick={() => setTab(t[0])}>{t[1]}{t[2] !== '' ? <span className="dim"> {t[2]}</span> : null}</button>)}
      </div>
      <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: '18px 20px' }}>
        {tab === 'timeline' ? <div className="tl">{(r.timeline || []).slice().sort((x, y) => new Date(y.at) - new Date(x.at)).map((e, i) => <div className={'tlev ' + e.src} key={i}>
          <div className="tt">{dt(e.at)}</div><div className="tr"><span className="td" /></div>
          <div className="tc"><div className="row" style={{ gap: 8 }}><b>{e.title}</b><span className={'src ' + e.src}><i className="sd" />{SRC_LABEL[e.src]}</span></div>{e.detail ? <p>{e.detail}</p> : null}</div>
        </div>)}</div> : null}
        {tab === 'mail' ? (emails.length ? emails.map((e, i) => <div key={i} style={{ borderBottom: i < emails.length - 1 ? '1px solid var(--line)' : 'none', padding: '11px 0' }}>
          <div className="row"><b style={{ fontSize: 13.5 }}>{e.title}</b><span className="grow" /><span className="xs dim">{dt(e.at)}</span></div>
          <p className="sm mut" style={{ margin: '3px 0 0', lineHeight: 1.55 }}>{e.detail}</p>
        </div>) : <div className="sm mut">No correspondence has been observed on this renewal.</div>) : null}
        {tab === 'docs' ? (r.artifacts.length ? <div className="col" style={{ gap: 9 }}>{r.artifacts.map((x, i) => <div className="row" key={i} style={{ gap: 12, paddingBottom: 9, borderBottom: i < r.artifacts.length - 1 ? '1px solid var(--line)' : 'none' }}>
          <span className="li" style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--surface-2)', color: 'var(--text-muted)', display: 'grid', placeItems: 'center' }}><Icon n="file" s={13} /></span>
          <div className="grow"><div className="row" style={{ gap: 8 }}><b style={{ fontSize: 13 }}>{x.name}</b>{x.authoritative ? <span className="pill t-amber"><Icon n="lock" s={10} />Authoritative</span> : null}</div>
            <div className="xs dim">{x.type} · {x.source} · {dt(x.at, false)}{x.confidence ? ' · match ' + x.confidence : ''}</div></div>
          <span className={'pill ' + (x.filing === 'filed' ? 't-green' : x.filing === 'failed' || x.filing === 'unsupported' ? 't-red' : 't-amber')}>{x.filing === 'filed' ? 'Filed' : x.filing === 'awaiting-match' ? 'Awaiting match' : x.filing === 'failed' ? 'Filing failed' : x.filing === 'conflict' ? 'Superseded' : 'Unsupported'}</span>
        </div>)}</div> : <div className="sm mut">Nothing has been received or filed against this renewal.</div>) : null}
        {tab === 'sf' ? <div className="kv" style={{ gridTemplateColumns: '190px 1fr' }}>
          <span className="k">Stage</span><span className="v">{r.stage} · since {dt(r.stageSince, false)}</span>
          <span className="k">Renewal id</span><span className="v mono">{r.id}</span>
          <span className="k">Policy</span><span className="v mono">{r.policy}</span>
          <span className="k">Referring advisor</span><span className="v">{a ? a.name + ' (' + a.firm + ')' : 'empty — flagged as an exception'}</span>
          <span className="k">Primary contact</span><span className="v">{r.contact.name} · {r.contact.title} · {r.contact.email}</span>
          <span className="k">Renewal term</span><span className="v">{r.term}</span>
          <span className="k">Priority</span><span className="v">{r.priority}</span>
          <span className="k">Last external activity</span><span className="v">{rel(r.lastActivity)}</span>
          <span className="k">Audit</span><span className="v">Every engine assessment and human decision on this renewal is written back to Salesforce as the audit ledger.</span>
        </div> : null}
      </div>
    </div>
  </div>;
}

Object.assign(window, { BriefingScreen, ActionBlock });
