/* global React */
const { Icon, Badge } = window;
const { useState: useStateShell } = React;

// =====================================================================
// SIDEBAR — APIO Core nav. All 12 components in functional order.
// =====================================================================

const NAV = [
  { group: 'group 1 · live wireframes',  items: [
    { id: 'dashboard',     glyph: '◫', label: 'Dashboard',           note: 'US-050' },
    { id: 'sheriffIntake', glyph: '↑', label: 'Sheriff intake',      note: '505B · M3', badge: 'NEW' },
  ]},
  { group: 'overview',  items: [
    { id: 'flow',        glyph: '→', label: 'End-to-end flow',     note: '§1.9' },
    { id: 'uml',         glyph: '◇', label: 'System sketch',       note: 'UML-ish' },
    { id: 'personas',    glyph: '☻', label: 'Personas',            note: '8 roles' },
  ]},
  { group: '360 views', items: [
    { id: 'payee360',   glyph: '☰', label: 'Payee',          note: '3.1' },
    { id: 'payment360', glyph: '☰', label: 'Request',        note: '3.2', badge: '4' },
    { id: 'batch360',   glyph: '☰', label: 'Batch',          note: '3.5', badge: '1' },
    { id: 'file360',    glyph: '↓', label: 'File',           note: '3.5a', badge: '1' },
    { id: 'ap360',      glyph: '☰', label: 'Financials',     note: '3.5b · adjustments', badge: '7' },
  ]},
  { group: 'find', items: [
    { id: 'search',      glyph: '⌕', label: 'Search',         note: 'across all 360s' },
  ]},
  { group: 'pipelines', items: [
    { id: 'ingest',     glyph: '↓', label: 'Inbound interface',  note: '3.0' },
    { id: 'post',       glyph: '↑', label: 'AP interface',      note: '3.10' },
    { id: 'status',     glyph: '⌕', label: 'Status tracker',    note: '3.7' },
  ]},
  { group: 'configuration', items: [
    { id: 'batchTemplates',glyph: '☰', label: 'Batch templates',   note: '3.3b' },
    { id: 'ack',        glyph: '✓', label: 'Acknowledgements',  note: '3.4' },
    { id: 'validation', glyph: '!', label: 'Validation engine', note: '3.8' },
    { id: 'vault',      glyph: '☰', label: 'Document vault',    note: '3.6' },
    { id: 'sourceCfg',  glyph: '⚙', label: 'Source config',     note: '3.9' },
    { id: 'reporting',  glyph: '☰', label: 'Reporting',         note: '3.11' },
  ]},
  { group: 'sister apps', items: [
    { id: 'kiosk',      glyph: '✉', label: 'Email ack flow',     note: 'SPA' },
  ]},
];

const DEPARTMENTS = [
  { id: 'sheriff',    label: "Sheriff's Office",       sub: 'bonds · seizures · evidence' },
  { id: 'hhs',        label: 'Health & Human Svcs',    sub: 'rent · utility assistance' },
  { id: 'jury',       label: 'Jury Services',          sub: 'juror duty payments' },
  { id: 'constables', label: 'Constables',             sub: 'pcts 1–5 · service fees' },
  { id: 'jp',           label: 'Justices of the Peace',  sub: 'jp 1-1 thru 5-2' },
  { id: 'treasurer',    label: "Treasurer's Office",     sub: 'misc disbursements' },
  { id: 'specialFunds', label: 'Special Funds',          sub: 'restitution · court business · legacy macros' },
  { id: 'all',          label: 'All departments',        sub: 'admin · cross-dept view' },
];

function DepartmentSwitcher({ value, onChange }) {
  const [open, setOpen] = useStateShell(false);
  const cur = DEPARTMENTS.find(d => d.id === value) || DEPARTMENTS[0];
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', textAlign: 'left',
        fontFamily: 'var(--font-sketch)', fontSize: 13,
        background: 'var(--surface)', color: 'var(--ink)',
        border: '1px solid var(--border)', borderRadius: 6,
        padding: '8px 10px', cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 8,
        transition: 'border-color 120ms ease, box-shadow 120ms ease',
      }}>
        <span style={{
          width: 24, height: 24, borderRadius: 4, flexShrink: 0,
          border: '1px solid var(--border)', background: 'var(--paper-dim)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600, color: 'var(--ink-2)',
        }}>{cur.label[0]}</span>
        <span style={{ flex: 1, lineHeight: 1.15, minWidth: 0 }}>
          <div style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cur.label}</div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cur.sub}</div>
        </span>
        <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)' }}>{open ? '▴' : '▾'}</span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, zIndex: 50,
          background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 6,
          boxShadow: 'var(--shadow-2)', maxHeight: 320, overflowY: 'auto',
        }}>
          {DEPARTMENTS.map((d) => (
            <button key={d.id} onClick={() => { onChange(d.id); setOpen(false); }} style={{
              display: 'block', width: '100%', textAlign: 'left',
              padding: '8px 10px', cursor: 'pointer',
              background: d.id === value ? 'var(--paper-dim)' : 'transparent',
              border: 'none', borderBottom: '1px solid var(--line)',
              fontFamily: 'var(--font-sketch)', fontSize: 13,
            }}
            onMouseEnter={(e) => { if (d.id !== value) e.currentTarget.style.background = 'var(--paper-dim)'; }}
            onMouseLeave={(e) => { if (d.id !== value) e.currentTarget.style.background = 'transparent'; }}>
              <div style={{ fontWeight: 500 }}>{d.label}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--ink-3)' }}>{d.sub}</div>
            </button>
          ))}
          <div style={{ padding: '8px 10px', fontFamily: 'var(--font-sketch)', fontSize: 11, color: 'var(--redline)', borderTop: '1px solid var(--line)' }} data-redline>
            ?? scope by user role · § 7 still open
          </div>
        </div>
      )}
    </div>
  );
}

