// Admin shell: sidebar + command palette + sparkline/bar chart primitives + shared styles

const adminStyles = {
  mono: { fontFamily: "'JetBrains Mono', monospace" },
  monoLabel: { fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: '0.22em', color: '#565656' },
};

// Sparkline SVG
const Sparkline = ({ data, width = 120, height = 32, color = '#10B981', fill = true }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => [
    (i / (data.length - 1)) * width,
    height - ((v - min) / range) * (height - 2) - 1,
  ]);
  const line = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
  const area = `${line} L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      {fill && <path d={area} fill={color} opacity={0.1} />}
      <path d={line} fill="none" stroke={color} strokeWidth={1.2} />
    </svg>
  );
};

const Bars = ({ data, width = 260, height = 56, color = '#10B981', highlight = -1 }) => {
  const max = Math.max(...data);
  const gap = 1;
  const bw = (width - gap * (data.length - 1)) / data.length;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      {data.map((v, i) => {
        const h = (v / max) * (height - 2);
        return <rect key={i} x={i * (bw + gap)} y={height - h} width={bw} height={h} fill={i === highlight ? '#EDEDED' : color} opacity={i === highlight ? 1 : 0.7} rx={0.5} />;
      })}
    </svg>
  );
};

// STATUS DOT
const StatusDot = ({ status }) => {
  const color = status === 'ok' ? '#10B981' : status === 'warn' ? '#F59E0B' : status === 'err' ? '#DC2626' : '#565656';
  return <span style={{ width: 7, height: 7, borderRadius: '50%', background: color, display: 'inline-block', boxShadow: status === 'ok' ? `0 0 4px ${color}` : 'none' }} />;
};

// SIDEBAR
const AdminSidebar = ({ current, onNav, collapsed, onToggle, onOpenPalette }) => {
  const items = [
    { id: 'dashboard', label: 'Dashboard', icon: <IconGrid size={13} /> },
    { id: 'domains', label: 'Domains', icon: <IconGlobe size={13} /> },
    { id: 'keys', label: 'Keys', icon: <IconKey size={13} /> },
    { id: 'firehose', label: 'Firehose', icon: <IconActivity size={13} />, live: true },
    { id: 'abuse', label: 'Abuse', icon: <IconShield size={13} /> },
    { id: 'health', label: 'System', icon: <IconServer size={13} /> },
    { id: 'audit', label: 'Audit log', icon: <IconScroll size={13} /> },
    { id: 'settings', label: 'Settings', icon: <IconSettings size={13} /> },
  ];
  const w = collapsed ? 52 : 208;
  return (
    <div style={{ width: w, background: '#0D0D0D', borderRight: '1px solid #1f1f1f', display: 'flex', flexDirection: 'column', flexShrink: 0, transition: 'width 180ms ease' }}>
      <div style={{ padding: collapsed ? '14px 0' : '14px 14px', display: 'flex', alignItems: 'center', justifyContent: collapsed ? 'center' : 'space-between', borderBottom: '1px solid #161616' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 22, height: 22, borderRadius: 4, background: '#F59E0B', display: 'flex', alignItems: 'center', justifyContent: 'center', ...adminStyles.mono, fontSize: 11, fontWeight: 700, color: '#0A0A0A' }}>A</div>
          {!collapsed && <div style={{ ...adminStyles.mono, fontSize: 11, letterSpacing: '0.18em', color: '#EDEDED' }}>ADMIN<span style={{ color: '#F59E0B' }}>·</span>CTL</div>}
        </div>
      </div>

      {!collapsed && (
        <button onClick={onOpenPalette} style={{
          margin: 10, padding: '7px 10px', background: '#141414', border: '1px solid #1f1f1f', borderRadius: 5,
          display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', color: '#8A8A8A',
          ...adminStyles.mono, fontSize: 11,
        }}>
          <IconSearch size={11} />
          <span style={{ flex: 1, textAlign: 'left' }}>Command…</span>
          <span style={{ padding: '1px 5px', border: '1px solid #262626', borderRadius: 3, fontSize: 9 }}>⌘K</span>
        </button>
      )}

      <div style={{ flex: 1, padding: '6px 6px', overflowY: 'auto' }}>
        {items.map((it) => (
          <button
            key={it.id}
            onClick={() => onNav(it.id)}
            title={collapsed ? it.label : undefined}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 10,
              padding: collapsed ? '9px 0' : '8px 10px', justifyContent: collapsed ? 'center' : 'flex-start',
              background: current === it.id ? '#181818' : 'transparent',
              border: 'none',
              borderLeft: !collapsed ? `2px solid ${current === it.id ? '#F59E0B' : 'transparent'}` : 'none',
              color: current === it.id ? '#EDEDED' : '#8A8A8A',
              cursor: 'pointer', borderRadius: collapsed ? 5 : 3, marginBottom: 1,
              fontFamily: "'Geist', system-ui, sans-serif", fontSize: 13,
              transition: 'background 100ms',
            }}
            onMouseEnter={(e) => current !== it.id && (e.currentTarget.style.background = '#141414')}
            onMouseLeave={(e) => current !== it.id && (e.currentTarget.style.background = 'transparent')}
          >
            {it.icon}
            {!collapsed && <span style={{ flex: 1, textAlign: 'left' }}>{it.label}</span>}
            {!collapsed && it.live && <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#10B981', animation: 'pulse 2s ease-in-out infinite' }} />}
          </button>
        ))}
      </div>

      <div style={{ borderTop: '1px solid #161616', padding: collapsed ? '10px 0' : '10px 12px' }}>
        <button onClick={onToggle} style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, background: 'none', border: 'none', color: '#565656', cursor: 'pointer', ...adminStyles.mono, fontSize: 10, letterSpacing: '0.15em', padding: 4 }}>
          {collapsed ? '»' : '« COLLAPSE'}
        </button>
      </div>
    </div>
  );
};

// COMMAND PALETTE
const CommandPalette = ({ open, onClose, onRun }) => {
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (open) { setQ(''); setTimeout(() => inputRef.current?.focus(), 20); } }, [open]);
  if (!open) return null;

  const cmds = [
    { id: 'nav:dashboard', label: 'Go to Dashboard', kind: 'nav', hotkey: 'G D' },
    { id: 'nav:domains', label: 'Go to Domains', kind: 'nav', hotkey: 'G O' },
    { id: 'nav:keys', label: 'Go to Keys', kind: 'nav', hotkey: 'G K' },
    { id: 'nav:firehose', label: 'Go to Firehose', kind: 'nav', hotkey: 'G F' },
    { id: 'nav:abuse', label: 'Go to Abuse', kind: 'nav' },
    { id: 'nav:health', label: 'Go to System health', kind: 'nav' },
    { id: 'nav:audit', label: 'Go to Audit log', kind: 'nav' },
    { id: 'nav:settings', label: 'Go to Settings', kind: 'nav' },
    { id: 'act:newkey', label: 'Generate new access key', kind: 'action', hotkey: 'N K' },
    { id: 'act:adddomain', label: 'Add shared domain', kind: 'action', hotkey: 'N D' },
    { id: 'act:blocksender', label: 'Block sender pattern', kind: 'action' },
    { id: 'act:pause', label: 'Pause / resume firehose', kind: 'action' },
    { id: 'act:export', label: 'Export keys as CSV', kind: 'action' },
    { id: 'act:signout', label: 'Sign out admin session', kind: 'action' },
  ];
  const filtered = q ? cmds.filter(c => c.label.toLowerCase().includes(q.toLowerCase())) : cmds;

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 400, animation: 'fadeIn 120ms' }} />
      <div style={{ position: 'fixed', top: '14%', left: '50%', transform: 'translateX(-50%)', width: '90%', maxWidth: 580, background: '#111', border: '1px solid #1f1f1f', borderRadius: 10, zIndex: 401, overflow: 'hidden', animation: 'zoomInTop 150ms ease' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid #1f1f1f' }}>
          <IconSearch size={14} stroke="#8A8A8A" />
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Type a command or search…" style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: '#EDEDED', fontFamily: "'Geist', system-ui, sans-serif", fontSize: 15 }} />
          <span style={{ ...adminStyles.mono, fontSize: 9, color: '#565656', border: '1px solid #262626', padding: '2px 5px', borderRadius: 3, letterSpacing: '0.1em' }}>ESC</span>
        </div>
        <div style={{ maxHeight: 380, overflowY: 'auto', padding: 6 }}>
          {filtered.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: '#565656', fontSize: 12 }}>No matches</div>}
          {filtered.map((c, i) => (
            <button key={c.id} onClick={() => { onRun(c.id); onClose(); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 12px', background: i === 0 ? '#181818' : 'transparent', border: 'none',
              cursor: 'pointer', borderRadius: 5, marginBottom: 1, color: '#EDEDED',
            }}
              onMouseEnter={(e) => e.currentTarget.style.background = '#181818'}
              onMouseLeave={(e) => e.currentTarget.style.background = i === 0 ? '#181818' : 'transparent'}
            >
              <span style={{ ...adminStyles.mono, fontSize: 9, letterSpacing: '0.15em', color: c.kind === 'nav' ? '#60A5FA' : '#F59E0B', width: 36 }}>
                {c.kind === 'nav' ? 'NAV' : 'ACT'}
              </span>
              <span style={{ flex: 1, textAlign: 'left', fontSize: 13 }}>{c.label}</span>
              {c.hotkey && <span style={{ ...adminStyles.mono, fontSize: 10, color: '#565656', letterSpacing: '0.1em' }}>{c.hotkey}</span>}
            </button>
          ))}
        </div>
      </div>
    </>
  );
};

// Shared page chrome
const AdminPageHeader = ({ title, count, children }) => (
  <div style={{ padding: '16px 24px', borderBottom: '1px solid #1f1f1f', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexShrink: 0 }}>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
      <h1 style={{ margin: 0, fontSize: 18, fontWeight: 500, color: '#EDEDED' }}>{title}</h1>
      {count !== undefined && <span style={{ ...adminStyles.mono, fontSize: 11, color: '#565656', letterSpacing: '0.08em' }}>{count}</span>}
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{children}</div>
  </div>
);

const AdminBtn = ({ children, onClick, variant = 'muted', danger, size = 'md' }) => {
  const pad = size === 'sm' ? '5px 10px' : '8px 12px';
  const fs = size === 'sm' ? 11 : 12;
  const base = { padding: pad, borderRadius: 5, cursor: 'pointer', fontFamily: "'Geist', system-ui, sans-serif", fontSize: fs, display: 'inline-flex', alignItems: 'center', gap: 6, transition: 'background 100ms, border-color 100ms' };
  const styles = {
    primary: { ...base, background: '#F59E0B', color: '#0A0A0A', border: 'none', fontWeight: 600 },
    primaryGreen: { ...base, background: '#10B981', color: '#0A0A0A', border: 'none', fontWeight: 600 },
    muted: { ...base, background: 'transparent', color: danger ? '#DC2626' : '#EDEDED', border: `1px solid ${danger ? '#3a1414' : '#262626'}` },
    ghost: { ...base, background: 'transparent', color: '#8A8A8A', border: 'none' },
  };
  return <button onClick={onClick} style={styles[variant]}
    onMouseEnter={(e) => { if (variant === 'muted') e.currentTarget.style.background = danger ? '#2a0e0e' : '#1a1a1a'; }}
    onMouseLeave={(e) => { if (variant === 'muted') e.currentTarget.style.background = 'transparent'; }}
  >{children}</button>;
};

// Admin icons (not in main set)
const IconGrid = (p) => <Icon {...p}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></Icon>;
const IconGlobe = (p) => <Icon {...p}><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15 15 0 0 1 0 20"/><path d="M12 2a15 15 0 0 0 0 20"/></Icon>;
const IconKey = (p) => <Icon {...p}><circle cx="7.5" cy="15.5" r="4.5"/><path d="M10.5 12.5 22 1"/><path d="m18 5 3 3"/><path d="m14 9 3 3"/></Icon>;
const IconActivity = (p) => <Icon {...p}><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></Icon>;
const IconShield = (p) => <Icon {...p}><path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5l-8-3z"/></Icon>;
const IconServer = (p) => <Icon {...p}><rect x="2" y="3" width="20" height="6" rx="1"/><rect x="2" y="14" width="20" height="6" rx="1"/><path d="M6 6h.01"/><path d="M6 17h.01"/></Icon>;
const IconScroll = (p) => <Icon {...p}><path d="M8 3H6a2 2 0 0 0-2 2v6"/><path d="M4 11v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2h-2"/><path d="M8 3v18"/><path d="M16 3v18"/></Icon>;
const IconPause = (p) => <Icon {...p}><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></Icon>;
const IconPlay = (p) => <Icon {...p} fill="currentColor" sw={0}><path d="M5 3 19 12 5 21Z"/></Icon>;
const IconDownload = (p) => <Icon {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></Icon>;
const IconEye = (p) => <Icon {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></Icon>;
const IconFilter = (p) => <Icon {...p}><path d="M22 3H2l8 9.5V20l4-2v-5.5L22 3z"/></Icon>;

Object.assign(window, { Sparkline, Bars, StatusDot, AdminSidebar, CommandPalette, AdminPageHeader, AdminBtn, adminStyles, IconGrid, IconGlobe, IconKey, IconActivity, IconShield, IconServer, IconScroll, IconPause, IconPlay, IconDownload, IconEye, IconFilter });
