/* Private Organization / Microfinance — Console theme. Never has access to village-level identity. */

const VENTURE_OPTIONS = [
  { value: 'general', label: 'General market assessment' },
  { value: 'agri-lending', label: 'Agricultural micro-lending' },
  { value: 'input-supply', label: 'Farm input supply' },
  { value: 'logistics', label: 'Logistics / transport' },
];
const APPETITE_OPTIONS = [
  { value: 'conservative', label: 'Conservative' },
  { value: 'balanced', label: 'Balanced' },
  { value: 'aggressive', label: 'Growth-seeking' },
];

function canned_answer(question, aggregate, appetite) {
  const q = question.toLowerCase();
  const totalVillages = aggregate.regions.reduce(function (s, r) { return s + r.villagesMonitored; }, 0);
  const totalSevereWarning = aggregate.regions.reduce(function (s, r) { return s + r.levelCounts.severe + r.levelCounts.warning; }, 0);
  const worstRegion = aggregate.regions.slice().sort(function (a, b) { return b.avgComposite - a.avgComposite; })[0];

  if (q.indexOf('report') !== -1) {
    return 'Summary report — ' + new Date().toISOString().slice(0, 10) + '\n\n' +
      aggregate.regions.map(function (r) {
        return r.region + ': ' + r.villagesMonitored + ' villages monitored, avg composite risk ' + r.avgComposite + '/100, top driver ' + DOMAIN_LABEL[r.topDomain] + '. Level mix — Calm ' + r.levelCounts.calm + ', Watch ' + r.levelCounts.watch + ', Warning ' + r.levelCounts.warning + ', Severe ' + r.levelCounts.severe + '.';
      }).join('\n') +
      '\n\nOverall: ' + totalSevereWarning + ' of ' + totalVillages + ' monitored villages are at Warning or Severe.';
  }
  if (q.indexOf('trend') !== -1 || q.indexOf('change') !== -1) {
    return 'Composite risk across your selected scope has been broadly ' + (totalSevereWarning > totalVillages / 2 ? 'elevated over recent weeks, driven mainly by ' + DOMAIN_LABEL[worstRegion.topDomain].toLowerCase() + ' signals in ' + worstRegion.region + '.' : 'stable to moderate, with no region showing a sharp deterioration in the current window.');
  }
  if (q.indexOf('invest') !== -1 || q.indexOf('expand') !== -1 || q.indexOf('safe') !== -1 || q.indexOf('enter') !== -1) {
    if (appetite === 'conservative') {
      return totalSevereWarning > 0
        ? 'Given a conservative risk appetite, ' + worstRegion.region + ' currently shows the highest composite risk (' + worstRegion.avgComposite + '/100) — consider waiting for the next reporting cycle or narrowing to lower-risk townships before committing new exposure there.'
        : 'Current conditions across your selected scope look calm to moderate — a conservative entry looks reasonable, subject to your own diligence.';
    }
    return 'Across your selected scope, ' + (aggregate.regions.length > 1 ? aggregate.regions.map(function (r) { return r.region + ' (' + r.avgComposite + '/100)'; }).join(' and ') : worstRegion.region + ' (' + worstRegion.avgComposite + '/100)') + ' is the current composite risk read. With a ' + appetite + ' appetite, this is within a workable range, but keep an eye on ' + DOMAIN_LABEL[worstRegion.topDomain].toLowerCase() + ' signals in ' + worstRegion.region + '.';
  }
  if (q.indexOf('attention') !== -1 || q.indexOf('township') !== -1 || q.indexOf('where') !== -1) {
    return 'At the township level, aggregate signals point to elevated risk concentrated where ' + DOMAIN_LABEL[worstRegion.topDomain].toLowerCase() + ' is the leading driver, particularly within ' + worstRegion.region + '. Individual village identity is never exposed at this tier — for ground-level verification, coordinate through your own field/operations team.';
  }
  return aggregate.regions.map(function (r) {
    return r.region + ': avg composite ' + r.avgComposite + '/100 across ' + r.villagesMonitored + ' villages, led by ' + DOMAIN_LABEL[r.topDomain].toLowerCase() + ' signals.';
  }).join(' ');
}

const SUGGESTED_QUESTIONS = [
  'Summarize current risk',
  'Which townships need attention?',
  'Generate a one-page report',
  'Is this a good time to expand operations here?',
];

