/* global React */
const { Icon, Badge, Card, Button, MarginNote } = window;

// =====================================================================
// SPRINGBOARD — Dallas County APIO program home
//
// The wireframe spec from leadership ("APIO Core + sister apps") is
// preserved as the right-rail "Apps" stack. The primary content area
// reflects the customer's actual mental model from the discovery work:
// six deployment groups tracking against the SOW M3/M4/M5 milestones
// and the Aug-31-2026 Group 1 go-live (per APIO_Deployment_Groups.md
// and Deborah Wann's "deploy as we go" framing of Apr 22, 2026).
//
// CITATIONS — see TRACEABILITY.md for the full mapping.
//   SOW_Execution_Plan.md  → 6-group structure + budget + M3/M4/M5
//   APIO_Deployment_Groups.md (Apr 24 2026) → group composition
//   meeting 2026-05-26 AM   → "we deploy as we go"
// =====================================================================

const ROLLOUT_GROUPS = [
  { id: 'g1', name: 'Group 1', period: 'Aug 2026', sowMilestone: 'M3 Phase 1 · High Volume',
    status: 'in-build', statusLabel: 'In build · go-live Aug 31',
    sources: 6, departments: ['Sheriff (505B)', 'County Clerk (Special Funds)', 'Jury Services', 'County Auditor (PPM/Misc)'],
    note: 'Demoable. Sheriff intake live as wireframe.',
    sowQuote: '"Sheriff, Courts, Clerk Integrations Live" — $211,250 (25% of APIO budget)' },
  { id: 'g2', name: 'Group 2', period: 'Sep 2026', sowMilestone: 'M3 continuation',
    status: 'discovery', statusLabel: 'Discovery complete · spec drafting',
    sources: 11, departments: ['DA', 'Constables 1–3', '8 Justices of the Peace', 'HHS 1 & 3'],
    note: 'Largest wave; largest training footprint.',
    sowQuote: null },
  { id: 'g3', name: 'Group 3', period: 'Oct 2026', sowMilestone: 'M3 / M4 transition',
    status: 'design', statusLabel: 'Awaiting substitution-rules sign-off',
    sources: 6, departments: ['Auto-approved (501/502)', 'Department-approved (504B/503CF/503J/503T)'],
    note: 'Multi-leg disbursement model per US-009.',
    sowQuote: null },
  { id: 'g4', name: 'Group 4', period: 'Nov 2026', sowMilestone: 'M3 / M4 transition',
    status: 'design', statusLabel: 'OTP-heavy · jury exception flows',
    sources: 4, departments: ['DA (Jury Pay—Grand)', 'Treasurer (OTP Misc, 1099 impl.)'],
    note: '4 jury exception types; new-funding generates 2 Fusion invoices.',
    sowQuote: null },
  { id: 'g5', name: 'Group 5', period: 'Dec 2026', sowMilestone: 'M4 Phase 2 · Low Volume',
    status: 'backlog', statusLabel: 'Heavy training; staggered',
    sources: 6, departments: ['HHS (HOWPA/STRMU/CEAP/IMPORT)', 'CSCD', 'Constable 4'],
    note: null,
    sowQuote: null },
  { id: 'g6', name: 'Group 6', period: 'Jan 2027', sowMilestone: 'M5 Go-Live Finalization',
    status: 'backlog', statusLabel: 'Tail / minimal training',
    sources: 2, departments: ['Fiscal Services (Payroll Pre-Funding)', 'County Auditor (Special Pay)'],
    note: null,
    sowQuote: null },
];

const APIO_APPS = [
  { id: 'core',  name: 'APIO Core',       desc: '12 components — payment requests, batches, files, financials', glyph: '⌂', target: 'flow',  state: 'building' },
  { id: 'dash',  name: 'Operations Dashboard', desc: 'Status tiles + activity feed (US-050)',                    glyph: '◫', target: 'dashboard', state: 'building' },
  { id: 'kiosk', name: 'Email Ack Flow',  desc: 'email → SSO → acknowledge',                                       glyph: '✉', target: 'kiosk', state: 'live'  },
  { id: 'admin', name: 'Administrator',   desc: 'sources, rules, roles, retention',                                glyph: '⚙', state: 'hold', reason: 'waiting on roles model from IAM' },
];

