/* Shared mock data + page layout */

const MOCK_INDEXES = [
  { id: 'idx_8a3f', name: 'surveillance-jan-2026', videos: 1284, hours: 312.4, size: '4.2 TB', status: 'ready', accent: 'east-perimeter, north-gate, parking-lot', updated: '2h ago', model: 'marengo-2.7' },
  { id: 'idx_2b91', name: 'product-demo-archive', videos: 86, hours: 24.1, size: '180 GB', status: 'ready', accent: 'launch reels, walkthroughs, podcasts', updated: 'yesterday', model: 'marengo-2.7' },
  { id: 'idx_7c4d', name: 'dashcam-fleet-q1', videos: 4128, hours: 988.2, size: '11.4 TB', status: 'indexing', progress: 0.62, accent: '142 vehicles, 38 routes', updated: '12m ago', model: 'marengo-2.7' },
  { id: 'idx_9f02', name: 'sports-broadcast-2025', videos: 312, hours: 624.0, size: '8.1 TB', status: 'ready', accent: 'NFL, NBA, premier league', updated: '4d ago', model: 'pegasus-1.2' },
  { id: 'idx_5e6a', name: 'ugc-moderation-pool', videos: 18420, hours: 2104.7, size: '24.8 TB', status: 'ready', accent: 'user uploads, last 30 days', updated: '1h ago', model: 'marengo-2.7' },
  { id: 'idx_4d33', name: 'manufacturing-line-a', videos: 720, hours: 168.0, size: '2.1 TB', status: 'failed', accent: 'plant 7, conveyor inspection', updated: '6h ago', model: 'marengo-2.7' },
];

const MOCK_VIDEOS = [
  { id: 'v_001', title: 'cam-04 / east-perimeter / 2026-01-14', duration: '08:00:00', size: '14.2 GB', codec: 'H.265', dwarfed: true, ratio: 38.4 },
  { id: 'v_002', title: 'cam-12 / north-gate / 2026-01-14', duration: '08:00:00', size: '12.8 GB', codec: 'H.265', dwarfed: true, ratio: 41.2 },
  { id: 'v_003', title: 'cam-04 / east-perimeter / 2026-01-15', duration: '08:00:00', size: '14.0 GB', codec: 'H.265', dwarfed: false },
  { id: 'v_004', title: 'cam-07 / parking-lot / 2026-01-14', duration: '08:00:00', size: '11.2 GB', codec: 'H.264', dwarfed: false },
  { id: 'v_005', title: 'cam-12 / north-gate / 2026-01-15', duration: '08:00:00', size: '12.6 GB', codec: 'H.265', dwarfed: true, ratio: 39.8 },
];

const MOCK_TOOLS = [
  { id: 'embed', name: 'Video Embeddings', desc: 'Generate dense vectors for clips, frames, or full videos.', icon: 'Layers', cost: '0.4 credits / min', tag: 'Search', popular: true },
  { id: 'caption', name: 'Captioning', desc: 'Frame-accurate transcripts and visual descriptions.', icon: 'Caption', cost: '1.2 credits / min', tag: 'Transcribe', popular: true },
  { id: 'highlights', name: 'Highlight Extraction', desc: 'Auto-clip the most engaging moments.', icon: 'Crop', cost: '0.8 credits / min', tag: 'Edit' },
  { id: 'segment', name: 'Scene Segmentation', desc: 'Detect shot, scene, and chapter boundaries.', icon: 'Film', cost: '0.3 credits / min', tag: 'Structure' },
  { id: 'detect', name: 'Object & Action Detection', desc: 'Bounding boxes, tracks, and actions per frame.', icon: 'Tag', cost: '0.9 credits / min', tag: 'Vision' },
  { id: 'enhance', name: 'Quality Enhancement', desc: 'Upscale to 4K, denoise, deinterlace.', icon: 'Wand', cost: '2.4 credits / min', tag: 'Restore' },
  { id: 'moderate', name: 'Content Moderation', desc: 'Flag nudity, violence, hate, and minors.', icon: 'Shield', cost: '0.5 credits / min', tag: 'Safety' },
  { id: 'finetune', name: 'Custom Fine-tuning', desc: 'Train a domain-specific embedder on your data.', icon: 'Sparkles', cost: 'from 4,000 credits', tag: 'Custom', new: true },
];