function LevelBar({ counts }) {
  const total = counts.calm + counts.watch + counts.warning + counts.severe || 1;
  const seg = function (n, color, label) {
    return <div className="ap-levelbar-seg" title={label + ': ' + n + ' villages'} style={{ width: (100 * n / total) + '%', background: color, height: 10 }} />;
  };
  return (
    <div style={{ display: 'flex', borderRadius: 'var(--radius-pill)', overflow: 'hidden', width: '100%' }} role="img"
      aria-label={'Calm ' + counts.calm + ', Watch ' + counts.watch + ', Warning ' + counts.warning + ', Severe ' + counts.severe}>
      {seg(counts.calm, 'var(--calm)', 'Calm')}{seg(counts.watch, 'var(--watch)', 'Watch')}{seg(counts.warning, 'var(--warning)', 'Warning')}{seg(counts.severe, 'var(--severe)', 'Severe')}
    </div>
  );
}

function PrivateOrgApp() {
  const store = useAsterStore();
  const [region, setRegion] = React.useState('all');
  const [venture, setVenture] = React.useState('general');
  const [appetite, setAppetite] = React.useState('balanced');
  const [aggregate, setAggregate] = React.useState(function () { return window.AsterStore.computePrivateOrgAggregate({ region: 'all', venture: 'general' }); });
  const [assessing, setAssessing] = React.useState(false);
  const [question, setQuestion] = React.useState('');
  const [chatLog, setChatLog] = React.useState([]);
  const [asking, setAsking] = React.useState(false);
  const [alertForm, setAlertForm] = React.useState(false);
  const [removeAlertId, setRemoveAlertId] = React.useState(null);
  const [toast, setToast, toastNode] = useToast();
  const chatEndRef = React.useRef(null);

  React.useEffect(function () {
    chatEndRef.current && chatEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
  }, [chatLog.length, asking]);

  function runAssessment() {
    setAssessing(true);
    setTimeout(function () {
      setAggregate(window.AsterStore.computePrivateOrgAggregate({ region: region, venture: venture }));
      setAssessing(false);
      setToast('Assessment updated.');
    }, 700);
  }

  function ask(q) {
    if (!q.trim() || asking) return;
    setAsking(true);
    setChatLog(function (log) { return log.concat([{ role: 'user', text: q }]); });
    setQuestion('');
    setTimeout(function () {
      const answer = canned_answer(q, aggregate, appetite);
      setChatLog(function (log) { return log.concat([{ role: 'assistant', text: answer }]); });
      setAsking(false);
    }, 900);
  }

  return (
    <div style={{ maxWidth: 1000, margin: '0 auto', padding: 'var(--space-6) var(--space-5) var(--space-11)' }}>
      <div style={{ marginBottom: 'var(--space-6)' }}>
        <div style={{ font: '600 11px var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>Private Organization / Microfinance</div>
        <h1 style={{ margin: '2px 0 0', font: '700 22px var(--font-display)', color: 'var(--text-strong)' }}>Risk assessment console</h1>
        <div style={{ font: '12px var(--font-text)', color: 'var(--text-subtle)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
          {Ic('lock', { width: 12, height: 12 })} Township/region aggregates only — village-level identity is never shown here.
        </div>
      </div>

      <Card padding="lg" elevation="sm" style={{ marginBottom: 'var(--space-6)' }}>
        <SectionHeading eyebrow="Configurator" title="Risk scenario" />
        <div style={{ display: 'flex', gap: 'var(--space-4)', flexWrap: 'wrap', alignItems: 'flex-end', marginBottom: 'var(--space-4)' }}>
          <div style={{ minWidth: 200 }}>
            <Select label="Region" options={[{ value: 'all', label: 'All focus regions' }, { value: 'Mandalay Region', label: 'Mandalay Region' }, { value: 'Magway Region', label: 'Magway Region' }]} value={region} onChange={function (e) { setRegion(e.target.value); }} />
          </div>
          <div style={{ minWidth: 220 }}>
            <Select label="Venture type" options={VENTURE_OPTIONS} value={venture} onChange={function (e) { setVenture(e.target.value); }} />
          </div>
          <div style={{ minWidth: 180 }}>
            <Select label="Risk appetite" options={APPETITE_OPTIONS} value={appetite} onChange={function (e) { setAppetite(e.target.value); }} />
          </div>
          <Button variant="primary" disabled={assessing} onClick={runAssessment}
            iconLeft={assessing ? null : Ic('play', { width: 14, height: 14 })}>
            {assessing ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><span className="ap-spinner" style={{ borderTopColor: '#fff' }} /> Assessing…</span> : 'Run assessment'}
          </Button>
        </div>
        <div style={{ font: '11px var(--font-mono)', color: 'var(--text-subtle)' }}>Last updated {fmtDateTime(aggregate.generatedAt)}</div>
      </Card>

      <SectionHeading eyebrow="Always-on" title="Dashboard" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12, marginBottom: 'var(--space-7)' }}>
        {assessing && aggregate.regions.map(function (r) {
          return <div key={r.region} className="ap-skeleton" style={{ height: 150 }} />;
        })}
        {!assessing && aggregate.regions.map(function (r) {
          return (
            <Card key={r.region} padding="lg" elevation="sm" className="ap-rise">
              <div style={{ font: '600 14px var(--font-text)', color: 'var(--text-strong)', marginBottom: 8 }}>{r.region}</div>
              <div style={{ display: 'flex', gap: 'var(--space-6)', marginBottom: 10 }}>
                <Stat label="Villages monitored" value={r.villagesMonitored} />
                <Stat label="Avg composite" value={r.avgComposite} unit="/100" tone={r.avgComposite >= 50 ? 'warning' : 'neutral'} />
                <Stat label="Top driver" value={DOMAIN_LABEL[r.topDomain]} />
              </div>
              <LevelBar counts={r.levelCounts} />
              <div style={{ display: 'flex', justifyContent: 'space-between', font: '11px var(--font-mono)', color: 'var(--text-subtle)', marginTop: 6 }}>
                <span>Calm {r.levelCounts.calm}</span><span>Watch {r.levelCounts.watch}</span><span>Warning {r.levelCounts.warning}</span><span>Severe {r.levelCounts.severe}</span>
              </div>
            </Card>
          );
        })}
        {!assessing && aggregate.regions.length === 0 && <EmptyState icon="map" text="No villages in this scope." />}
      </div>

      <Card padding="lg" elevation="sm" style={{ marginBottom: 'var(--space-7)' }}>
        <SectionHeading eyebrow="Ask Aster" title="AI assistant" hint="Answers use only the aggregated scope above — try a suggestion to start." />
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 'var(--space-4)' }}>
          {SUGGESTED_QUESTIONS.map(function (q) {
            return <button key={q} className="ap-chip" onClick={function () { ask(q); }} disabled={asking} style={{ padding: '6px 12px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border-default)', background: 'var(--surface-card)', cursor: 'pointer', font: '12px var(--font-text)', color: 'var(--text-body)', opacity: asking ? 0.6 : 1 }}>{q}</button>;
          })}
        </div>
        <div className="ap-scroll" style={{ maxHeight: 280, overflow: 'auto', marginBottom: 'var(--space-4)' }}>
          {chatLog.length === 0 && !asking && (
            <div style={{ font: '13px var(--font-text)', color: 'var(--text-subtle)', display: 'flex', alignItems: 'center', gap: 8 }}>
              {Ic('sparkles', { width: 14, height: 14 })} Ask a question about the current scenario, or generate a report.
            </div>
          )}
          {chatLog.map(function (m, i) {
            return (
              <div key={i} className="ap-rise" style={{ marginBottom: 10, display: 'flex', gap: 8, justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
                {m.role === 'assistant' && (
                  <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--surface-brand-soft)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 2 }}>
                    {Ic('sparkles', { width: 13, height: 13 })}
                  </span>
                )}
                <div style={{ maxWidth: '78%', whiteSpace: 'pre-wrap', padding: '9px 13px', borderRadius: 'var(--radius-card)', font: '13px/1.55 var(--font-text)', background: m.role === 'user' ? 'var(--surface-brand-soft)' : 'var(--surface-sunken)', color: 'var(--text-body)' }}>{m.text}</div>
              </div>
            );
          })}
          {asking && (
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--surface-brand-soft)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {Ic('sparkles', { width: 13, height: 13 })}
              </span>
              <span style={{ display: 'inline-flex', gap: 4, padding: '10px 13px', borderRadius: 'var(--radius-card)', background: 'var(--surface-sunken)' }}>
                <span className="ap-typing-dot" /><span className="ap-typing-dot" /><span className="ap-typing-dot" />
              </span>
            </div>
          )}
          <div ref={chatEndRef} />
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1 }}>
            <Input placeholder="Ask a question…" value={question} onChange={function (e) { setQuestion(e.target.value); }}
              onKeyDown={function (e) { if (e.key === 'Enter') ask(question); }} />
          </div>
          <Button variant="primary" onClick={function () { ask(question); }} disabled={!question.trim() || asking} iconLeft={Ic('send', { width: 14, height: 14 })}>Ask</Button>
        </div>
      </Card>

      <Card padding="lg" elevation="sm">
        <SectionHeading eyebrow="Proactive" title="Custom alerts"
          hint="Get notified when aggregate conditions cross a threshold you define."
          right={<Button variant="secondary" size="sm" iconLeft={Ic('bell-plus', { width: 14, height: 14 })} onClick={function () { setAlertForm(true); }}>Add alert</Button>} />
        {store.privateAlerts.length === 0 && <EmptyState icon="bell" text="No custom alerts configured yet."
          action={<Button variant="secondary" size="sm" onClick={function () { setAlertForm(true); }}>Create your first alert</Button>} />}
        {store.privateAlerts.map(function (a) {
          return (
            <div key={a.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 0', borderTop: '1px solid var(--border-subtle)', opacity: a.enabled ? 1 : 0.55 }}>
              <div style={{ font: '13px var(--font-text)', color: 'var(--text-body)', display: 'flex', alignItems: 'center', gap: 8 }}>
                {Ic(DOMAIN_ICON[a.domain], { width: 14, height: 14, style: { color: 'var(--text-subtle)', flexShrink: 0 } })}
                <span>Notify if <strong>{DOMAIN_LABEL[a.domain]}</strong> reaches <strong>{LEVEL_LABEL[a.thresholdLevel]}</strong> or above in <strong>{a.minCount}+</strong> villages in <strong>{a.region}</strong></span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                <Switch checked={a.enabled} onChange={function () { window.AsterStore.togglePrivateAlert(a.id); }} label={a.enabled ? 'On' : 'Off'} />
                <IconButton label="Remove alert" variant="ghost" onClick={function () { setRemoveAlertId(a.id); }}>{Ic('trash-2', { width: 15, height: 15 })}</IconButton>
              </div>
            </div>
          );
        })}
      </Card>

      <AlertFormModal open={alertForm} onClose={function () { setAlertForm(false); }}
        onSubmit={function (data) { window.AsterStore.addPrivateAlert(data); setAlertForm(false); setToast('Alert added.'); }} />

      <ConfirmDialog open={!!removeAlertId} onClose={function () { setRemoveAlertId(null); }}
        title="Remove this alert?" tone="danger" confirmLabel="Remove alert"
        body="You'll stop receiving notifications for this threshold. You can recreate it anytime."
        onConfirm={function () { window.AsterStore.removePrivateAlert(removeAlertId); setRemoveAlertId(null); setToast({ message: 'Alert removed.', tone: 'info' }); }} />

      {toastNode}
    </div>
  );
}

