/* global window, React */
// ============================================================
// Agent Policy — how the agent decides, and where TP draws the line.
// Sections (top to bottom):
//   1. Header + KPI strip (4 KPIs)
//   2. Governance score card + autonomy heat map (novel)
//   3. Rules library — filter by family, list of cards w/ autonomy band toggle
//   4. Audit log — compact table of recent agent decisions
// ============================================================

const { useState: usePolState, useMemo: usePolMemo } = React;

const BANDS = [
  { id: 'auto',     label: 'Auto',         short: 'AUTO',  desc: 'Agent acts. No human in loop.' },
  { id: 'notify',   label: 'Notify',       short: 'NOTIFY',  desc: 'Agent acts. Pings TP after.' },
  { id: 'approval', label: 'Approval',     short: 'APPR',  desc: 'Agent stages. TP confirms before action.' },
  { id: 'human',    label: 'Human-only',   short: 'HUMAN', desc: 'TP decides. Agent never acts.' },
];
const BAND_BY_ID = Object.fromEntries(BANDS.map(b => [b.id, b]));

function PolicyKpi({ label, value, sub, kind }) {
  return (
    <div className={`pk ${kind ? `pk--${kind}` : ''}`}>
      <div className="pk__label">{label}</div>
      <div className="pk__value">{value}</div>
      {sub && <div className="pk__sub">{sub}</div>}
    </div>
  );
}

