// kova/modules.jsx — module placeholder pages · Wave B
// Each page is a styled "Coming in Wave D-F" state — proves shell wiring works,
// proves navigation works, proves RBAC pattern, while preserving the IA.

const {
  Btn, Card, Chip, PageHead, KPITile, ConfidenceMeter, StatusBadge,
  RunBadge, VerificationStamp, EmptyState, RestrictedState, LoadingBlock,
  ApprovalChain, NotificationRow, Tabs, Icon, Kbd,
} = window.K;


/* ============================================================
   MODULE_META · single source of metadata for placeholders
   ============================================================ */
const MODULE_META = {
  home: {
    title: 'Good morning, Rohan.',
    crumb: ['HOME', 'today'],
    sub: 'Wave D delivers the CEO journey end-to-end. Phase 1 visual proof lives at system.html.',
    eyebrow: 'WAVE D · CEO JOURNEY',
    body: 'HOME is decision-first, not dashboard-first. The page will answer "what needs attention right now" with a primary DecisionCard, three KPI tiles, and a queue of next approvals.',
    kpis: [
      { mod: 'home',  label: 'Approvals',      value: '4',       foot: 'since 9 am',         trend: { dir: 'up', label: '+2' } },
      { mod: 'vault', label: 'Unlock identified', value: '₹14.2 L', foot: '38 SKUs · VAULT' },
      { mod: 'price', label: 'Margin Δ · 7 d', value: '+ 6.4 %', foot: 'verified',           valueColor: 'var(--success)' },
      { mod: 'orbit', label: 'Briefs · 24 h',  value: '7',       foot: 'all verified' },
    ],
  },
  orbit: {
    title: 'Orbit · market intelligence',
    crumb: ['ORBIT'],
    sub: 'Wave E. Brief generation, signals, opportunities — all rendered as Verified Output Cards.',
    eyebrow: 'WAVE E · BUSINESS MODULES',
    body: 'ORBIT will house the daily intelligence brief, signal feed, and the run history for orbit_brief_agent. Every output verified against sources before render.',
    kpis: [
      { mod: 'orbit', label: 'Briefs today',  value: '3', foot: '1 verified, 2 pending' },
      { mod: 'orbit', label: 'Signals open',  value: '7', foot: '2 high confidence' },
      { mod: 'orbit', label: 'Source health', value: '4 / 4', foot: 'all green' },
    ],
  },
  vault: {
    title: 'Vault · deadstock recovery',
    crumb: ['VAULT'],
    sub: 'Wave E. Items queue, action detail, run pages. Approve → CONNECT executes.',
    eyebrow: 'WAVE E · BUSINESS MODULES',
    body: 'VAULT identifies aged inventory and proposes hold · transfer · reprice actions. Each recommendation carries 3+ claims with receipts. Approval triggers the connector pipeline.',
    kpis: [
      { mod: 'vault', label: 'Items aged > 180 d', value: '38',   foot: 'across 4 stores' },
      { mod: 'vault', label: 'Unlock identified',   value: '₹14.2 L', foot: 'this scan' },
      { mod: 'vault', label: 'In flight transfers', value: '2',     foot: 'awaiting logistics' },
    ],
  },
  price: {
    title: 'Price · pricing terminal',
    crumb: ['PRICE'],
    sub: 'Wave E. Rates · quotes · margin · ceiling approvals. Deterministic math, AI explains.',
    eyebrow: 'WAVE E · BUSINESS MODULES',
    body: 'The PRICE engine calculates; the price_explain_agent explains. Every recommended price includes confidence, evidence, risk, and margin implications. CEO ceiling enforced.',
    kpis: [
      { mod: 'price', label: 'Drafts pending', value: '6',  foot: '2 above ceiling' },
      { mod: 'price', label: '24K gold · live', value: '₹78,420 / 10g', foot: 'refreshed 12 min ago' },
      { mod: 'price', label: 'Margin · approved', value: '+ 6.4 %', foot: 'WoW',  valueColor: 'var(--success)' },
    ],
  },
  kraft: {
    title: 'Kraft · design pipeline',
    crumb: ['KRAFT'],
    sub: 'Wave E. Briefs → packets → Rhino handoff → CAD upload → versions.',
    eyebrow: 'WAVE E · BUSINESS MODULES',
    body: 'KRAFT manages the brief-to-launch lineage. Designers work in private workspaces. Submission for approval moves a launch pack through the standard verification chain.',
    kpis: [
      { mod: 'kraft', label: 'Briefs open',  value: '12', foot: '3 ready for CAD' },
      { mod: 'kraft', label: 'CAD in review',value: '5',  foot: '1 awaiting CEO' },
      { mod: 'kraft', label: 'Launch packs', value: '2',  foot: 'this quarter' },
    ],
  },
  approvals: {
    title: 'Approvals · the trust inbox',
    crumb: ['APPROVALS'],
    sub: 'Wave D. The cross-module inbox. Every external write passes here. Approve, reject, escalate.',
    eyebrow: 'WAVE D · TRUST LAYER',
    body: 'APPROVALS aggregates verified Output Cards from ORBIT, VAULT, PRICE, KRAFT. Each carries its evidence, its chain, and its impact. This is the single place a CEO clears their day.',
    kpis: [
      { mod: 'approvals', label: 'Awaiting you',     value: '4',  foot: '2 move money' },
      { mod: 'approvals', label: 'Co-signs needed',  value: '3',  foot: 'cross-team' },
      { mod: 'approvals', label: 'Signed today',     value: '11', foot: '0 rejected', valueColor: 'var(--success)' },
    ],
  },
  monitor: {
    title: 'Monitor · agent telemetry',
    crumb: ['MONITOR'],
    sub: 'Wave F. Power-user surface. Runs · traces · tools · costs · errors · curator queue.',
    eyebrow: 'WAVE F · TRUST & POWER',
    body: 'MONITOR is the only module with Datadog-style density. Every run is a record: prompt snapshot, agent + skill pack version, memory version, tool receipts, verifier checks, output card, outcome.',
    kpis: [
      { mod: 'monitor', label: 'Runs · 24 h',  value: '142', foot: '4 errors · 0 stuck' },
      { mod: 'monitor', label: 'Median run',   value: '8.4 s', foot: 'p95 19 s' },
      { mod: 'monitor', label: 'Cost · 24 h',  value: '$3.18', foot: '0.022 / run' },
    ],
  },
  connect: {
    title: 'Connect · integrations',
    crumb: ['CONNECT'],
    sub: 'Wave F. CSV imports, ERP sources, failure inbox, retry & repair.',
    eyebrow: 'WAVE F · TRUST & POWER',
    body: 'CONNECT is the I/O surface. Connectors are heartbeat-monitored. Failures land in a typed inbox with structured retry paths. No silent sync drift.',
    kpis: [
      { mod: 'connect', label: 'Active sources',   value: '6', foot: 'all green' },
      { mod: 'connect', label: 'Failures (24 h)',  value: '2', foot: 'auto-recovered: 1' },
      { mod: 'connect', label: 'Last sync',        value: '8 min', foot: 'Tally · POS · WMS' },
    ],
  },
  admin: {
    title: 'Admin · governance',
    crumb: ['ADMIN'],
    sub: 'Wave F. SSO, users, roles, audit, features. Admin views are themselves audited.',
    eyebrow: 'WAVE F · TRUST & POWER',
    body: 'ADMIN is the SSO + RBAC surface. Provider configuration (Entra ID, Google Workspace, Google OAuth). Role mappings. Audit trail. Feature flags. Every admin action leaves a receipt.',
    kpis: [
      { mod: 'admin', label: 'Users active', value: '24',  foot: '3 invited · 0 pending' },
      { mod: 'admin', label: 'Roles',        value: '5',   foot: 'mapped to 3 IdP groups' },
      { mod: 'admin', label: 'Audit events', value: '418', foot: 'last 7 d' },
    ],
  },
  wiki: {
    title: 'Wiki · approved knowledge',
    crumb: ['WIKI'],
    sub: 'Wave F. Approved company memory. Pages link to the Runs that produced them.',
    eyebrow: 'WAVE F · TRUST & POWER',
    body: 'WIKI holds approved tenant knowledge, memory facts, and prompt guides. Memory candidates wait here for human approval before promotion. No silent drift, no cross-tenant learning.',
    kpis: [
      { mod: 'wiki', label: 'Pages',              value: '184', foot: '12 awaiting review' },
      { mod: 'wiki', label: 'Memory candidates',  value: '7',   foot: '3 high confidence' },
      { mod: 'wiki', label: 'Last update',        value: '32 min', foot: 'rcp-44ab · merch policy' },
    ],
  },
};