function AlertFormModal({ open, onClose, onSubmit }) {
  const [region, setRegion] = React.useState('Mandalay Region');
  const [domain, setDomain] = React.useState('climate');
  const [thresholdLevel, setThresholdLevel] = React.useState('warning');
  const [minCount, setMinCount] = React.useState('2');

  React.useEffect(function () { if (open) { setRegion('Mandalay Region'); setDomain('climate'); setThresholdLevel('warning'); setMinCount('2'); } }, [open]);

  const countNum = Math.max(1, Number(minCount) || 1);

  return (
    <Modal open={open} onClose={onClose} title="Add custom alert" width={460}
      footer={
        <React.Fragment>
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" onClick={function () { onSubmit({ region: region, domain: domain, thresholdLevel: thresholdLevel, minCount: countNum }); }}>Add alert</Button>
        </React.Fragment>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <Select label="Region" options={[{ value: 'Mandalay Region', label: 'Mandalay Region' }, { value: 'Magway Region', label: 'Magway Region' }]} value={region} onChange={function (e) { setRegion(e.target.value); }} />
        <Select label="Domain" options={[{ value: 'climate', label: 'Climate' }, { value: 'economic', label: 'Economic' }, { value: 'conflict', label: 'Conflict' }]} value={domain} onChange={function (e) { setDomain(e.target.value); }} />
        <Select label="Threshold level" options={[{ value: 'watch', label: 'Watch' }, { value: 'warning', label: 'Warning' }, { value: 'severe', label: 'Severe' }]} value={thresholdLevel} onChange={function (e) { setThresholdLevel(e.target.value); }} />
        <Input label="Minimum village count" type="number" min="1" value={minCount} onChange={function (e) { setMinCount(e.target.value); }} />
        <div style={{ padding: '10px 12px', borderRadius: 'var(--radius-card)', background: 'var(--surface-sunken)', font: '13px/1.5 var(--font-text)', color: 'var(--text-body)', display: 'flex', gap: 8 }}>
          {Ic('bell', { width: 14, height: 14, style: { flexShrink: 0, marginTop: 2, color: 'var(--brand)' } })}
          <span>You'll be notified if <strong>{DOMAIN_LABEL[domain]}</strong> reaches <strong>{LEVEL_LABEL[thresholdLevel]}</strong> or above in <strong>{countNum}+</strong> villages in <strong>{region}</strong>.</span>
        </div>
      </div>
    </Modal>
  );
}