function Sidebar({ active, onNavigate, dept, onDept }) {
  const hrefFor = (id) => (window.pagePath ? window.pagePath(id) : '#');
  const handleClick = (id) => (e) => {
    if (onNavigate) { e.preventDefault(); onNavigate(id); }
  };
  return (
    <aside style={{
      width: 248, flexShrink: 0,
      background: 'var(--surface)',
      borderRight: '1px solid var(--border)',
      padding: '18px 14px',
      display: 'flex', flexDirection: 'column', gap: 14,
      overflowY: 'auto',
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, position: 'relative', paddingTop: 4 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: 1.2, padding: '0 6px 2px' }}>
          DEPARTMENT
        </div>
        <DepartmentSwitcher value={dept} onChange={onDept}/>
      </div>

      {NAV.map((grp) => (
        <div key={grp.group} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: 1.2, padding: '0 6px 4px' }}>
            {grp.group.toUpperCase()}
          </div>
          {grp.items.map((it) => {
            const isActive = active === it.id;
            return (
              <a key={it.id} href={hrefFor(it.id)} onClick={handleClick(it.id)}
                style={{
                  textDecoration: 'none',
                  fontFamily: 'var(--font-sketch)', fontSize: 13, textAlign: 'left',
                  background: isActive ? 'var(--highlight)' : 'transparent',
                  color: isActive ? 'var(--accent-2)' : 'var(--ink-2)',
                  borderLeft: '3px solid ' + (isActive ? 'var(--accent)' : 'transparent'),
                  borderRadius: '0 6px 6px 0',
                  padding: '7px 9px',
                  cursor: 'pointer',
                  display: 'flex', alignItems: 'center', gap: 9,
                  fontWeight: isActive ? 500 : 400,
                  transition: 'background 120ms ease',
                }}
                onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = 'var(--paper-dim)'; }}
                onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
                <Icon glyph={it.glyph} size={14} style={{ color: isActive ? 'var(--accent)' : 'var(--ink-3)' }}/>
                <span style={{ flex: 1, lineHeight: 1.15 }}>{it.label}</span>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 9,
                  color: 'var(--ink-4)', letterSpacing: 0.6,
                }}>{it.note}</span>
                {it.badge && <Badge tone="hl">{it.badge}</Badge>}
              </a>
            );
          })}
        </div>
      ))}

      <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 6, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '6px 6px' }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            border: '1px solid var(--border)', background: 'var(--paper-dim)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 600, color: 'var(--ink-2)',
          }}>k</div>
          <div style={{ flex: 1, lineHeight: 1.15 }}>
            <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, fontWeight: 600 }}>k.lee</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--ink-3)' }}>HHS preparer</div>
          </div>
          <Icon glyph="⚙" size={13} style={{ color: 'var(--ink-3)' }}/>
        </div>
      </div>
    </aside>
  );
}