const MOCK_API_KEYS = [
  { id: 'k1', name: 'production', key: 'vmn_live_••••••••••••3f9a', created: '2026-01-08', last: '12s ago', scopes: ['index:*', 'tools:*'] },
  { id: 'k2', name: 'staging', key: 'vmn_test_••••••••••••a72c', created: '2026-01-10', last: '4h ago', scopes: ['index:read', 'tools:read'] },
  { id: 'k3', name: 'arjun-laptop', key: 'vmn_live_••••••••••••82de', created: '2025-12-20', last: '3d ago', scopes: ['index:*'] },
];

const MOCK_USAGE = [
  { day: 'M', credits: 124 }, { day: 'T', credits: 287 }, { day: 'W', credits: 198 },
  { day: 'T', credits: 412 }, { day: 'F', credits: 356 }, { day: 'S', credits: 84 }, { day: 'S', credits: 168 },
];

const NAV = [
  { id: 'home', label: 'Home', icon: 'Home', section: 'WORKSPACE' },
  { id: 'indexes', label: 'Stores', icon: 'Database', section: 'WORKSPACE', count: 6 },
  { id: 'tools', label: 'Tools', icon: 'Tools', section: 'WORKSPACE' },
  { id: 'dwarf', label: 'Dwarf', icon: 'Compress', section: 'INGEST INFRA' },
  { id: 'mellon', label: 'Mellon', icon: 'Layers', section: 'INGEST INFRA' },
  { id: 'training', label: 'Training', icon: 'Cpu', section: 'DATA INFRA', disabled: true },
  { id: 'inference', label: 'Inference', icon: 'Activity', section: 'DATA INFRA', disabled: true },
  { id: 'anvesha', label: 'Search', icon: 'Search', section: 'APP INFRA' },
  { id: 'curation', label: 'Curation', icon: 'Filter', section: 'APP INFRA', disabled: true },
  { id: 'streaming', label: 'Streaming', icon: 'Wave', section: 'EGRESS INFRA', disabled: true },
  { id: 'api', label: 'API Keys', icon: 'Key', section: 'DEVELOPER', disabled: true },
  { id: 'docs', label: 'Documentation', icon: 'Book', section: 'DEVELOPER', disabled: true },
  { id: 'credits', label: 'Credits & Billing', icon: 'Coins', section: 'ACCOUNT' },
  { id: 'settings', label: 'Settings', icon: 'Settings', section: 'ACCOUNT' },
];

/* ─── Sidebar ─── */

