"use client";

import { useMemo, useState } from 'react';
import styles from './page.module.css';

const MODES = [
  { id: 'solo', label: 'Solo assistant', claim: 'One operator, one agent loop, direct tool access with approval prompts.', pieces: ['personal session', 'private memory', 'local tools', 'cron jobs'] },
  { id: 'department', label: 'Department team', claim: 'Every department owns a manager agent, specialist agents, tools, memory, queue, budget, and approval policy.', pieces: ['department namespace', 'manager agent', 'specialists', 'shared queue'] },
  { id: 'federated', label: 'Federated organization', claim: 'Departments collaborate through a broker, policy engine, approvals, events, and audit trails — not uncontrolled agent-to-agent calls.', pieces: ['request broker', 'policy engine', 'event bus', 'approval ledger'] },
];

const DEPARTMENTS = [
  { id:'marketing', name:'Marketing', manager:'Growth Manager Agent', agents:['Campaign Strategist','Competitor Scout','Content Calendar','Paid Ads Optimizer'], tools:['web_search','brand_assets','email_send'], memory:'campaigns · audience · channels', queue:14, approval:'Budget + external sends' },
  { id:'finance', name:'Finance', manager:'Finance Controller Agent', agents:['Budget Analyst','Revenue Reporter','Forecast Agent','Approval Controller'], tools:['supabase_read','sheet_export','finance_api'], memory:'budgets · revenue · forecasts', queue:8, approval:'Restricted financial data' },
  { id:'legal', name:'Legal', manager:'Legal Risk Agent', agents:['Contract Reviewer','Compliance Agent','Policy Drafter'], tools:['document_review','redline','email_send'], memory:'contracts · policies · obligations', queue:6, approval:'All legal opinions' },
  { id:'sales', name:'Sales', manager:'Pipeline Manager Agent', agents:['Lead Researcher','CRM Updater','Proposal Agent'], tools:['crm_read','gh_issue_comment','email_send'], memory:'accounts · deals · contacts', queue:19, approval:'Customer-facing writes' },
  { id:'ops', name:'Operations', manager:'Ops Coordinator Agent', agents:['Vendor Agent','Logistics Agent','Process Monitor'], tools:['terminal_run','web_fetch','calendar'], memory:'vendors · SOPs · incidents', queue:11, approval:'Vendor commitments' },
  { id:'engineering', name:'Engineering', manager:'Engineering Lead Agent', agents:['Bug Triage','Claude Code Runner','Codex Reviewer','Release Watcher'], tools:['terminal_run','github','vercel'], memory:'repos · incidents · deploys', queue:22, approval:'Deploys + destructive commands' },
];

const REQUEST_TYPES = [
  { id:'read', label:'Read summary', baseRisk:'low' },
  { id:'confidential', label:'Confidential data', baseRisk:'high' },
  { id:'write', label:'Write/update', baseRisk:'medium' },
  { id:'external', label:'External send', baseRisk:'irreversible_external' },
  { id:'exec', label:'Tool execution', baseRisk:'high' },
];

const ROLES = [
  { id:'employee', label:'Employee' },
  { id:'dept_head', label:'Department head' },
  { id:'ceo', label:'CEO' },
  { id:'contractor', label:'Contractor' },
];

const SENSITIVITY = [
  { id:'public', label:'Public / approved', weight:0 },
  { id:'internal', label:'Internal', weight:1 },
  { id:'confidential', label:'Confidential', weight:2 },
  { id:'restricted', label:'Restricted', weight:3 },
];

const FLOW_STEPS = [
  ['01','Request created','Source agent submits intent, business reason, target department, requested fields, sensitivity, and urgency.'],
  ['02','Broker normalizes','Request Broker attaches tenant_id, department_id, actor_id, task_id, correlation_id, and target queue.'],
  ['03','RBAC + policy','Policy engine checks role, department, data owner, scope, risk tier, rate limits, and active approvals.'],
  ['04','Approval decision','Low-risk can auto-approve by policy; sensitive finance/legal/customer/tool actions pause for manager approval.'],
  ['05','Target agent executes','Target department manager assigns a specialist agent with scoped memory and tool permissions.'],
  ['06','Result returned','Only approved fields or artifact links are returned. Raw restricted data can stay inside the owning department.'],
  ['07','Audit + replay','activity_log, audit_logs, approval_requests, tool_egress, and task events preserve the full chain.'],
];

