/* Remaining sections in the agent-first language: autonomy, sources, book, advisors, close */
const { useState: rS } = React;

/* ---------------- Agent autonomy ---------------- */
const LADDER = [
  { mode: 'Autopilot Enabled', title: 'I handle these alone', note: 'Composed and sent without review, inside the conditions you set', auto: 'handled' },
  { mode: 'Eligible for Consideration', title: "I'm ready to handle these — your call", note: 'Sustained low edit and discard rates. I recommend promotion; I cannot promote myself', auto: 'prepared' },
  { mode: 'Review Required', title: 'You review every one', note: 'I prepare, you approve', auto: 'recommends' },
  { mode: 'Autopilot Suspended', title: 'Returned to review', note: 'Autonomy withdrawn after the numbers moved', auto: 'blocked' },
];
function Spark({ v }) {
  const max = Math.max.apply(null, v);
  return <span className="row" style={{ gap: 2, alignItems: 'flex-end', height: 18 }}>{v.map((x, i) => <i key={i} style={{ width: 6, height: Math.max(2, (x / max) * 18), background: i === v.length - 1 ? 'var(--blue)' : 'var(--line-strong)', display: 'block', borderRadius: 1 }} />)}</span>;
}
function AutonomyScreen() {
  const app = useApp(); const MD = window.MD;
  const [open, setOpen] = rS(null);
  const enabled = MD.automation.filter((a) => a.mode === 'Autopilot Enabled').length;
  return <div className="ag-canvas">
    <div className="ph"><div className="ph-row"><div className="grow">
      <h1>Agent autonomy</h1>
      <p className="sub">What I send alone, what I prepare for you, and what I will never do without you — per communication category. <b>I am running {enabled} category on autopilot</b> and reviewing the rest. I can recommend promotion; only an administrator grants it.</p>
    </div><span className="ph-badge"><Icon n="shield" s={14} />Human-controlled</span></div></div>

    {LADDER.map((L) => {
      const cats = MD.automation.filter((a) => a.mode === L.mode);
      if (!cats.length) return null;
      return <div className="secwrap" key={L.mode}>
        <div className="sec"><span className="st">{L.title}</span><span className="sn">{cats.length}</span><span className="snote">{L.note}</span></div>
        {cats.map((a) => <div className={'dcard ' + (L.mode === 'Autopilot Enabled' ? 'week' : L.mode === 'Autopilot Suspended' ? 'blocked' : '')} key={a.cat}>
          <div className="acc" />
          <div className="grow" style={{ minWidth: 0 }}>
            <div style={{ display: 'flex' }}>
              <div className="dcard-b">
                <div className="dcard-h"><span className="who">{a.cat}</span><span className="meta mono">{a.b}</span></div>
                <div className="body" style={{ marginTop: 6 }}>{a.note}</div>
                <div className="dsig">
                  <span className={'cf ' + (a.edit < 0.12 ? 'high' : a.edit < 0.22 ? 'moderate' : 'blocked')}><i className="cd" />{pct(a.edit)} edited before send</span>
                  <span className="dot">·</span><span>{pct(a.discard)} discarded</span>
                  <span className="dot">·</span><span>{pct(a.exc)} produced an exception</span>
                  <span className="dot">·</span><span>{a.volume} composed this cycle</span>
                </div>
                <div className="dcard-chips">
                  <span className="chip"><i className="cd" />{a.inReview === '—' ? 'no review period' : a.inReview + ' in review'}</span>
                  <span className="chip"><i className="cd" />control changed {dt(a.changedAt, false)} by {a.owner}</span>
                  {a.locked ? <span className="chip amber"><i className="cd" />locked by communications policy</span> : null}
                </div>
              </div>
              <div className="dcard-r">
                <AutoTag v={L.auto} />
                <Spark v={a.trend} />
                <span className="xs dim">correction trend</span>
              </div>
            </div>
            <div className="dbar">
              {a.mode === 'Autopilot Enabled'
                ? <Gated action="automation" label="Return to review"><button className="btn p" onClick={() => app.setAutomation(a.cat, 'Review Required')}><Icon n="pause" s={13} />Return to review</button></Gated>
                : <Gated action="automation" label="Grant autonomy"><button className="btn p" disabled={a.locked || a.mode === 'Review Required'} onClick={() => app.setAutomation(a.cat, 'Autopilot Enabled')}><Icon n="play" s={13} />Grant autonomy for this category</button></Gated>}
              {a.mode === 'Autopilot Suspended' ? <Gated action="automation" label="Return to review"><button className="btn" onClick={() => app.setAutomation(a.cat, 'Review Required')}>Return to review</button></Gated> : null}
              <button className="btn" onClick={() => setOpen(open === a.cat ? null : a.cat)}><Icon n="eye" s={13} />{open === a.cat ? 'Hide conditions' : 'Conditions and rollback'}</button>
              <span className="note">{a.locked ? 'Monetary content — never eligible in Phase One.' : a.mode === 'Autopilot Enabled' ? 'Review restores automatically if the edit rate exceeds 15% over a rolling week.' : 'I never promote myself.'}</span>
            </div>
            {open === a.cat ? <div className="rpanel">
              <div className="rgrid">
                <div><span className="l">Applies to</span><span className="v mono">{a.b}</span></div>
                <div><span className="l">Volume</span><span className="v">{a.volume} messages</span></div>
                <div><span className="l">Edit rate</span><span className="v">{pct(a.edit)}</span></div>
                <div><span className="l">Discard rate</span><span className="v">{pct(a.discard)}</span></div>
                <div><span className="l">Exception rate</span><span className="v">{pct(a.exc)}</span></div>
                <div><span className="l">Decision owner</span><span className="v">{a.owner}</span></div>
              </div>
              <div className="rconc"><b>Rollback.</b> Any category returns to review immediately and takes effect on the next evaluation — nothing in flight is sent. Coverage, actuarial output, and policy documents stay human-controlled regardless of category performance.</div>
            </div> : null}
          </div>
        </div>)}
      </div>;
    })}

    <div className="secwrap">
      <div className="sec"><span className="st">Control history</span><span className="snote">Who changed what, when, and why</span></div>
      <div className="feed-list">{MD.automationLog.map((l, i) => <div className="feed-event" key={i}>
        <span className={'fe-icon ' + (l.who === 'System' ? 'run' : 'override')}><Icon n="user" s={14} /></span>
        <div className="grow"><div className="fe-text"><b>{l.what}</b></div><div className="fe-meta"><span className="fe-actor">{l.who}</span><span>·</span><span>{dt(l.at, false)}</span><span>·</span><span>{l.why}</span></div></div>
      </div>)}</div>
    </div>
  </div>;
}