// =====================================================================
// GLOBAL NAV — Redwood top bar (dark warm-charcoal with brand accent)
// =====================================================================
function GlobalNav({ onHome, page, dept = "Sheriff's Office" }) {
  const utilities = [
    { id: 'apps',     glyph: '▦', label: 'Apps',     note: 'springboard' },
    { id: 'search',   glyph: '⌕', label: 'Search',   note: '⌘ K' },
    { id: 'notif',    glyph: '⚑', label: 'Alerts',   badge: 3 },
    { id: 'help',     glyph: '?', label: 'Help' },
  ];
  const homeHref = window.pagePath ? window.pagePath('springboard') : 'APIO.html';
  const handleHomeClick = (e) => { if (onHome) { e.preventDefault(); onHome(); } };
  return (
    <header style={{
      background: '#312d2a',
      color: '#ffffff',
      borderBottom: '1px solid #1f1b18',
      padding: '8px 24px',
      display: 'flex', alignItems: 'center', gap: 18,
      flexShrink: 0,
      height: 52, boxSizing: 'border-box',
    }}>
      {/* logo + app */}
      <a href={homeHref} onClick={handleHomeClick} title="Back to springboard"
         style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10, color: 'inherit', textDecoration: 'none' }}>
        <span style={{
          width: 28, height: 28, borderRadius: 6,
          background: 'var(--marker)', color: '#ffffff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700,
          letterSpacing: -0.3,
        }}>D</span>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.05 }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: 1.2, opacity: 0.6 }}>DALLAS COUNTY · FINANCE</span>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, letterSpacing: -0.01 }}>APIO Core</span>
        </div>
      </a>

      <span style={{ width: 1, height: 24, background: '#ffffff', opacity: 0.15 }}/>

      {/* dept context */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, opacity: 0.6, letterSpacing: 1.1 }}>DEPT</span>
        <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 13, fontWeight: 500 }}>{dept}</span>
      </div>

      <div style={{ flex: 1 }}/>

      {/* utility nav */}
      <nav style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
        {utilities.map((u) => (
          <button key={u.id} title={u.note ? `${u.label} · ${u.note}` : u.label} style={{
            background: 'transparent', color: '#ffffff',
            border: '1px solid transparent', borderRadius: 6,
            padding: '5px 9px', cursor: 'pointer',
            fontFamily: 'var(--font-sketch)', fontSize: 12,
            display: 'flex', alignItems: 'center', gap: 6, position: 'relative',
            transition: 'background 120ms ease',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
            <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 14, lineHeight: 1, opacity: 0.85 }}>{u.glyph}</span>
            <span>{u.label}</span>
            {u.badge && (
              <span style={{
                position: 'absolute', top: 1, right: 1,
                minWidth: 14, height: 14, padding: '0 3px', borderRadius: 7,
                background: 'var(--marker)', color: '#ffffff',
                fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: '1px solid #312d2a',
              }}>{u.badge}</span>
            )}
          </button>
        ))}

        <span style={{ width: 1, height: 22, background: '#ffffff', opacity: 0.15, margin: '0 6px' }}/>

        {/* user menu */}
        <button style={{
          background: 'rgba(255,255,255,0.08)', color: '#ffffff',
          border: '1px solid rgba(255,255,255,0.15)', borderRadius: 999,
          padding: '3px 10px 3px 3px', cursor: 'pointer',
          fontFamily: 'var(--font-sketch)', fontSize: 12,
          display: 'flex', alignItems: 'center', gap: 7,
          transition: 'background 120ms ease',
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.14)'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; }}>
          <span style={{
            width: 22, height: 22, borderRadius: '50%',
            background: 'var(--marker)', color: '#ffffff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600,
          }}>K</span>
          <span>k.lee</span>
          <span style={{ fontSize: 10, opacity: 0.7 }}>▾</span>
        </button>
      </nav>
    </header>
  );
}

// =====================================================================
// TOPBAR — page-level header below GlobalNav
// =====================================================================
function TopBar({ title, breadcrumb = [], note, actions }) {
  return (
    <div style={{
      borderBottom: '1px solid var(--border)', background: 'var(--surface)',
      padding: '14px 28px',
      display: 'flex', alignItems: 'flex-end', gap: 16, justifyContent: 'space-between',
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
        {breadcrumb.length > 0 && (
          <div style={{ fontFamily: 'var(--font-sketch)', fontSize: 12, color: 'var(--ink-3)', display: 'flex', gap: 6 }}>
            {breadcrumb.map((b, i) => (
              <React.Fragment key={i}>
                <span>{b}</span>
                {i < breadcrumb.length - 1 && <span style={{ color: 'var(--ink-4)' }}>›</span>}
              </React.Fragment>
            ))}
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600, margin: 0, lineHeight: 1.15, letterSpacing: -0.01 }}>{title}</h1>
          {note && <span style={{ fontFamily: 'var(--font-sketch)', fontSize: 13, color: 'var(--ink-3)' }}>· {note}</span>}
        </div>
      </div>
      {actions && <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{actions}</div>}
    </div>
  );
}

// =====================================================================
// MARGIN NOTE — annotation overlay (used sparingly in Redwood mode)
// =====================================================================
function MarginNote({ children, color = 'var(--redline)', tilt = 0, style }) {
  return (
    <div className="margin-note" style={{
      fontFamily: 'var(--font-sketch)', fontSize: 12, fontWeight: 500,
      color,
      lineHeight: 1.3,
      ...style,
    }}>{children}</div>
  );
}

function ArrowPointer({ dir = 'left', length = 60, tilt = 0, style }) {
  const arrows = { left: '←', right: '→', up: '↑', down: '↓', upleft: '↖', upright: '↗' };
  return (
    <span style={{
      fontFamily: 'var(--font-sketch)', fontSize: 18,
      color: 'var(--redline)',
      display: 'inline-block',
      ...style,
    }}>{arrows[dir]}</span>
  );
}

Object.assign(window, { Sidebar, TopBar, GlobalNav, MarginNote, ArrowPointer });