// ---------- Governance score card (novel) ----------
function GovernanceScore({ governance }) {
  const r = 56;            // radius
  const c = 2 * Math.PI * r;
  const pct = governance.score / 100;
  const dash = c * pct;
  const tier = governance.score >= 80 ? 'green' : governance.score >= 60 ? 'amber' : 'red';
  const tierLabel = tier === 'green' ? 'Healthy' : tier === 'amber' ? 'Watch' : 'Risk';
  return (
    <div className="gov-score">
      <div className="gov-score__head">
        <div className="gov-score__eyebrow">GOVERNANCE SCORE</div>
        <div className="gov-score__title">How well does policy balance autonomy &amp; control?</div>
      </div>
      <div className="gov-score__body">
        <div className="gov-score__ring">
          <svg viewBox="0 0 140 140" width="140" height="140">
            <circle cx="70" cy="70" r={r} fill="none" stroke="var(--surface-3)" strokeWidth="9" />
            <circle cx="70" cy="70" r={r} fill="none"
              stroke={tier === 'green' ? 'var(--green)' : tier === 'amber' ? 'var(--amber)' : 'var(--red)'}
              strokeWidth="9"
              strokeDasharray={`${dash} ${c}`}
              strokeLinecap="round"
              transform="rotate(-90 70 70)" />
          </svg>
          <div className="gov-score__num">
            <div className="gov-score__val">{governance.score}</div>
            <div className="gov-score__lbl">{tierLabel}</div>
          </div>
        </div>
        <div className="gov-score__bands">
          {governance.bands.map(b => {
            const tier = b.value >= 80 ? 'green' : b.value >= 60 ? 'amber' : 'red';
            return (
              <div key={b.label} className={`gov-band gov-band--${tier}`}>
                <div className="gov-band__row1">
                  <span className="gov-band__label">{b.label}</span>
                  <span className="gov-band__val">{b.value}</span>
                </div>
                <div className="gov-band__bar"><span style={{ width: `${b.value}%` }} /></div>
                <div className="gov-band__sub">{b.sub}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- Autonomy heat map (novel) ----------
function AutonomyHeatmap({ families, rules, onCellClick, selectedCell }) {
  // grid[family.id][band.id] = { count, savings, triggers }
  const grid = {};
  families.forEach(f => {
    grid[f.id] = {};
    BANDS.forEach(b => { grid[f.id][b.id] = { count: 0, savings: 0, triggers: 0 }; });
  });
  rules.forEach(r => {
    if (!grid[r.family] || !grid[r.family][r.autonomy]) return;
    const cell = grid[r.family][r.autonomy];
    cell.count    += 1;
    cell.savings  += r.dollarsSaved || 0;
    cell.triggers += r.triggers7d   || 0;
  });

  // Find the max cell value for color scaling
  const maxTriggers = Math.max(1, ...families.flatMap(f => BANDS.map(b => grid[f.id][b.id].triggers)));

  return (
    <div className="heatmap">
      <div className="heatmap__head">
        <div>
          <div className="heatmap__eyebrow">AUTONOMY HEATMAP</div>
          <div className="heatmap__title">Where the agent acts · where it asks</div>
        </div>
        <div className="heatmap__sub">
          Cell shows <span className="mono">rules · 7d triggers</span>. Click to filter.
        </div>
      </div>
      <div className="heatmap__grid">
        <div className="heatmap__corner"></div>
        {BANDS.map(b => (
          <div key={b.id} className={`heatmap__col-head heatmap__col-head--${b.id}`}>
            <div className="heatmap__col-label">{b.label}</div>
            <div className="heatmap__col-sub">{b.short}</div>
          </div>
        ))}
        {families.map(f => (
          <React.Fragment key={f.id}>
            <div className="heatmap__row-head">
              <span className="heatmap__row-icon">{f.icon}</span>
              <div>
                <div className="heatmap__row-label">{f.label}</div>
                <div className="heatmap__row-sub">{f.sub}</div>
              </div>
            </div>
            {BANDS.map(b => {
              const cell = grid[f.id][b.id];
              const intensity = cell.triggers / maxTriggers;
              const empty = cell.count === 0;
              const isSelected = selectedCell && selectedCell.family === f.id && selectedCell.band === b.id;
              return (
                <button
                  key={b.id}
                  className={`heatmap__cell heatmap__cell--${b.id} ${empty ? 'heatmap__cell--empty' : ''} ${isSelected ? 'heatmap__cell--selected' : ''}`}
                  style={{
                    '--intensity': empty ? 0 : 0.15 + intensity * 0.85,
                  }}
                  onClick={() => onCellClick && onCellClick(f.id, b.id)}
                >
                  <div className="heatmap__cell-count">{cell.count}</div>
                  {cell.triggers > 0 && (
                    <div className="heatmap__cell-trig">{cell.triggers}× / 7d</div>
                  )}
                  {empty && <div className="heatmap__cell-empty">—</div>}
                </button>
              );
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ---------- Rule card with autonomy band selector ----------
function BandSelector({ value, onChange }) {
  return (
    <div className="band-seg">
      {BANDS.map(b => (
        <button
          key={b.id}
          className={`band-seg__btn band-seg__btn--${b.id} ${value === b.id ? 'on' : ''}`}
          onClick={() => onChange(b.id)}
          title={b.desc}
        >
          {b.short}
        </button>
      ))}
    </div>
  );
}

function RuleCard({ rule, family, onToggle, onAutonomy, onView }) {
  const band = BAND_BY_ID[rule.autonomy];
  return (
    <div className={`rule ${!rule.active ? 'rule--paused' : ''}`}>
      <div className="rule__bar">
        <span className={`rule__band-dot rule__band-dot--${rule.autonomy}`}></span>
      </div>
      <div className="rule__main">
        <div className="rule__head">
          <span className="rule__family">{family.icon} {family.label}</span>
          <span className="rule__sep">·</span>
          <span className="rule__id">{rule.id.toUpperCase()}</span>
          {!rule.active && <span className="pill pill--grey" style={{ marginLeft: 8, fontSize: 9 }}>PAUSED</span>}
          <div className="rule__head-right">
            <BandSelector value={rule.autonomy} onChange={(b) => onAutonomy(rule.id, b)} />
          </div>
        </div>

        <div className="rule__name">{rule.name}</div>

        <div className="rule__logic">
          <div className="rule__logic-row">
            <span className="rule__logic-kw">WHEN</span>
            <span className="rule__logic-text">{rule.when}</span>
          </div>
          <div className="rule__logic-row">
            <span className="rule__logic-kw rule__logic-kw--then">THEN</span>
            <span className="rule__logic-text">{rule.then}</span>
          </div>
        </div>

        <div className="rule__stats">
          <span className="rule__stat">
            <span className="rule__stat-label">Triggered 7d</span>
            <span className="rule__stat-val">{rule.triggers7d}×</span>
          </span>
          <span className="rule__stat">
            <span className="rule__stat-label">$ saved</span>
            <span className="rule__stat-val">${rule.dollarsSaved.toLocaleString()}</span>
          </span>
          <span className="rule__stat">
            <span className="rule__stat-label">Avg latency</span>
            <span className="rule__stat-val">
              {rule.avgLatencyMs === 0 ? '—' :
               rule.avgLatencyMs < 1000 ? `${rule.avgLatencyMs}ms` :
               `${(rule.avgLatencyMs / 1000).toFixed(1)}s`}
            </span>
          </span>
          <span className="rule__stat">
            <span className="rule__stat-label">Override rate</span>
            <span className={`rule__stat-val ${rule.overrideRate > 20 ? 'rule__stat-val--red' : ''}`}>
              {rule.overrideRate}%
            </span>
          </span>
          <span className="rule__stat rule__stat--actions">
            <span className={`rule__toggle ${rule.active ? 'on' : ''}`} onClick={() => onToggle(rule.id)} title={rule.active ? 'Pause rule' : 'Activate rule'}>
              <span className="rule__toggle-knob"></span>
            </span>
            <button className="rule__view" onClick={() => onView(rule.id)}>view triggers →</button>
          </span>
        </div>
      </div>
    </div>
  );
}

// ---------- Audit log table ----------
function AuditLog({ audit, rules, onShowToast }) {
  const ruleById = Object.fromEntries(rules.map(r => [r.id, r]));
  const [filter, setFilter] = usePolState('all');

  const filters = [
    { id: 'all',          label: 'All' },
    { id: 'auto',         label: 'Agent acted' },
    { id: 'tp-decided',   label: 'TP decided' },
    { id: 'tp-override',  label: 'TP overrode' },
    { id: 'waiting',      label: 'Awaiting TP' },
  ];

  const filtered = audit.filter(a => {
    if (filter === 'all') return true;
    if (filter === 'auto')        return /^auto/.test(a.outcome);
    if (filter === 'tp-decided')  return a.outcome === 'TP decided';
    if (filter === 'tp-override') return a.outcome === 'TP overrode' || a.outcome === 'TP approved';
    if (filter === 'waiting')     return /awaiting|notified/.test(a.outcome);
    return true;
  });

  const outcomeKind = (o) => {
    if (o.startsWith('auto'))      return 'green';
    if (o === 'TP overrode')       return 'red';
    if (o === 'TP approved')       return 'blue';
    if (o === 'TP decided')        return 'amber';
    if (o.includes('awaiting'))    return 'amber';
    if (o === 'notified')          return 'blue';
    return 'grey';
  };

  return (
    <div className="audit">
      <div className="audit__head">
        <div>
          <div className="audit__title">Agent decision audit · last {audit.length}</div>
          <div className="audit__sub">Every decision the agent made, with outcome and override.</div>
        </div>
        <div className="audit__filters">
          {filters.map(f => (
            <button key={f.id}
              className={`filter-chip ${filter === f.id ? 'filter-chip--active' : ''}`}
              onClick={() => setFilter(f.id)}>
              {f.label}
            </button>
          ))}
          <button className="btn btn--ghost" style={{ marginLeft: 6 }}
            onClick={() => onShowToast && onShowToast('CSV export queued · check downloads in 30s')}>
            ⤓ CSV
          </button>
        </div>
      </div>

      <div className="audit__table">
        <div className="audit__row audit__row--head">
          <span>Time</span>
          <span>Trip</span>
          <span>Rule</span>
          <span>Outcome</span>
          <span>Action taken</span>
          <span className="num">Latency</span>
          <span>Override by</span>
        </div>
        {filtered.map(a => {
          const rule = ruleById[a.ruleId];
          const kind = outcomeKind(a.outcome);
          return (
            <div key={a.id} className="audit__row">
              <span className="audit__ts">{a.ts}</span>
              <span className="audit__trip">{a.tripId}</span>
              <span className="audit__rule">
                {rule ? rule.name : a.ruleId}
                <span className="audit__rule-id">{a.ruleId.toUpperCase()}</span>
              </span>
              <span><span className={`pill pill--${kind}`}>{a.outcome}</span></span>
              <span className="audit__action">{a.action}</span>
              <span className="num audit__latency">
                {a.latencyMs === 0 ? '—' :
                 a.latencyMs < 1000 ? `${a.latencyMs}ms` :
                 `${(a.latencyMs / 1000).toFixed(1)}s`}
              </span>
              <span className="audit__override">
                {a.overrideBy ? (
                  <>
                    <span className="audit__avatar">{a.overrideBy.split(' ').map(p => p[0]).join('')}</span>
                    {a.overrideBy}
                  </>
                ) : <span style={{ color: 'var(--ink-3)' }}>—</span>}
              </span>
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div className="audit__empty">No entries match this filter.</div>
        )}
      </div>
    </div>
  );
}

// ---------- New Rule modal ----------
function NewRuleModal({ families, onCancel, onCreate }) {
  const [family, setFamily]   = usePolState(families[0].id);
  const [name, setName]       = usePolState('');
  const [whenText, setWhen]   = usePolState('');
  const [thenText, setThen]   = usePolState('');
  const [autonomy, setAuto]   = usePolState('notify');
  const [active, setActive]   = usePolState(true);

  const canCreate = name.trim().length > 2 && whenText.trim().length > 4 && thenText.trim().length > 4;

  return (
    <div className="modal__overlay" onClick={onCancel}>
      <div className="modal modal--narrow" onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__eyebrow">New policy rule</div>
          <div className="modal__title">Add a rule to the library</div>
          <div className="modal__sub">
            Rules are evaluated by the agent on every wave. New rules start in draft until reviewed by Carrier Manager.
          </div>
        </div>
        <div className="modal__body">
          <div className="field">
            <label className="field__label">Family</label>
            <div className="seg seg--block" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
              {families.map(f => (
                <button key={f.id}
                  className={`seg__btn ${family === f.id ? 'on' : ''}`}
                  onClick={() => setFamily(f.id)}>
                  <span style={{ display: 'block', fontWeight: 600 }}>{f.icon} {f.label}</span>
                  <span style={{ display: 'block', fontSize: 9.5, opacity: 0.7, marginTop: 1 }}>{f.sub}</span>
                </button>
              ))}
            </div>
          </div>
          <div className="field">
            <label className="field__label">Rule name</label>
            <input className="input" type="text"
              placeholder="e.g. Confirm at contracted +<10% on Walmart lanes"
              value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div className="field">
            <label className="field__label">WHEN — condition</label>
            <textarea className="textarea" rows="2"
              placeholder="e.g. Customer is Walmart AND spot premium ≤ 10% AND lane has ≥ 1 uncovered load"
              value={whenText} onChange={e => setWhen(e.target.value)} />
          </div>
          <div className="field">
            <label className="field__label">THEN — action</label>
            <textarea className="textarea" rows="2"
              placeholder="e.g. Auto-confirm with recommended carrier · log to audit"
              value={thenText} onChange={e => setThen(e.target.value)} />
          </div>
          <div className="field">
            <label className="field__label">Autonomy band</label>
            <BandSelector value={autonomy} onChange={setAuto} />
            <div className="field__sub">{BAND_BY_ID[autonomy]?.desc}</div>
          </div>
          <label className="check-row__item">
            <input type="checkbox" checked={active} onChange={() => setActive(v => !v)} />
            <span>Activate immediately (otherwise saved as draft)</span>
          </label>
        </div>
        <div className="modal__foot">
          <button className="btn" onClick={onCancel}>Cancel</button>
          <button className="btn btn--primary" disabled={!canCreate}
            onClick={() => onCreate({
              family, name: name.trim(), when: whenText.trim(),
              then: thenText.trim(), autonomy, active,
            })}>
            + Create rule
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- Main view ----------
function AgentPolicy() {
  const P = window.POLICY;
  const [rules, setRules] = usePolState(P.rules);
  const [familyFilter, setFamilyFilter] = usePolState('all');
  const [bandFilter,   setBandFilter]   = usePolState('all');
  const [showPaused,   setShowPaused]   = usePolState(true);
  const [toast, setToast] = usePolState(null);
  const [newRuleOpen, setNewRuleOpen] = usePolState(false);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2800);
  };

  const onToggleRule = (id) => {
    setRules(prev => prev.map(r => r.id === id ? { ...r, active: !r.active } : r));
    const r = rules.find(x => x.id === id);
    if (r) showToast(`Rule "${r.name}" · ${r.active ? 'paused' : 'activated'}`);
  };

  const onChangeAutonomy = (id, band) => {
    setRules(prev => prev.map(r => r.id === id ? { ...r, autonomy: band } : r));
    const r = rules.find(x => x.id === id);
    if (r && r.autonomy !== band) {
      showToast(`Rule "${r.name}" · moved to ${BAND_BY_ID[band].label}`);
    }
  };

  const onHeatmapClick = (family, band) => {
    setFamilyFilter(family);
    setBandFilter(band);
  };

  const filteredRules = usePolMemo(() => {
    return rules.filter(r => {
      if (!showPaused && !r.active) return false;
      if (familyFilter !== 'all' && r.family !== familyFilter) return false;
      if (bandFilter !== 'all' && r.autonomy !== bandFilter) return false;
      return true;
    });
  }, [rules, familyFilter, bandFilter, showPaused]);

  const totals = usePolMemo(() => {
    const active = rules.filter(r => r.active).length;
    const paused = rules.filter(r => !r.active).length;
    const byBand = Object.fromEntries(BANDS.map(b => [b.id, 0]));
    rules.forEach(r => { if (r.active) byBand[r.autonomy]++; });
    const autoPct = Math.round((byBand.auto / active) * 100);
    return { active, paused, byBand, autoPct };
  }, [rules]);

  const onCreateRule = (data) => {
    // generate next id
    const maxN = Math.max(...rules.map(r => parseInt(r.id.replace('r-', ''), 10)).filter(n => !isNaN(n)));
    const id = `r-${String(maxN + 1).padStart(2, '0')}`;
    const newRule = {
      ...data,
      id,
      triggers7d: 0, dollarsSaved: 0, avgLatencyMs: 0, overrideRate: 0,
    };
    setRules(prev => [newRule, ...prev]);
    setNewRuleOpen(false);
    showToast(`✓ Rule "${data.name}" created · ${data.active ? 'active' : 'draft'} · ${BAND_BY_ID[data.autonomy].label}`);
  };

  const hasFilter = familyFilter !== 'all' || bandFilter !== 'all';

  return (
    <div className="policy" data-screen-label="Agent policy">
      {/* Header */}
      <div className="pol-head">
        <div>
          <div className="pol-head__eyebrow">AGENT POLICY · TP</div>
          <div className="pol-head__title">How the agent decides — and where you draw the line.</div>
          <div className="pol-head__sub">
            <span className="v">{totals.active}</span> rules active · <span className="v">{totals.paused}</span> paused ·
            <span className="v"> {totals.byBand.human}</span> always-human ·
            policy version <span className="mono">v3.7</span> · published 2d ago
          </div>
        </div>
        <div className="pol-head__right">
          <button className="btn">⤓ Export policy</button>
          <button className="btn">⏱ Version history</button>
          <button className="btn btn--primary" onClick={() => setNewRuleOpen(true)}>+ New rule</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="pol-kpis">
        <PolicyKpi label="Auto-approved (7d)"  value={`${P.kpis.autoApprovedPct}%`} sub="of all agent decisions" kind="green" />
        <PolicyKpi label="TP hours saved (7d)" value={P.kpis.tpHoursSaved7d.toFixed(1)} sub="estimated · ~4.5min / decision" />
        <PolicyKpi label="$ saved (7d)"        value={`$${P.kpis.dollarsSaved7d.toLocaleString()}`} sub="vs no-agent baseline" />
        <PolicyKpi label="Avg latency"         value={`${P.kpis.avgLatencyMs}ms`} sub="observe → reason → act" />
      </div>

      {/* Governance + Heatmap row */}
      <div className="pol-top-row">
        <GovernanceScore governance={P.governance} />
        <AutonomyHeatmap
          families={P.families}
          rules={rules}
          onCellClick={onHeatmapClick}
          selectedCell={hasFilter ? { family: familyFilter, band: bandFilter } : null}
        />
      </div>

      {/* Rules library */}
      <div className="pol-section">
        <div className="pol-section__head">
          <div>
            <div className="pol-section__title">Policy rules library</div>
            <div className="pol-section__sub">
              {filteredRules.length} of {rules.length} rules ·
              click a rule to expand · drag autonomy band to change who decides
            </div>
          </div>
          <div className="pol-section__filters">
            <label className="show-paused">
              <input type="checkbox" checked={showPaused} onChange={() => setShowPaused(v => !v)} />
              show paused
            </label>
            {hasFilter && (
              <button className="ov-filters__clear" onClick={() => { setFamilyFilter('all'); setBandFilter('all'); }}>
                Clear filters ×
              </button>
            )}
          </div>
        </div>

        {/* Family + Band filter chips */}
        <div className="pol-chips">
          <div className="pol-chips__group">
            <span className="pol-chips__label">FAMILY</span>
            <button className={`filter-chip ${familyFilter === 'all' ? 'filter-chip--active' : ''}`}
              onClick={() => setFamilyFilter('all')}>All <span className="n">{rules.length}</span></button>
            {P.families.map(f => (
              <button key={f.id}
                className={`filter-chip ${familyFilter === f.id ? 'filter-chip--active' : ''}`}
                onClick={() => setFamilyFilter(f.id)}>
                {f.icon} {f.label} <span className="n">{rules.filter(r => r.family === f.id).length}</span>
              </button>
            ))}
          </div>
          <div className="pol-chips__group">
            <span className="pol-chips__label">BAND</span>
            <button className={`filter-chip ${bandFilter === 'all' ? 'filter-chip--active' : ''}`}
              onClick={() => setBandFilter('all')}>All</button>
            {BANDS.map(b => (
              <button key={b.id}
                className={`filter-chip filter-chip--band-${b.id} ${bandFilter === b.id ? 'filter-chip--active' : ''}`}
                onClick={() => setBandFilter(b.id)}>
                {b.label} <span className="n">{rules.filter(r => r.autonomy === b.id).length}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="rules-list">
          {filteredRules.map(rule => {
            const family = P.families.find(f => f.id === rule.family);
            return (
              <RuleCard
                key={rule.id}
                rule={rule}
                family={family}
                onToggle={onToggleRule}
                onAutonomy={onChangeAutonomy}
                onView={(id) => showToast(`Opening trigger list for ${id.toUpperCase()} (last 7d)`)}
              />
            );
          })}
          {filteredRules.length === 0 && (
            <div className="rules-empty">No rules match your filters.</div>
          )}
        </div>
      </div>

      {/* Audit log */}
      <div className="pol-section">
        <AuditLog audit={P.audit} rules={rules} onShowToast={showToast} />
      </div>

      {toast && <div className="pol-toast">{toast}</div>}

      {newRuleOpen && (
        <NewRuleModal
          families={P.families}
          onCancel={() => setNewRuleOpen(false)}
          onCreate={onCreateRule}
        />
      )}
    </div>
  );
}

Object.assign(window, { AgentPolicy });