/* ---------------- Source activity ---------------- */
function SourcesScreen() {
  const app = useApp(); const MD = window.MD; const h = MD.health;
  const stale = h.email.groups.filter((g) => g.state === 'stale');
  const affected = (MD.exceptions.find((x) => x.id === 'X11') || {}).affected || [];
  return <div className="ag-canvas">
    <div className="ph"><div className="ph-row"><div className="grow">
      <h1>What I can see</h1>
      <p className="sub">Every conclusion I draw comes from Salesforce and the Microsoft email estate. <b>{stale.length ? stale.length + ' mailbox group is stale' : 'All sources are current'}</b>, so there {stale.length ? 'are renewals I will not draw conclusions about yet' : 'is nothing I am blind to right now'}.</p>
    </div><span className="ph-badge"><Icon n="check" s={14} />Last full pass {rel(h.engine.lastFull)}</span></div></div>

    <div className="secwrap">
      <div className="sec"><span className="st">Sources</span><span className="snote">Read access, write availability, freshness</span></div>
      <div className="ledger">
        <div className="lrow" style={{ cursor: 'default' }}>
          <span className="li"><Icon n="database" s={14} /></span>
          <div className="grow"><div className="lt"><b>Salesforce</b> — system of record and audit ledger</div>
            <div className="lm">Certificate OAuth, integration user, API only · last read {rel(h.salesforce.lastRead)} · last write {rel(h.salesforce.lastWrite)} · {h.salesforce.queued} writes queued</div></div>
          <span className="pill t-green"><Icon n="check" s={10} />Read + write</span>
        </div>
        {h.email.groups.map((g) => <div className="lrow" key={g.name} style={{ cursor: 'default' }}>
          <span className={'li ' + (g.state === 'stale' ? 'slate' : 'blue')}><Icon n="mail" s={14} /></span>
          <div className="grow"><div className="lt"><b>{g.name}</b></div><div className="lm">Observed within Madison-defined mailbox boundaries · last observation {rel(g.last)}</div></div>
          <span className={'pill ' + (g.state === 'stale' ? 't-amber' : 't-green')}><Icon n={g.state === 'stale' ? 'alert' : 'check'} s={10} />{g.state === 'stale' ? 'Stale' : 'Current'}</span>
        </div>)}
        <div className="lrow" style={{ cursor: 'default' }}>
          <span className="li"><Icon n="activity" s={14} /></span>
          <div className="grow"><div className="lt"><b>Renewal agent</b> — evaluation engine</div>
            <div className="lm">Last full-book pass {rel(h.engine.lastFull)} across {h.engine.evaluated} renewals · {h.engine.failed24} failed evaluations in 24h · queue {h.engine.queue}</div></div>
          <span className="pill t-green"><Icon n="check" s={10} />Idle</span>
        </div>
      </div>
    </div>

    {stale.length ? <div className="secwrap">
      <div className="sec"><span className="st">What I will not conclude</span><span className="sn">{affected.length}</span><span className="snote">Absence of a reply is not a fact while a source is stale</span></div>
      <div className="note amber" style={{ display: 'block', marginBottom: 12 }}>
        <div className="row" style={{ gap: 10, marginBottom: 7 }}><Icon n="alert" s={15} /><b>{stale[0].name} last observed {rel(stale[0].last)}</b></div>
        <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>On these renewals I will say <b>response status currently unverified</b> rather than "no response received", and I defer any action that depends on absence until observation resumes.</div>
      </div>
      <div className="mon">{affected.map((id) => { const r = MD.byId[id]; if (!r) return null; return <div className="mrow" key={id} onClick={() => app.nav('#/renewal/' + id)}>
        <span className="mw">{r.account}</span>
        <span className="mx">{(window.AG.openC(r)[0] || {}).item || 'no open condition'}<div className="xs dim" style={{ marginTop: 2 }}>{r.stage}</div></span>
        <span className="mt"><span className="auto monitor"><i className="ad" />Unverified</span></span>
      </div>; })}</div>
    </div> : null}

    <div className="secwrap">
      <div className="sec"><span className="st">If a source fails</span><span className="snote">What I do instead of guessing</span></div>
      <div className="signals">
        {[['Salesforce unavailable', 'Sends suspend, writes queue, and every action visibly reports itself as blocked. State reconciles before sending resumes.'],
          ['Email unavailable', 'Observation is marked stale. Missing replies are never presented as fact and dependent actions are deferred.'],
          ['Partial data', 'No partial action. I raise an exception rather than act on an incomplete picture.'],
          ['Schema change', 'I surface the assumption that failed instead of continuing on a mapping I can no longer trust.']].map((x) => <div className="sig" key={x[0]}>
            <div className="sname">{x[0]}</div><div className="smeta" style={{ lineHeight: 1.55 }}>{x[1]}</div>
          </div>)}
      </div>
    </div>
  </div>;
}