const ADVANTAGE_ROWS = [
  { k:'Primary shape', hermes:'Personal runtime for one operator/session.', paper:'Company/work control plane and artifacts.', madarx:'Federated AI workforce: employees, departments, agents, approvals, tools, queues, audit.' },
  { k:'Department ownership', hermes:'Not modeled as departments by default.', paper:'Can model org work, but runtime is external.', madarx:'Each department owns agents, memory namespace, tools, queue, policies and approval manager.' },
  { k:'Cross-team work', hermes:'delegate_task spawns subagents, not company-governed departments.', paper:'Tasks/governance exist, but not necessarily local execution.', madarx:'Brokered cross-department requests with RBAC, policy, manager approval and audit lineage.' },
  { k:'Approval strength', hermes:'Strong command approvals for personal execution.', paper:'Governance workflows in control plane.', madarx:'Approval-first at company boundary: cross-department data, tool scopes, external sends, deploys, finance/legal restrictions.' },
  { k:'Execution engines', hermes:'Hermes itself runs tools and providers.', paper:'Adapters phone home; plane can stay separate.', madarx:'Claude Code, Codex, Hermes, Anthropic, Ollama and future MCP tools behind a single governance layer.' },
  { k:'Scalability path', hermes:'Great single-user/gateway scale.', paper:'Org data model scale.', madarx:'Department queues, worker pools, event bus, policy cache, memory scopes, audit partitions, multi-tenant cloud path.' },
  { k:'Business moat', hermes:'Operator productivity.', paper:'Structured autonomous company records.', madarx:'Accountable AI labor market inside the company: everyone gets agents, and agents can collaborate safely.' },
];

const WAR_STEPS = [
  { dept:'Marketing', action:'Campaign Strategist drafts real estate launch brief and asks Finance for available spend.', status:'request.created' },
  { dept:'Broker', action:'Request Broker sees cross-department finance data and sends to Finance queue.', status:'policy.check' },
  { dept:'Finance', action:'Finance Controller allows summarized campaign budget but blocks raw revenue exports.', status:'approval.required' },
  { dept:'Legal', action:'Legal Risk Agent reviews campaign claims before external publication.', status:'parallel.review' },
  { dept:'Sales', action:'Sales Proposal Agent prepares lead segment after Marketing and Finance approval.', status:'queued' },
  { dept:'Ops', action:'Caretaker schedules WhatsApp/email outreach only after final human approval.', status:'ready' },
  { dept:'Executive', action:'CEO Briefing Agent receives audited summary with every handoff and approval linked.', status:'complete' },
];

const ARCH_LAYERS = [
  ['People + departments','employees · department heads · executives · contractors'],
  ['Department tenancy','tenant_id · department_id · workspace_id · memory namespace · budget profile'],
  ['Governance plane','RBAC · policies · approval rules · rate limits · audit rules'],
  ['Coordination plane','request broker · task router · event bus · queues · heartbeat worker'],
  ['Intelligence plane','manager agents · specialist agents · Hermes · Claude Code · Codex · Ollama'],
  ['Data + tools','SQLite/Postgres-ready store · vector memory · files · GitHub · Supabase · email · terminal'],
];

function riskRank(r){ return { low:0, medium:1, high:2, irreversible_external:3 }[r] ?? 0; }
function riskLabel(r){ return r === 'irreversible_external' ? 'irreversible external' : r; }