function Sidebar({ active, onNavigate, user, credits }) {
  const sections = [...new Set(NAV.map(n => n.section))];

  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <Logo size={20} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 16 }}>
        {sections.map(sec => (
          <React.Fragment key={sec}>
            <div className="sidebar-section">{sec}</div>
            {NAV.filter(n => n.section === sec).map(n => {
              const Comp = Icon[n.icon];
              return (
                <div key={n.id}
                  className={`nav-item ${active === n.id ? 'active' : ''} ${n.disabled ? 'disabled' : ''}`}
                  onClick={() => !n.disabled && onNavigate(n.id)}
                  style={n.disabled ? { opacity: 0.45, cursor: 'not-allowed', pointerEvents: 'auto' } : {}}>
                  <Comp size={15} />
                  <span>{n.label}</span>
                  {n.disabled && <span className="nav-count" style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Soon</span>}
                  {!n.disabled && n.count != null && <span className="nav-count">{n.count}</span>}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>

      {/* Credits chip */}
      <div style={{ padding: '12px 14px', borderTop: '1px solid var(--border-subtle)' }}>
        <div style={{
          padding: 12,
          background: 'var(--bg-inset)',
          borderRadius: 'var(--radius-md)',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <span className="eyebrow" style={{ fontSize: 10 }}>Credits</span>
            <button className="btn btn-ghost btn-sm" onClick={() => onNavigate('credits')}
              style={{ padding: '0 6px', height: 22, fontSize: 11 }}>
              Top up
            </button>
          </div>
          <div className="mono" style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 500, letterSpacing: '-0.02em' }}>
            {credits.toLocaleString()}
          </div>
          <div style={{ marginTop: 8, height: 3, background: 'var(--border-subtle)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{
              width: `${Math.min(100, (credits / 10000) * 100)}%`,
              height: '100%', background: 'var(--accent)', borderRadius: 2,
              transition: 'width 0.4s var(--ease-out)',
            }} />
          </div>
          <div style={{ marginTop: 6, fontSize: 10, color: 'var(--text-tertiary)' }}>
            Pro plan · resets May 1
          </div>
        </div>
      </div>
    </aside>
  );
}

/* ─── Topbar ─── */

function Topbar({ title, breadcrumb, user, onLogout, actions }) {
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    if (!menuOpen) return;
    const close = () => setMenuOpen(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [menuOpen]);

  return (
    <div className="topbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 13, color: 'var(--text-secondary)' }}>
        {breadcrumb?.map((b, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span style={{ color: 'var(--text-tertiary)' }}>/</span>}
            <span style={{ color: i === breadcrumb.length - 1 ? 'var(--text-primary)' : 'var(--text-secondary)', fontWeight: i === breadcrumb.length - 1 ? 500 : 400 }}>
              {b}
            </span>
          </React.Fragment>
        ))}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {actions}

        <div style={{ position: 'relative' }}>
          <button onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '4px 6px 4px 4px', borderRadius: 'var(--radius-md)',
              border: '1px solid transparent',
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-surface-hover)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
          >
            <Avatar user={user} size={28} />
            <Icon.ChevronDown size={13} color="var(--text-tertiary)" />
          </button>
          {menuOpen && (
            <div style={{
              position: 'absolute', top: '100%', right: 0, marginTop: 6,
              background: 'var(--bg-surface)',
              border: '1px solid var(--border-default)',
              borderRadius: 'var(--radius-md)',
              boxShadow: 'var(--shadow-lg)',
              minWidth: 220, padding: 6, zIndex: 100,
            }} className="fade-in">
              <div style={{ padding: '10px 10px 12px', borderBottom: '1px solid var(--border-subtle)', marginBottom: 6 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{user.name}</div>
                <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{user.email}</div>
              </div>
              {[
                { label: 'Profile', icon: 'User', id: 'settings' },
                { label: 'Billing', icon: 'Coins', id: 'credits' },
                { label: 'API Keys', icon: 'Key', id: 'api' },
              ].map(m => {
                const Comp = Icon[m.icon];
                return (
                  <div key={m.id}
                    onClick={() => { setMenuOpen(false); }}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '8px 10px', borderRadius: 4, cursor: 'pointer',
                      fontSize: 13, color: 'var(--text-primary)',
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-surface-hover)'}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                    <Comp size={14} color="var(--text-tertiary)" />
                    {m.label}
                  </div>
                );
              })}
              <div style={{ height: 1, background: 'var(--border-subtle)', margin: '6px 0' }} />
              <div onClick={onLogout} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', borderRadius: 4, cursor: 'pointer',
                fontSize: 13, color: 'var(--negative)',
              }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--negative-bg)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                <Icon.Logout size={14} />
                Sign out
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Avatar({ user, size = 32 }) {
  const initials = (user.name || 'U').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: 'linear-gradient(135deg, var(--accent), var(--accent-light))',
      color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.4, fontWeight: 500, letterSpacing: '-0.01em',
      flexShrink: 0,
    }}>
      {initials}
    </div>
  );
}

/* ─── Status pill ─── */

function StatusPill({ status, progress }) {
  if (status === 'ready') return <span className="badge badge-positive"><span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--positive)' }} />Ready</span>;
  if (status === 'indexing') return (
    <span className="badge badge-warning">
      <span className="spinner" style={{ width: 9, height: 9, borderTopColor: 'var(--warning)' }} />
      Indexing {progress != null ? `${Math.round(progress * 100)}%` : ''}
    </span>
  );
  if (status === 'encoding') return (
    <span className="badge badge-warning">
      <span className="spinner" style={{ width: 9, height: 9, borderTopColor: 'var(--warning)' }} />
      Encoding {progress != null ? `${Math.round(progress * 100)}%` : ''}
    </span>
  );
  if (status === 'failed') return <span className="badge badge-negative">Failed</span>;
  if (status === 'queued') return <span className="badge badge-neutral">Queued</span>;
  return <span className="badge badge-neutral">{status}</span>;
}

/* ─── Empty state ─── */

function EmptyState({ icon, title, body, cta }) {
  const Comp = Icon[icon] || Icon.Box;
  return (
    <div style={{
      padding: '64px 32px', textAlign: 'center', maxWidth: 460, margin: '0 auto',
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 12, margin: '0 auto 20px',
        background: 'var(--bg-inset)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Comp size={24} color="var(--text-tertiary)" />
      </div>
      <h3 style={{ fontSize: 16, fontWeight: 600, margin: '0 0 6px' }}>{title}</h3>
      <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: '0 0 20px' }}>{body}</p>
      {cta}
    </div>
  );
}

Object.assign(window, {
  MOCK_INDEXES, MOCK_VIDEOS, MOCK_TOOLS, MOCK_API_KEYS, MOCK_USAGE, NAV,
  Sidebar, Topbar, Avatar, StatusPill, EmptyState,
});