/* ---------------- Renewal book ---------------- */
const BVIEWS = [
  { id: 'all', label: 'All active', f: (r) => r.stage !== 'Renewed' },
  { id: 'need', label: 'Needs a person', f: (r) => window.AG.needsA(r) },
  { id: 'multi', label: 'Several conditions', f: (r) => window.AG.openC(r).length > 1 },
  { id: 'crit', label: 'Deadline pressure', f: (r) => window.AG.openC(r).some((c) => c.pressure === 'crit' || c.pressure === 'overdue') },
  { id: 'mon', label: 'Monitoring only', f: (r) => r.engine === 'Await external response' || r.engine === 'Internal ageing' },
  { id: 'close', label: 'In the Close Chain', f: (r) => !!r.close },
  { id: 'hold', label: 'Held', f: (r) => !!r.hold || !!r.suppressed },
  { id: 'renewed', label: 'Renewed', f: (r) => r.stage === 'Renewed' },
];
function BookScreen() {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const [view, setView] = rS('all');
  const [q, setQ] = rS('');
  const [page, setPage] = rS(0);
  let rows = MD.renewals.filter((BVIEWS.find((v) => v.id === view) || BVIEWS[0]).f);
  if (q.length > 1) rows = rows.filter((r) => (r.account + ' ' + r.policy + ' ' + r.contact.name).toLowerCase().indexOf(q.toLowerCase()) >= 0);
  const PER = 25;
  const shown = rows.slice(page * PER, page * PER + PER);
  return <div className="ag-canvas wide">
    <div className="ph"><div className="ph-row"><div className="grow">
      <h1>Renewal book</h1>
      <p className="sub">The full inventory — the one place a table earns its keep. I evaluated every row this morning; the ones that need you are on <button className="reasoning-link" style={{ fontSize: 14.5 }} onClick={() => app.nav('#/today')}>today's work</button>.</p>
    </div><span className="ph-badge"><Icon n="building" s={14} />{MD.renewals.length} policies</span></div></div>
    <div className="row" style={{ gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
      {BVIEWS.map((v) => <button key={v.id} className={'tabbtn' + (view === v.id ? ' on' : '')} onClick={() => { setView(v.id); setPage(0); }}>{v.label}<span className="dim"> {MD.renewals.filter(v.f).length}</span></button>)}
      <span className="grow" />
      <input className="mailf" style={{ width: 210 }} value={q} onChange={(e) => { setQ(e.target.value); setPage(0); }} placeholder="Search account, policy, contact" />
    </div>
    <div className="btbl-wrap">
      <table className="btbl">
        <thead><tr><th>Account</th><th>Advisor</th><th>Salesforce position</th><th>What I am waiting on</th><th>Owing</th><th style={{ textAlign: 'right' }}>Age</th><th>Deadline</th><th>My state</th></tr></thead>
        <tbody>{shown.map((r) => { const c = AG.prim(r); const a = AG.advOf(r); const oc = AG.openC(r);
          return <tr key={r.id} onClick={() => app.nav('#/renewal/' + r.id)}>
            <td><b>{r.account}</b><div className="xs dim">{r.policy}</div></td>
            <td className="mut">{a ? a.name : <span className="pill t-amber">No advisor</span>}</td>
            <td className="mut">{r.stage}</td>
            <td>{c ? <span className="row" style={{ gap: 7 }}><span className="bcode">{c.cat}</span><span className="trunc" style={{ maxWidth: 210 }}>{c.item}</span>{oc.length > 1 ? <span className="pill t-night">+{oc.length - 1}</span> : null}</span> : <span className="dim">nothing</span>}</td>
            <td className="mut">{c ? c.owing : '—'}</td>
            <td style={{ textAlign: 'right' }} className={c && c.age >= 14 ? 'hot' : ''}>{c ? c.age + 'd' : '—'}</td>
            <td className={c && c.daysTo < 0 ? 'hot' : ''}>{c ? (c.daysTo < 0 ? Math.abs(c.daysTo) + 'd over' : c.daysTo + 'd') : '—'}</td>
            <td><span className={'auto ' + (AG.needsA(r) ? 'recommends' : r.hold ? 'blocked' : r.stage === 'Renewed' ? 'handled' : 'monitor')}><i className="ad" />{AG.needsA(r) ? 'Needs you' : r.hold ? 'Held' : r.stage === 'Renewed' ? 'Closed' : 'Monitoring'}</span></td>
          </tr>; })}</tbody>
      </table>
      <div className="row" style={{ padding: '11px 16px', gap: 12, borderTop: '1px solid var(--line)', fontSize: 12.5, color: 'var(--text-muted)' }}>
        <button className="btn sm" disabled={!page} onClick={() => setPage(page - 1)}>Previous</button>
        <span>{rows.length ? page * PER + 1 : 0}–{Math.min(rows.length, page * PER + PER)} of {rows.length}</span>
        <button className="btn sm" disabled={page * PER + PER >= rows.length} onClick={() => setPage(page + 1)}>Next</button>
      </div>
    </div>
  </div>;
}

/* ---------------- Advisor briefings ---------------- */
function AdvisorsScreen() {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const groups = AG.consolidationGroups();
  const rows = MD.advisors.filter((a) => a.policies.length).map((a) => {
    const rs = a.policies.map((id) => MD.byId[id]);
    return { a, n: rs.length, need: rs.filter(AG.needsA).length, crit: rs.filter((r) => AG.openC(r).some((c) => c.pressure === 'crit' || c.pressure === 'overdue')).length, drafts: MD.drafts.filter((d) => d.state === 'ready' && rs.some((r) => r.id === d.renewal)).length };
  }).sort((x, y) => y.drafts - x.drafts || y.need - x.need || y.n - x.n);
  return <div className="ag-canvas">
    <div className="ph"><div className="ph-row"><div className="grow">
      <h1>Advisor briefings</h1>
      <p className="sub">Roughly 95% of the book is advisor-originated, so the advisor is the orchestration point. <b>I consolidated {groups.length} book{groups.length === 1 ? '' : 's'} today</b> so nobody receives unrelated engine messages twice in one morning.</p>
    </div><span className="ph-badge"><Icon n="users" s={14} />{rows.length} advisors</span></div></div>
    {groups.length ? <div className="secwrap">
      <div className="sec"><span className="st">Briefs I assembled</span><span className="sn">{groups.length}</span><span className="snote">Ready to review and send</span></div>
      {groups.map((g) => <BriefCard key={g.advisor.id} g={g} />)}
    </div> : null}
    <div className="secwrap">
      <div className="sec"><span className="st">Every advisor book</span><span className="snote">Sorted by what needs attention</span></div>
      <div className="mon">{rows.slice(0, 14).map(({ a, n, need, crit, drafts }) => <div className="mrow" key={a.id} onClick={() => app.nav('#/advisor/' + a.id)}>
        <span className="mw">{a.name}<div className="xs dim" style={{ marginTop: 2 }}>{a.firm}</div></span>
        <span className="mx">{n} active {n === 1 ? 'renewal' : 'renewals'} · {need ? need + ' need a person' : 'none need a person'}{crit ? ' · ' + crit + ' under deadline pressure' : ''}
          <div className="xs dim" style={{ marginTop: 2 }}>last advisor touch {rel(a.lastTouch)}{a.portal !== 'active' ? ' · portal ' + a.portal : ''}</div></span>
        <span className="mt">{drafts > 1 ? <span className="pill t-purple"><Icon n="layers" s={10} />{drafts} prepared</span> : drafts ? <span className="pill t-blue">{drafts} prepared</span> : <span className="auto monitor"><i className="ad" />Clear</span>}</span>
      </div>)}</div>
    </div>
  </div>;
}

function AdvisorBriefing({ id }) {
  const app = useApp(); const MD = window.MD; const AG = window.AG;
  const a = MD.advisors.find((x) => x.id === id);
  if (!a) return <div className="ag-canvas"><div className="empty"><b>Advisor not found</b></div></div>;
  const rs = a.policies.map((x) => MD.byId[x]).filter(Boolean);
  const drafts = MD.drafts.filter((d) => (d.state === 'ready' || d.state === 'held') && rs.some((r) => r.id === d.renewal));
  const need = rs.filter(AG.needsA);
  const groups = {};
  rs.forEach((r) => AG.openC(r).forEach((c) => { (groups[c.cat] = groups[c.cat] || []).push({ r, c }); }));
  const g = AG.consolidationGroups().find((x) => x.advisor.id === id);
  return <div className="ag-canvas">
    <div className="ph"><div className="ph-row"><div className="grow">
      <h1>{a.name}</h1>
      <p className="sub">{a.firm} · {a.email}</p>
    </div><span className="ph-badge"><Icon n="users" s={14} />{rs.length} active policies</span></div></div>
    <div className="assess" style={{ marginBottom: 20 }}>
      <div className="head">
        <span 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 }}>{need.length ? need.length + ' of ' + rs.length + ' renewals in this book need something today.' : 'Nothing in this book needs a person today.'}</h2></div>
      </div>
      <p className="prose">{drafts.length > 1
        ? <>I prepared <b>{drafts.length} separate messages</b> for {a.name.split(' ')[0]} across unrelated accounts{g ? <> and consolidated {g.drafts.length} of them into one brief</> : <> and held them for consolidation</>}. Last advisor contact was {rel(a.lastTouch)}.{a.portal !== 'active' ? ' Their portal access is ' + a.portal + ', so native reminder jobs are not reaching them.' : ''}</>
        : <>The open conditions in this book are spread across {Object.keys(groups).length} categories. Last advisor contact was {rel(a.lastTouch)}.{a.portal !== 'active' ? ' Their portal access is ' + a.portal + ' — native reminders are not landing.' : ''}</>}</p>
      <div className="profile-strip" style={{ marginTop: 18 }}>
        <div className="ps-cell"><div className="ps-l">Active policies</div><div className="ps-v">{rs.length}</div></div>
        <div className="ps-cell"><div className="ps-l">Need a person</div><div className="ps-v" style={{ color: need.length ? 'var(--amber-deep)' : 'var(--text)' }}>{need.length}</div></div>
        <div className="ps-cell"><div className="ps-l">Prepared today</div><div className="ps-v">{drafts.length}</div></div>
        <div className="ps-cell"><div className="ps-l">Last touch</div><div className="ps-v" style={{ fontSize: 14 }}>{rel(a.lastTouch)}</div></div>
        <div className="ps-cell"><div className="ps-l">Portal</div><div className="ps-v" style={{ fontSize: 14, textTransform: 'capitalize' }}>{a.portal}</div></div>
      </div>
    </div>
    {g ? <div className="secwrap"><div className="sec"><span className="st">The brief I assembled</span><span className="snote">One message, {g.drafts.length} accounts</span></div><BriefCard g={g} /></div> : null}
    <div className="secwrap">
      <div className="sec"><span className="st">Book grouped by condition</span><span className="snote">{Object.keys(groups).length} categories · {rs.length} renewals</span></div>
      <div className="mon">{Object.keys(groups).sort().map((cat) => <div key={cat}>
        <div className="row" style={{ padding: '9px 18px', background: 'var(--surface-2)', borderBottom: '1px solid var(--line)', gap: 9 }}>
          <span className="bcode">{cat}</span><b className="sm">{MD.B[cat]}</b><span className="grow" /><span className="sm mut">{groups[cat].length}</span>
        </div>
        {groups[cat].sort((x, y) => x.c.daysTo - y.c.daysTo).map(({ r, c }) => <div className="mrow" key={r.id + c.id} onClick={() => app.nav('#/renewal/' + r.id)}>
          <span className="mw">{r.account}</span>
          <span className="mx">{c.item}<div className="xs dim" style={{ marginTop: 2 }}>{c.owing} · open {c.age}d · {c.attempts} attempt{c.attempts === 1 ? '' : 's'}</div></span>
          <span className="mt" style={{ color: c.daysTo < 0 ? 'var(--red-deep)' : 'inherit' }}>{c.daysTo < 0 ? Math.abs(c.daysTo) + 'd past ' + c.dl : c.daysTo + 'd to ' + c.dl}</span>
        </div>)}
      </div>)}
        {!Object.keys(groups).length ? <div className="empty" style={{ border: 'none' }}><b>Nothing open</b>Every renewal in this book is clear.</div> : null}
      </div>
    </div>
  </div>;
}

Object.assign(window, { AutonomyScreen, SourcesScreen, BookScreen, AdvisorsScreen, AdvisorBriefing, Spark, LADDER });