function Springboard({ go }) {
  const navigate = go || ((id) => { if (window.goTo) window.goTo(id); });

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)', padding: '36px 56px 60px' }}>
      {/* HEADER */}
      <div style={{
        display: 'flex', alignItems: 'flex-end', gap: 18,
        paddingBottom: 16, borderBottom: '1px solid var(--border)',
        flexWrap: 'wrap',
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', letterSpacing: 1.2 }}>
            DALLAS COUNTY · FINANCE · APIO MODERNIZATION
          </div>
          <h1 style={{ margin: '4px 0 0', fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 600, letterSpacing: -0.01 }}>
            APIO Program Home
          </h1>
          <div style={{ marginTop: 6, fontFamily: 'var(--font-sketch)', fontSize: 13, color: 'var(--ink-3)' }}>
            DIR-CPO-5892 · $1.74M engagement · 6 rollout groups · Group 1 go-live <b style={{ color: 'var(--ink)' }}>Aug 31, 2026</b>
          </div>
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)' }}>
          signed in · k.lee · HHS preparer
        </div>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr) 320px',
        gap: 36,
        marginTop: 28,
      }}>
        {/* LEFT — Rollout groups */}
        <div>
          <div style={{
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
            marginBottom: 14, gap: 14,
          }}>
            <div>
              <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>Rollout groups</h2>
              <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>
                Phased deployment per Deborah Wann (2026-04-22): <i>"it is just too much for us to handle big bang."</i>
              </div>
            </div>
            <a href="#" onClick={(e) => e.preventDefault()} style={{
              fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--accent)',
            }}>See full schedule →</a>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ROLLOUT_GROUPS.map((g) => <RolloutGroupRow key={g.id} group={g} navigate={navigate}/>)}
          </div>

          {/* Evidence footer */}
          <div style={{
            marginTop: 20, padding: '12px 14px',
            border: '1px solid var(--line)', borderRadius: 6, background: 'var(--paper-dim)',
            fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)',
            display: 'flex', gap: 14, alignItems: 'flex-start',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: 1.2, color: 'var(--ink-4)', flexShrink: 0, marginTop: 2 }}>SOURCE</span>
            <div style={{ flex: 1, lineHeight: 1.5 }}>
              Group composition + go-live cadence per <b>APIO_Deployment_Groups.md</b> (2026-04-24) and the DBITS DIR-CPO-5892 SOW.
              Group 1 milestone <b>M3 Phase 1 · $211,250</b> mandates "Sheriff, Courts, Clerk Integrations Live."
              Status states (in build / discovery / design / backlog) reflect each group's actual position in
              the discovery → wireframe → spec → build pipeline as of {new Date().toISOString().slice(0,10)}.
            </div>
          </div>
        </div>

        {/* RIGHT — APIO Apps (boss's springboard direction kept intact) */}
        <div>
          <h2 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>APIO apps</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {APIO_APPS.map((a) => <AppTile key={a.id} app={a} navigate={navigate}/>)}
          </div>
        </div>
      </div>

      {/* FOOTER */}
      <div style={{
        marginTop: 40, paddingTop: 12, borderTop: '1px solid var(--line)',
        display: 'flex', gap: 14, flexWrap: 'wrap',
        fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)', letterSpacing: 1.1,
      }}>
        <span>DALLAS COUNTY · OFFICE OF BUDGET & EVALUATION</span>
        <span>·</span>
        <span>APIO v0.9 · {new Date().toISOString().slice(0,7)}</span>
        <span>·</span>
        <span>SUPPORT: ext-4400</span>
        <span style={{ marginLeft: 'auto' }}>Design ref: leadership wireframe set · Customer ref: PMO discovery 2026-04 → 2026-05</span>
      </div>
    </div>
  );
}

