// admin-shell.jsx — Sidebar + Topbar (light purple, landing-aligned)
// 모든 색은 CSS 변수 참조 → 다크모드 토글이 [data-theme="dark"]만 바꿔도 전부 반응
const ADMIN_COLORS = {
  bg: 'var(--c-bg)',
  panel: 'var(--c-panel)',
  panelSoft: 'var(--c-panel-soft)',
  border: 'var(--c-border)',
  borderStrong: 'var(--c-border-strong)',
  borderHi: 'var(--c-border-hi)',
  text: 'var(--c-text)',
  textSoft: 'var(--c-text-soft)',
  muted: 'var(--c-muted)',
  faint: 'var(--c-faint)',
  primary: 'var(--c-primary)',
  primaryDeep: 'var(--c-primary-deep)',
  primarySoft: 'var(--c-primary-soft)',
  primarySofter: 'var(--c-primary-softer)',
  good: 'var(--c-good)',
  goodSoft: 'var(--c-good-soft)',
  warn: 'var(--c-warn)',
  warnSoft: 'var(--c-warn-soft)',
  bad: 'var(--c-bad)',
  badSoft: 'var(--c-bad-soft)',
  rowSoft: 'var(--c-row-soft)',
  rowSofter: 'var(--c-row-softer)',
};

const NAV_ITEMS = [
  { id: 'dashboard', label: '대시보드' },
  { id: 'users', label: '유저' },
  { id: 'stats', label: '통계' },
  { id: 'beta-requests', label: '베타 신청자' },
  { id: 'whitelist', label: '화이트리스트' },
  { id: 'ai-cost', label: '🪙 AI 비용', divider: true },
  { id: 'review-queue', label: '🚨 검토 큐' },
  { id: 'action-logs', label: '📋 활동 로그' },
  { id: 'toggles', label: '⚡ 긴급 토글' },
  { id: 'alerts', label: '🔔 알림 구독' },
  { id: 'feedback', label: '📨 피드백' },
  { id: 'messages', label: '💬 메시지' },
  { id: 'announcements', label: '📣 공지' },
];

function Sidebar({ route }) {
  return (
    <aside style={{
      width: 220, flexShrink: 0,
      background: ADMIN_COLORS.panel,
      borderRight: `1px solid ${ADMIN_COLORS.border}`,
      display: 'flex', flexDirection: 'column',
      position: 'sticky', top: 0, height: '100vh',
    }}>
      {/* 로고 */}
      <div style={{ padding: '24px 24px 20px', borderBottom: `1px solid ${ADMIN_COLORS.border}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-0.02em', color: ADMIN_COLORS.text }}>
            Keitta
          </div>
          <span style={{
            fontSize: 9, fontWeight: 800, letterSpacing: '0.14em',
            color: ADMIN_COLORS.primary, background: ADMIN_COLORS.primarySoft,
            padding: '3px 7px', borderRadius: 4, textTransform: 'uppercase',
          }}>ADMIN</span>
        </div>
      </div>

      {/* 메뉴 */}
      <nav style={{ flex: 1, padding: '12px 12px', display: 'flex', flexDirection: 'column', gap: 1, overflowY: 'auto' }}>
        {NAV_ITEMS.map(item => {
          const active = route === item.id;
          return (
            <React.Fragment key={item.id}>
              {item.divider && <div style={{ height: 1, background: ADMIN_COLORS.border, margin: '8px 12px' }}/>}
              <a href={`#${item.id}`} style={{
                display: 'block',
                padding: '10px 14px',
                borderRadius: 8,
                fontSize: 13.5, fontWeight: active ? 700 : 500,
                color: active ? ADMIN_COLORS.primary : ADMIN_COLORS.muted,
                background: active ? ADMIN_COLORS.primarySoft : 'transparent',
                textDecoration: 'none',
                transition: 'background 0.12s, color 0.12s',
                borderLeft: active ? `2px solid ${ADMIN_COLORS.primary}` : '2px solid transparent',
                paddingLeft: 12,
              }}
                onMouseEnter={e => { if (!active) { e.currentTarget.style.background = ADMIN_COLORS.primarySofter; e.currentTarget.style.color = ADMIN_COLORS.text; } }}
                onMouseLeave={e => { if (!active) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = ADMIN_COLORS.muted; } }}
              >
                {item.label}
              </a>
            </React.Fragment>
          );
        })}
      </nav>

      {/* 하단: 환경 + 일반 모드 */}
      <div style={{ padding: '16px 20px', borderTop: `1px solid ${ADMIN_COLORS.border}`, display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ fontSize: 11, color: ADMIN_COLORS.faint, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: ADMIN_COLORS.good }}/>
          <span className="mono">prod · v0.4.2</span>
        </div>
        <a href="Keitta Landing.html" style={{
          fontSize: 12, color: ADMIN_COLORS.muted, textDecoration: 'none', fontWeight: 500,
        }}
          onMouseEnter={e => e.currentTarget.style.color = ADMIN_COLORS.primary}
          onMouseLeave={e => e.currentTarget.style.color = ADMIN_COLORS.muted}
        >
          ← 일반 모드
        </a>
      </div>
    </aside>
  );
}

