/* Aster Risk Desk (internal) — Console theme. */

function RiskDeskApp() {
  const store = useAsterStore();
  const [noteDrafts, setNoteDrafts] = React.useState({});
  const [generating, setGenerating] = React.useState({});
  const [staleFilter, setStaleFilter] = React.useState('all');
  const [toast, setToast, toastNode] = useToast();

  const needsReview = store.calls.filter(function (c) { return c.status === 'submitted' || (c.status === 'reviewed' && !c.orgNote); });
  const staleAll = store.villages
    .map(function (v) { return { v: v, syn: store.synthesis[v.id] }; })
    .filter(function (x) { return !x.syn.reviewed; })
    .sort(function (a, b) { return window.AsterStore.levelRank(b.syn.level) - window.AsterStore.levelRank(a.syn.level); });
  const stale = staleAll.filter(function (x) { return staleFilter === 'all' || x.syn.level === staleFilter; });
  const severeCount = store.villages.filter(function (v) { return store.synthesis[v.id].level === 'severe'; }).length;

  const staleCounts = { all: staleAll.length };
  ['severe', 'warning', 'watch', 'calm'].forEach(function (l) {
    staleCounts[l] = staleAll.filter(function (x) { return x.syn.level === l; }).length;
  });

  function runSynthesis(villageId) {
    setGenerating(function (g) { return Object.assign({}, g, { [villageId]: true }); });
    setTimeout(function () {
      window.AsterStore.generateSynthesis(villageId);
      setGenerating(function (g) { return Object.assign({}, g, { [villageId]: false }); });
      setToast('Synthesis refreshed — flagged for analyst review.');
    }, 1400);
  }

  return (
    <div style={{ maxWidth: 1000, margin: '0 auto', padding: 'var(--space-6) var(--space-5) var(--space-11)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 'var(--space-6)' }}>
        <div>
          <div style={{ font: '600 11px var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>Internal</div>
          <h1 style={{ margin: '2px 0 0', font: '700 22px var(--font-display)', color: 'var(--text-strong)' }}>Aster Risk Desk</h1>
        </div>
        <div style={{ display: 'flex', gap: 'var(--space-6)', flexWrap: 'wrap' }}>
          <Stat label="Awaiting review" value={needsReview.length} tone={needsReview.length > 0 ? 'warning' : 'neutral'} />
          <Stat label="Stale syntheses" value={staleAll.length} />
          <Stat label="Severe villages" value={severeCount} tone={severeCount > 0 ? 'severe' : 'neutral'} />
        </div>
      </div>

      <SectionHeading eyebrow="Queue" title={'Calls for help needing review (' + needsReview.length + ')'}
        hint="Highest-severity villages first. Add a coordination note so the org has context." />
      {needsReview.length === 0 && <EmptyState icon="check-circle" text="Nothing waiting on risk-desk review right now." />}
      {needsReview.map(function (c) {
        const v = window.AsterStore.findVillage(c.villageId);
        const syn = store.synthesis[c.villageId];
        const draft = noteDrafts[c.id] || '';
        return (
          <Card key={c.id} padding="md" elevation="sm" className="ap-rise" style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
              <div>
                <div style={{ font: '600 14px var(--font-text)', color: 'var(--text-strong)' }}>{v.name} <span style={{ color: 'var(--text-subtle)', fontWeight: 400 }}>· {v.township}, {v.region}</span></div>
                <div style={{ font: '12px var(--font-text)', color: 'var(--text-muted)', marginTop: 2 }}>{c.type === 'protocol' ? 'Applying to ' + window.AsterStore.findProtocol(c.protocolId).name : 'General distress signal'} · submitted {fmtRelative(c.submittedAt)}</div>
              </div>
              <Badge tone={syn.level}>{LEVEL_LABEL[syn.level]}</Badge>
            </div>
            {c.message && <div style={{ font: '13px/1.5 var(--font-text)', color: 'var(--text-body)', marginTop: 8 }}>{c.message}</div>}
            <div style={{ display: 'flex', gap: 'var(--space-6)', flexWrap: 'wrap', margin: '10px 0', alignItems: 'center' }}>
              <Stat label="Composite" value={syn.composite} unit="/100" />
              <Stat label="Confidence" value={syn.confidence} />
              <Stat label="Lead time" value={syn.leadTime} />
              <Sparkline points={store.trends[v.id].composite} color={LEVEL_COLOR[syn.level]} width={90} height={26} fill={false} />
            </div>
            <ul style={{ margin: '0 0 10px', paddingLeft: 18, font: '13px/1.6 var(--font-text)', color: 'var(--text-body)' }}>
              {syn.keyDrivers.map(function (d, i) { return <li key={i}>{d}</li>; })}
            </ul>
            <Textarea rows={2} value={draft} maxLength={280}
              onChange={function (e) { setNoteDrafts(Object.assign({}, noteDrafts, { [c.id]: e.target.value })); }}
              placeholder="Add a coordination note for the humanitarian organization (optional)…" />
            <div style={{ marginTop: 8 }}>
              <Button variant="primary" size="sm" iconLeft={Ic('send', { width: 13, height: 13 })}
                onClick={function () { window.AsterStore.riskDeskReview(c.id, draft || null); setToast('Reviewed and relayed to ' + window.AsterStore.ORG.name + '.'); }}>
                Review &amp; relay
              </Button>
            </div>
          </Card>
        );
      })}

      <div style={{ marginTop: 'var(--space-8)' }}>
        <SectionHeading eyebrow="Monitoring" title="Villages awaiting a fresh synthesis"
          right={<FilterChips size="sm" active={staleFilter} onChange={setStaleFilter} items={[
            { id: 'all', label: 'All', count: staleCounts.all },
            { id: 'severe', label: 'Severe', count: staleCounts.severe, color: 'var(--severe)' },
            { id: 'warning', label: 'Warning', count: staleCounts.warning, color: 'var(--warning)' },
            { id: 'watch', label: 'Watch', count: staleCounts.watch, color: 'var(--watch)' },
            { id: 'calm', label: 'Calm', count: staleCounts.calm, color: 'var(--calm)' },
          ]} />} />
        {stale.length === 0 && <EmptyState icon="check-circle" text={staleFilter === 'all' ? 'All syntheses are current.' : 'No ' + LEVEL_LABEL[staleFilter] + '-level villages awaiting synthesis.'} />}
        {stale.length > 0 && (
          <Card padding="none" elevation="sm">
            {stale.map(function (x) {
              const busy = !!generating[x.v.id];
              return (
                <div key={x.v.id} className="ap-row" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 16px', borderBottom: '1px solid var(--border-subtle)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                    <Badge tone={x.syn.level}>{LEVEL_LABEL[x.syn.level]}</Badge>
                    <span style={{ font: '13px var(--font-text)', color: 'var(--text-strong)' }}>{x.v.name}</span>
                    <span style={{ font: '12px var(--font-text)', color: 'var(--text-subtle)' }}>{x.v.township}, {x.v.region}</span>
                    <span style={{ font: '11px var(--font-mono)', color: 'var(--text-subtle)' }}>last generated {fmtRelative(x.syn.lastGenerated)}</span>
                  </div>
                  <Button variant="secondary" size="sm" disabled={busy} onClick={function () { runSynthesis(x.v.id); }}>
                    {busy ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><span className="ap-spinner" /> Generating…</span> : 'Generate synthesis'}
                  </Button>
                </div>
              );
            })}
          </Card>
        )}
      </div>
      {toastNode}
    </div>
  );
}