// =====================================================================
// ROLLOUT GROUP ROW
// =====================================================================
function RolloutGroupRow({ group, navigate }) {
  const statusTone = {
    'in-build':   { fg: 'var(--success)', bg: '#eaf5ec', border: '#c1dcc7' },
    'discovery':  { fg: 'var(--accent-2)', bg: 'var(--highlight)', border: '#c2d8ec' },
    'design':     { fg: '#7a4e00', bg: '#fcefd6', border: '#e8d4a3' },
    'backlog':    { fg: 'var(--ink-3)', bg: 'var(--paper-dim)', border: 'var(--border)' },
  }[group.status] || { fg: 'var(--ink-3)', bg: 'var(--paper-dim)', border: 'var(--border)' };

  const isG1 = group.id === 'g1';
  const clickable = isG1; // only G1 has working wireframe routes today

  return (
    <div
      onClick={clickable ? () => navigate('dashboard') : undefined}
      style={{
        display: 'grid',
        gridTemplateColumns: '110px 120px 1fr 130px',
        gap: 14, alignItems: 'center',
        padding: '12px 16px',
        background: 'var(--surface)',
        border: `1px solid ${isG1 ? 'var(--accent)' : 'var(--border)'}`,
        borderRadius: 8,
        cursor: clickable ? 'pointer' : 'default',
        transition: 'box-shadow 120ms ease, transform 120ms ease',
        boxShadow: isG1 ? 'var(--shadow-1)' : 'none',
        position: 'relative',
      }}
      onMouseEnter={(e) => { if (clickable) e.currentTarget.style.boxShadow = 'var(--shadow-2)'; }}
      onMouseLeave={(e) => { if (clickable) e.currentTarget.style.boxShadow = 'var(--shadow-1)'; }}
    >
      {/* col 1 — group + period */}
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, letterSpacing: -0.01 }}>
          {group.name}
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', letterSpacing: 0.6 }}>
          {group.period}
        </div>
      </div>

      {/* col 2 — status pill */}
      <div>
        <span style={{
          display: 'inline-block', padding: '3px 10px',
          background: statusTone.bg, color: statusTone.fg,
          border: `1px solid ${statusTone.border}`,
          borderRadius: 999,
          fontFamily: 'var(--font-sketch)', fontSize: 11, fontWeight: 500,
          whiteSpace: 'nowrap',
        }}>{group.statusLabel}</span>
      </div>

      {/* col 3 — departments + SOW milestone */}
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 13, color: 'var(--ink)', lineHeight: 1.45 }}>
          {group.departments.join(' · ')}
        </div>
        <div style={{ marginTop: 4, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: 0.6 }}>
          {group.sources} sources · {group.sowMilestone}
        </div>
        {group.note && (
          <div style={{ marginTop: 4, fontFamily: 'var(--font-sketch)', fontSize: 12, color: isG1 ? 'var(--accent-2)' : 'var(--ink-3)', fontStyle: isG1 ? 'normal' : 'italic' }}>
            {group.note}
          </div>
        )}
      </div>

      {/* col 4 — go */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6 }}>
        {clickable ? (
          <>
            <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--accent)', fontWeight: 500 }}>Open</span>
            <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 16, color: 'var(--accent)' }}>→</span>
          </>
        ) : (
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)', letterSpacing: 1 }}>
            NOT YET INTERACTIVE
          </span>
        )}
      </div>
    </div>
  );
}