function Topbar({ title, subtitle, right }) {
  return (
    <header style={{
      padding: '28px 40px 8px',
      maxWidth: 1280, width: '100%', margin: '0 auto',
      borderBottom: `1px solid ${ADMIN_COLORS.border}`,
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap',
    }}>
      <div>
        <h1 style={{
          fontSize: 22, fontWeight: 800, letterSpacing: '-0.015em',
          color: ADMIN_COLORS.text, margin: 0,
        }}>{title}</h1>
        {subtitle && (
          <div style={{ fontSize: 12, color: ADMIN_COLORS.faint, marginTop: 6 }}>{subtitle}</div>
        )}
      </div>
      {right && <div>{right}</div>}
    </header>
  );
}

// 공통 UI primitive

function Card({ children, style, padding = 20 }) {
  return (
    <div style={{
      background: ADMIN_COLORS.panel,
      border: `1px solid ${ADMIN_COLORS.border}`,
      borderRadius: 12,
      padding,
      ...style,
    }}>{children}</div>
  );
}

function StatCard({ label, value, sub, hint, trend }) {
  return (
    <Card padding={0}>
      <div style={{ padding: '16px 18px', borderBottom: `1px solid ${ADMIN_COLORS.border}` }}>
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
          color: ADMIN_COLORS.muted, textTransform: 'uppercase',
        }}>{label}</div>
      </div>
      <div style={{ padding: '16px 18px 18px' }}>
        <div className="mono" style={{
          fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em',
          color: ADMIN_COLORS.text, lineHeight: 1.1,
          display: 'flex', alignItems: 'baseline', gap: 8,
        }}>
          {value}
          {trend !== undefined && (
            <span style={{
              fontSize: 12, fontWeight: 700,
              color: trend >= 0 ? ADMIN_COLORS.good : ADMIN_COLORS.bad,
            }}>
              {trend >= 0 ? '▲' : '▼'} {Math.abs(trend)}%
            </span>
          )}
        </div>
        {sub && <div style={{ fontSize: 12, color: ADMIN_COLORS.muted, marginTop: 6 }}>{sub}</div>}
        {hint && <div className="mono" style={{ fontSize: 10.5, color: ADMIN_COLORS.faint, marginTop: 6 }}>{hint}</div>}
      </div>
    </Card>
  );
}

function Pill({ children, tone = 'neutral', size = 'sm' }) {
  const tones = {
    neutral: { bg: ADMIN_COLORS.rowSoft, fg: ADMIN_COLORS.text },
    primary: { bg: ADMIN_COLORS.primarySoft, fg: ADMIN_COLORS.primary },
    good:    { bg: ADMIN_COLORS.goodSoft, fg: ADMIN_COLORS.good },
    warn:    { bg: ADMIN_COLORS.warnSoft, fg: ADMIN_COLORS.warn },
    bad:     { bg: ADMIN_COLORS.badSoft, fg: ADMIN_COLORS.bad },
    mono:    { bg: ADMIN_COLORS.rowSofter, fg: ADMIN_COLORS.muted },
  };
  const t = tones[tone] || tones.neutral;
  const padY = size === 'xs' ? 2 : 3;
  const padX = size === 'xs' ? 6 : 8;
  const fs = size === 'xs' ? 10.5 : 11;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: `${padY}px ${padX}px`, borderRadius: 5,
      background: t.bg, color: t.fg,
      fontSize: fs, fontWeight: 700, letterSpacing: 0,
      whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function Btn({ children, kind = 'default', size = 'md', onClick, disabled, style }) {
  const variants = {
    primary: { bg: ADMIN_COLORS.primary, fg: 'white', border: ADMIN_COLORS.primary, hoverBg: ADMIN_COLORS.primaryDeep },
    default: { bg: ADMIN_COLORS.panel, fg: ADMIN_COLORS.text, border: ADMIN_COLORS.borderStrong, hoverBg: ADMIN_COLORS.panelSoft },
    ghost:   { bg: 'transparent', fg: ADMIN_COLORS.muted, border: 'transparent', hoverBg: ADMIN_COLORS.primarySofter },
    danger:  { bg: ADMIN_COLORS.panel, fg: ADMIN_COLORS.bad, border: 'rgba(239,68,68,0.3)', hoverBg: ADMIN_COLORS.badSoft },
  };
  const v = variants[kind] || variants.default;
  const padY = size === 'sm' ? 6 : 9;
  const padX = size === 'sm' ? 12 : 16;
  const fs = size === 'sm' ? 12 : 13;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      padding: `${padY}px ${padX}px`,
      background: v.bg, color: v.fg,
      border: `1px solid ${v.border}`, borderRadius: 7,
      fontSize: fs, fontWeight: 600, letterSpacing: '-0.005em',
      transition: 'background 0.12s', whiteSpace: 'nowrap',
      opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer',
      ...style,
    }}
      onMouseEnter={e => !disabled && (e.currentTarget.style.background = v.hoverBg)}
      onMouseLeave={e => !disabled && (e.currentTarget.style.background = v.bg)}
    >{children}</button>
  );
}