/* ============================================================
   ModulePage — generic placeholder · shared shape
   ============================================================ */
const ModulePage = ({ moduleId, openDrawer, openCmdK, openModal, role = 'ceo', tenantId = 'acme' }) => {
  const meta = MODULE_META[moduleId];
  if (!meta) return null;

  // Pretend HOME has a "next decision" teaser, others get an empty state
  const isHome = moduleId === 'home';
  const isApprovals = moduleId === 'approvals';
  const isMonitor = moduleId === 'monitor';

  return (
    <div className="k-page-enter">
      <PageHead
        crumb={meta.crumb}
        title={meta.title}
        subtitle={meta.sub}
        actions={
          <>
            {isHome      && <Btn size="sm" onClick={openDrawer}>Open evidence</Btn>}
            {isApprovals && <Btn size="sm" onClick={openDrawer}>Open evidence</Btn>}
            {isMonitor   && <Btn size="sm" variant="ghost">Open run · last</Btn>}
            <Btn size="sm" variant="primary" onClick={openCmdK} kbd="⌘K">Jump to…</Btn>
          </>
        }
      />

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${meta.kpis.length}, 1fr)`, gap: 16, marginBottom: 24 }}>
        {meta.kpis.map((k, i) => <KPITile key={i} {...k} />)}
      </div>

      {/* Two-column placeholder content: brief + queue */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 20 }}>
        <Card>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Chip variant="accent" dot>{meta.eyebrow}</Chip>
            <Chip variant="mute">Wave B placeholder</Chip>
          </div>
          <h2 className="t-h2" style={{ marginTop: 0 }}>What this module will do</h2>
          <p className="t-body" style={{ color: 'var(--ink-2)', maxWidth: '64ch', marginTop: 8 }}>
            {meta.body}
          </p>

          {isApprovals && (
            <div style={{ marginTop: 20 }}>
              <div className="t-eyebrow" style={{ marginBottom: 10 }}>Sample approval chain · ready for Wave D</div>
              <ApprovalChain mod="approvals" steps={[
                { who: 'Priya · Merch lead',  meta: 'Drafted recommendation · 9:02', state: 'done' },
                { who: 'Auto · evidence sweep', meta: '3 of 3 claims sourced · 9:04', state: 'done' },
                { who: 'You · CEO',           meta: 'Awaiting sign · ⌘⏎ to approve', state: 'now' },
                { who: 'Logistics · execution', meta: 'Will queue transfer manifest', state: 'pending' },
              ]} />
            </div>
          )}

          {isMonitor && (
            <div style={{ marginTop: 20 }}>
              <div className="t-eyebrow" style={{ marginBottom: 10 }}>Sample recent runs · ready for Wave F</div>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                <thead>
                  <tr style={{ color: 'var(--mute)' }}>
                    <th style={{ textAlign: 'left', padding: '8px 0', borderBottom: '1px solid var(--line)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', fontSize: 10.5 }}>Run</th>
                    <th style={{ textAlign: 'left', padding: '8px 0', borderBottom: '1px solid var(--line)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', fontSize: 10.5 }}>Agent</th>
                    <th style={{ textAlign: 'left', padding: '8px 0', borderBottom: '1px solid var(--line)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', fontSize: 10.5 }}>Status</th>
                    <th style={{ textAlign: 'right', padding: '8px 0', borderBottom: '1px solid var(--line)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', fontSize: 10.5 }}>Duration</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    ['rcp-44c9', 'orbit_brief_agent',   'verified', '6.2 s'],
                    ['rcp-44ca', 'vault_action_agent',  'verified', '12.1 s'],
                    ['rcp-44cb', 'price_explain_agent', 'pending',  '—'],
                    ['rcp-44cc', 'kraft_design_agent',  'failed',   '18.4 s'],
                  ].map(r => (
                    <tr key={r[0]}
                        onClick={() => location.hash = `monitor/${r[0]}`}
                        style={{ borderBottom: '1px solid var(--line-2)', cursor: 'pointer' }}>
                      <td style={{ padding: '10px 0' }}><span className="t-mono" style={{ color: 'var(--accent)' }}>{r[0]}</span></td>
                      <td style={{ padding: '10px 0', color: 'var(--ink-2)' }}><span className="t-mono">{r[1]}</span></td>
                      <td style={{ padding: '10px 0' }}>
                        <StatusBadge kind={r[2]}>{r[2]}</StatusBadge>
                      </td>
                      <td style={{ padding: '10px 0', textAlign: 'right' }} className="t-mono">{r[3]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {!isApprovals && !isMonitor && (
            <div style={{ marginTop: 24 }}>
              <EmptyState
                mark="K"
                title="No content yet · this module ships in a later wave."
                body="The shell, the page-head, the KPI strip, the keyboard map — all working. Module content arrives in Wave D–F."
                cta={<Btn size="sm" onClick={openCmdK} kbd="⌘K">Jump to design library</Btn>}
              />
            </div>
          )}
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Up next · queue · sample</div>
            {[
              { mod: 'orbit',     title: 'Orbit · new daily brief · 3 recommendations', meta: '2 min ago',  read: false },
              { mod: 'approvals', title: 'Vault · awaiting your approval on rcp-44c9', meta: '9 min ago',  read: false },
              { mod: null,        title: 'Connect · Tally sync completed',             meta: '1 h ago',    read: true },
              { mod: null,        title: 'Kraft · CAD-117 ready for review',           meta: 'Yesterday',  read: true },
            ].map((n, i) => (
              <NotificationRow key={i} mod={n.mod} title={n.title} meta={n.meta} read={n.read} />
            ))}
          </Card>

          <Card>
            <div className="t-eyebrow" style={{ marginBottom: 8 }}>Verification · this surface</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                <span style={{ color: 'var(--mute)' }}>RBAC scope</span>
                <span className="t-mono" style={{ color: 'var(--ink)' }}>module.{moduleId}.read</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                <span style={{ color: 'var(--mute)' }}>Tenant</span>
                <span className="t-mono" style={{ color: 'var(--ink)' }}>{tenantId}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                <span style={{ color: 'var(--mute)' }}>Role</span>
                <span className="t-mono" style={{ color: 'var(--ink)' }}>{role}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                <span style={{ color: 'var(--mute)' }}>Source</span>
                <span className="t-mono" style={{ color: 'var(--ink)' }}>architecture v7</span>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

window.ModulePage = ModulePage;
window.MODULE_META = MODULE_META;