// =====================================================================
// APP TILE — right-rail apps (preserves the boss-direction "springboard")
// =====================================================================
function AppTile({ app, navigate }) {
  const isHold  = app.state === 'hold';
  const isLive  = app.state === 'live';
  const clickable = !isHold && app.target;

  return (
    <div
      onClick={clickable ? () => navigate(app.target) : undefined}
      style={{
        display: 'flex', alignItems: 'flex-start', gap: 12,
        padding: '12px 14px',
        background: 'var(--surface)',
        border: '1px solid ' + (isHold ? 'var(--line)' : 'var(--border)'),
        borderRadius: 8,
        cursor: clickable ? 'pointer' : 'not-allowed',
        opacity: isHold ? 0.65 : 1,
        transition: 'border-color 120ms ease, box-shadow 120ms ease',
      }}
      onMouseEnter={(e) => { if (clickable) { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.boxShadow = 'var(--shadow-1)'; } }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = isHold ? 'var(--line)' : 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}
    >
      <div style={{
        width: 36, height: 36, borderRadius: 6,
        background: isHold ? 'var(--paper-dim)' : 'var(--marker)',
        color: isHold ? 'var(--ink-3)' : '#ffffff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600,
        flexShrink: 0,
      }}>{app.glyph}</div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
            {app.name}
          </div>
          {isLive && <Badge tone="hl">live</Badge>}
          {isHold && <Badge tone="ink">paused</Badge>}
        </div>
        <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.4 }}>
          {app.desc}
        </div>
        {isHold && app.reason && (
          <div style={{ marginTop: 4, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)', letterSpacing: 0.4 }}>
            ↳ {app.reason}
          </div>
        )}
      </div>
    </div>
  );
}

// =====================================================================
// END-TO-END FLOW — unchanged content, kept for the existing nav link.
// =====================================================================
function FlowDiagram({ go }) {
  const dept = [
    { n: 1, label: 'Prepare',     go: 'payment360' },
    { n: 2, label: 'Batch',       go: 'batch360' },
    { n: 3, label: 'Acknowledge', ack: true, go: 'ack' },
    { n: 4, label: 'Submit',      go: 'batch360' },
  ];
  const fin = [
    { n: 5, label: 'Accept',   ack: true, optional: true },
    { n: 6, label: 'Audit',    ack: true, optional: true },
    { n: 7, label: 'Post',     ack: true, go: 'ap360' },
    { n: 8, label: 'Disburse', go: 'status' },
  ];

  return (
    <div style={{ padding: '40px 28px 60px', maxWidth: 920 }}>
      <h2 style={{ margin: '0 0 24px', fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600 }}>End-to-end flow</h2>
      <FlowRow label="DEPT" steps={dept} go={go}/>
      <div style={{ height: 16 }}/>
      <FlowRow label="FINANCIALS" steps={fin} go={go}/>
      <div style={{
        marginTop: 28,
        fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)',
      }}>
        <b style={{ color: 'var(--ink-2)' }}>highlighted</b> = approval · <b style={{ color: 'var(--ink-2)' }}>dashed</b> = optional · click any step
      </div>
    </div>
  );
}

function FlowRow({ label, steps, go }) {
  return (
    <div style={{ display: 'flex', alignItems: 'stretch', gap: 0 }}>
      <div style={{
        width: 90, flexShrink: 0,
        display: 'flex', alignItems: 'center',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: 1.2, color: 'var(--ink-3)',
      }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1, flexWrap: 'wrap' }}>
        {steps.map((s, i) => (
          <React.Fragment key={s.n}>
            <FlowChip step={s} onClick={s.go && go ? () => go(s.go) : undefined}/>
            {i < steps.length - 1 && (
              <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 14, color: 'var(--ink-4)' }}>→</span>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function FlowChip({ step: s, onClick }) {
  const ack = !!s.ack;
  const optional = !!s.optional;
  return (
    <span
      onClick={onClick}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 7,
        padding: '6px 12px',
        border: '1px ' + (optional ? 'dashed' : 'solid') + ' ' + (optional ? 'var(--border-strong)' : 'var(--border)'),
        borderRadius: 6,
        background: ack && !optional ? 'var(--highlight)' : 'var(--surface)',
        cursor: onClick ? 'pointer' : 'default',
        fontFamily: 'var(--font-sketch)', fontSize: 13, fontWeight: 500,
        opacity: optional ? 0.8 : 1,
      }}
    >
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)' }}>{s.n}</span>
      {s.label}
    </span>
  );
}

Object.assign(window, { Springboard, FlowDiagram });