function Input({ value, onChange, placeholder, type = 'text', style, icon }) {
  return (
    <div style={{ position: 'relative', ...style }}>
      {icon && (
        <div style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: ADMIN_COLORS.faint, fontSize: 12, pointerEvents: 'none' }}>
          {icon}
        </div>
      )}
      <input type={type} value={value} onChange={onChange} placeholder={placeholder} style={{
        width: '100%',
        padding: icon ? '8px 10px 8px 30px' : '8px 10px',
        background: ADMIN_COLORS.panel,
        border: `1px solid ${ADMIN_COLORS.border}`,
        borderRadius: 7,
        fontSize: 13, color: ADMIN_COLORS.text,
        outline: 'none',
        transition: 'border-color 0.12s, box-shadow 0.12s',
      }}
        onFocus={e => { e.currentTarget.style.borderColor = ADMIN_COLORS.primary; e.currentTarget.style.boxShadow = `0 0 0 3px ${ADMIN_COLORS.primarySoft}`; }}
        onBlur={e => { e.currentTarget.style.borderColor = ADMIN_COLORS.border; e.currentTarget.style.boxShadow = 'none'; }}
      />
    </div>
  );
}

function Select({ value, onChange, options, style }) {
  return (
    <select value={value} onChange={onChange} style={{
      padding: '8px 28px 8px 10px',
      background: ADMIN_COLORS.panel,
      border: `1px solid ${ADMIN_COLORS.border}`,
      borderRadius: 7,
      fontSize: 13, color: ADMIN_COLORS.text,
      outline: 'none',
      appearance: 'none',
      backgroundImage: `url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3e%3cpath d='M1 1l4 4 4-4' stroke='%235A5470' stroke-width='1.5' fill='none'/%3e%3c/svg%3e")`,
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'right 10px center',
      ...style,
    }}>
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  );
}

function Tabs({ value, onChange, tabs }) {
  return (
    <div style={{
      display: 'inline-flex', gap: 2,
      padding: 3, background: ADMIN_COLORS.primarySofter,
      borderRadius: 8,
    }}>
      {tabs.map(t => {
        const active = value === t.value;
        return (
          <button key={t.value} onClick={() => onChange(t.value)} style={{
            padding: '6px 14px',
            background: active ? ADMIN_COLORS.panel : 'transparent',
            border: 0, borderRadius: 6,
            fontSize: 12.5, fontWeight: active ? 700 : 500,
            color: active ? ADMIN_COLORS.primary : ADMIN_COLORS.muted,
            boxShadow: active ? '0 1px 3px rgba(124,92,252,0.15)' : 'none',
            cursor: 'pointer', whiteSpace: 'nowrap',
          }}>
            {t.label}
            {t.count !== undefined && (
              <span style={{
                marginLeft: 6, padding: '1px 6px', borderRadius: 4,
                background: active ? ADMIN_COLORS.primarySoft : ADMIN_COLORS.rowSoft,
                color: active ? ADMIN_COLORS.primary : ADMIN_COLORS.muted,
                fontSize: 10, fontWeight: 700,
              }} className="mono">{t.count}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

window.AdminShell = { Sidebar, Topbar, Card, StatCard, Pill, Btn, Input, Select, Tabs, COLORS: ADMIN_COLORS };
window.ADMIN_COLORS = ADMIN_COLORS;