function decide({ source, target, role, requestType, sensitivity, trustMode }){
  const crossDept = source !== target;
  const req = REQUEST_TYPES.find(x => x.id === requestType);
  const sens = SENSITIVITY.find(x => x.id === sensitivity);
  let risk = req.baseRisk;
  if (sens.weight >= 2 && riskRank(risk) < 2) risk = 'high';
  if (requestType === 'external') risk = 'irreversible_external';
  let decision = 'allow';
  const reasons = [];
  if (crossDept) reasons.push('cross-department boundary');
  if (sens.weight >= 2) reasons.push(`${sens.label.toLowerCase()} sensitivity`);
  if (role === 'contractor') reasons.push('contractor role cannot directly access internal department data');
  if (risk === 'irreversible_external') reasons.push('irreversible external action');
  if (role === 'ceo' && risk !== 'irreversible_external' && sensitivity !== 'restricted') decision = 'auto-approved';
  else if (role === 'contractor' && (crossDept || sens.weight >= 1)) decision = 'denied';
  else if (risk === 'irreversible_external') decision = 'approval-required';
  else if (trustMode === 'manual' && risk !== 'low') decision = 'approval-required';
  else if (trustMode === 'auto' && risk !== 'high') decision = 'auto-approved';
  else if (crossDept || riskRank(risk) >= 2) decision = 'approval-required';
  else decision = 'auto-approved';
  const approver = decision === 'approval-required' ? `${DEPARTMENTS.find(d=>d.id===target)?.name || target} manager` : decision === 'denied' ? 'none' : 'policy engine';
  return { decision, risk, reasons, approver, crossDept };
}

export default function FederatedAIPage(){
  const [mode, setMode] = useState('federated');
  const [dept, setDept] = useState('finance');
  const [view, setView] = useState('employee');
  const [source, setSource] = useState('marketing');
  const [target, setTarget] = useState('finance');
  const [role, setRole] = useState('employee');
  const [requestType, setRequestType] = useState('confidential');
  const [sensitivity, setSensitivity] = useState('confidential');
  const [trustMode, setTrustMode] = useState('approval_required');
  const [warIndex, setWarIndex] = useState(2);
  const [load, setLoad] = useState(1000);
  const [workers, setWorkers] = useState(16);

  const currentDept = DEPARTMENTS.find(d => d.id === dept);
  const currentMode = MODES.find(m => m.id === mode);
  const decision = useMemo(() => decide({ source, target, role, requestType, sensitivity, trustMode }), [source,target,role,requestType,sensitivity,trustMode]);
  const perf = useMemo(() => {
    const capacity = workers * 90;
    const wait = Math.max(1, Math.round((load / capacity) * 12));
    const util = Math.min(99, Math.round((load / capacity) * 100));
    const audit = Math.round(load * 5.4);
    return { capacity, wait, util, audit, queues: Math.ceil(load / Math.max(1,workers*250)) };
  }, [load, workers]);

  return (
    <main className={styles.shell}>
      <div className={styles.topbar}>
        <div className={styles.lead}><em>document · 004 · federation</em><b>madar<i>X</i> OS · company agent network</b></div>
        <div className={styles.links}><a href="/architecture">architecture atlas</a><a href="/">console</a></div>
      </div>

      <header className={styles.hero}>
        <div>
          <p className={styles.eyebrow}>AI generates. Humans approve. Departments collaborate.</p>
          <h1>From one AI assistant to a governed company-wide AI workforce.</h1>
          <p>madarX OS can become the operating layer where every employee and every department has its own team of agents — while cross-department work moves through policies, approvals, queues, memory boundaries, and audit trails.</p>
        </div>
        <aside className={styles.meta}>
          <b>strategic advantage</b>
          <dl>
            <dt>vs Hermes</dt><dd>not only personal execution — institutional coordination</dd>
            <dt>vs Paperclip</dt><dd>not only control-plane records — real governed runtime</dd>
            <dt>core moat</dt><dd>federated agent teams with approval-first collaboration</dd>
            <dt>scale path</dt><dd>local-first → team deployment → enterprise network</dd>
          </dl>
        </aside>
      </header>

      <section className={styles.modeStrip}>
        {MODES.map(m => <button key={m.id} className={mode===m.id?styles.on:''} onClick={()=>setMode(m.id)}><b>{m.label}</b><span>{m.claim}</span></button>)}
      </section>
      <section className={styles.section}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Current operating model</b><small>{currentMode.label}</small></div>
          <p className={styles.bigClaim}>{currentMode.claim}</p>
          <div className={styles.chips}>{currentMode.pieces.map(x => <span key={x}>{x}</span>)}</div>
        </div>
        <div className={`${styles.panel} ${styles.dark}`}>
          <div className={styles.panelTitle}><b>One-line product claim</b><small>positioning</small></div>
          <p>madarX OS turns individual AI agents into an approval-first, audit-friendly operating system for entire companies.</p>
        </div>
      </section>

      <section className={styles.section}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Department agent network</b><small>click a department</small></div>
          <div className={styles.orgGrid}>
            {DEPARTMENTS.map(d => <button key={d.id} className={dept===d.id?styles.on:''} onClick={()=>setDept(d.id)}>
              <b>{d.name}</b><small>{d.manager}</small><em>{d.queue} queued tasks</em>
            </button>)}
          </div>
        </div>
        <div className={`${styles.panel} ${styles.deptCard}`}>
          <div className={styles.panelTitle}><b>{currentDept.name}</b><small>department tenant</small></div>
          <dl className={styles.kv}><dt>manager</dt><dd>{currentDept.manager}</dd><dt>memory</dt><dd>{currentDept.memory}</dd><dt>tools</dt><dd>{currentDept.tools.join(' · ')}</dd><dt>approval</dt><dd>{currentDept.approval}</dd></dl>
          <div className={styles.agentList}>{currentDept.agents.map(a => <span key={a}>{a}</span>)}</div>
        </div>
      </section>

      <section className={`${styles.section} ${styles.single}`}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Cross-department communication simulator</b><small>marketing asks finance, legal asks engineering, support asks ops</small></div>
          <div className={styles.simGrid}>
            <div className={styles.controls}>
              <label>Source department<select value={source} onChange={e=>setSource(e.target.value)}>{DEPARTMENTS.map(d=><option value={d.id} key={d.id}>{d.name}</option>)}</select></label>
              <label>Target department<select value={target} onChange={e=>setTarget(e.target.value)}>{DEPARTMENTS.map(d=><option value={d.id} key={d.id}>{d.name}</option>)}</select></label>
              <label>Actor role<select value={role} onChange={e=>setRole(e.target.value)}>{ROLES.map(r=><option value={r.id} key={r.id}>{r.label}</option>)}</select></label>
              <label>Request type<select value={requestType} onChange={e=>setRequestType(e.target.value)}>{REQUEST_TYPES.map(r=><option value={r.id} key={r.id}>{r.label}</option>)}</select></label>
              <label>Data sensitivity<select value={sensitivity} onChange={e=>setSensitivity(e.target.value)}>{SENSITIVITY.map(s=><option value={s.id} key={s.id}>{s.label}</option>)}</select></label>
              <label>Trust mode<select value={trustMode} onChange={e=>setTrustMode(e.target.value)}><option value="approval_required">approval_required</option><option value="auto">auto-trust for safe scopes</option><option value="manual">manual every risky action</option></select></label>
            </div>
            <div className={styles.decisionPanel}>
              <span className={`${styles.badge} ${styles[decision.decision.replace('-', '')]}`}>{decision.decision}</span>
              <h3>{DEPARTMENTS.find(d=>d.id===source).name} → {DEPARTMENTS.find(d=>d.id===target).name}</h3>
              <p>Risk tier: <b>{riskLabel(decision.risk)}</b>. Approver: <b>{decision.approver}</b>.</p>
              <ul>{(decision.reasons.length?decision.reasons:['same-department low-friction request']).map(r => <li key={r}>{r}</li>)}</ul>
              <div className={styles.records}><b>Records created</b><span>cross_department_requests</span><span>activity_log</span>{decision.decision==='approval-required' && <span>approval_requests</span>}<span>audit_logs</span><span>department_queue_jobs</span></div>
            </div>
          </div>
        </div>
      </section>

      <section className={styles.section}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Request flow</b><small>brokered, not free-for-all</small></div>
          <div className={styles.flow}>{FLOW_STEPS.map(s => <div key={s[0]}><b>{s[0]}</b><span>{s[1]}</span><p>{s[2]}</p></div>)}</div>
        </div>
        <div className={`${styles.panel} ${styles.dark}`}>
          <div className={styles.panelTitle}><b>Why this is safer</b><small>boundary design</small></div>
          <p>Agents do not directly scrape another department’s memory or tools. They request work through a broker. The owning department decides what can be returned.</p>
          <ul className={styles.flat}><li>Raw finance data can remain inside Finance.</li><li>Marketing receives approved summaries, not unrestricted tables.</li><li>Legal opinions require Legal manager approval.</li><li>External sends and destructive tool calls remain irreversible_external.</li></ul>
        </div>
      </section>

      <section className={`${styles.section} ${styles.single}`}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Federation architecture</b><small>six-layer model</small></div>
          <div className={styles.layers}>{ARCH_LAYERS.map((l,i)=><div key={l[0]}><em>{String(i+1).padStart(2,'0')}</em><b>{l[0]}</b><span>{l[1]}</span></div>)}</div>
        </div>
      </section>

      <section className={styles.section}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Performance simulator</b><small>queues · workers · audit volume</small></div>
          <div className={styles.sliderRow}><label>Task load: {load.toLocaleString()} / hour<input type="range" min="10" max="10000" step="10" value={load} onChange={e=>setLoad(Number(e.target.value))}/></label><label>Workers: {workers}<input type="range" min="1" max="80" value={workers} onChange={e=>setWorkers(Number(e.target.value))}/></label></div>
          <div className={styles.metricGrid}><div><b>{perf.capacity.toLocaleString()}</b><span>task/hour capacity</span></div><div><b>{perf.util}%</b><span>worker utilization</span></div><div><b>{perf.wait}m</b><span>est. queue wait</span></div><div><b>{perf.audit.toLocaleString()}</b><span>audit events/hour</span></div></div>
        </div>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Scalability rules</b><small>keep it fast and inspectable</small></div>
          <ul className={styles.flat}><li>Every request carries tenant_id, department_id, actor_id, task_id, correlation_id.</li><li>Hot permissions, tool manifests and rate counters can be cached.</li><li>Long work moves to department queues with leases, retries and dead-letter handling.</li><li>Vector memory retrieval is scoped by tenant, department, role, task and policy.</li><li>Audit logs are append-only and can be partitioned by company/department/time.</li></ul>
        </div>
      </section>

      <section className={`${styles.section} ${styles.single}`}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Advantage matrix</b><small>Hermes · Paperclip · madarX OS</small></div>
          <div className={styles.tableWrap}><table className={styles.matrix}><thead><tr><th>Dimension</th><th>Hermes Agent</th><th>Paperclip</th><th>madarX OS advantage</th></tr></thead><tbody>{ADVANTAGE_ROWS.map(r=><tr key={r.k}><th>{r.k}</th><td>{r.hermes}</td><td>{r.paper}</td><td>{r.madarx}</td></tr>)}</tbody></table></div>
        </div>
      </section>

      <section className={`${styles.section} ${styles.single}`}>
        <div className={styles.panel}>
          <div className={styles.panelTitle}><b>Department war-room demo</b><small>launch a campaign across six departments</small></div>
          <div className={styles.warGrid}>{WAR_STEPS.map((s,i)=><button key={s.status} className={warIndex===i?styles.on:''} onClick={()=>setWarIndex(i)}><b>{s.dept}</b><span>{s.status}</span></button>)}</div>
          <div className={styles.warDetail}><b>{WAR_STEPS[warIndex].dept} · {WAR_STEPS[warIndex].status}</b><p>{WAR_STEPS[warIndex].action}</p><small>Every handoff creates durable task, activity, approval, and audit context. This is the difference between “agents chatting” and an accountable AI organization.</small></div>
        </div>
      </section>

      <footer className={styles.footer}><span>madarX OS · federated AI teams · document 004</span><span>company-wide agents · governed collaboration · audit-first</span></footer>
    </main>
  );
}
