import { useState, useEffect } from 'react';
import { NavLink } from 'react-router-dom';
import {
  LayoutGrid,
  Trophy,
  FlaskConical,
  ScanLine,
  LineChart,
  ParkingSquare,
  PanelLeftClose,
  TrendingUp,
  Zap,
  Compass,
  ScrollText,
} from 'lucide-react';

const NAV = [
  { to: '/', icon: LayoutGrid, label: 'Overview', end: true },
  { to: '/leaderboard', icon: Trophy, label: 'Leaderboard' },
  { to: '/experiments', icon: FlaskConical, label: 'Strategies' },
  { to: '/backtest', icon: ScanLine, label: 'Backtest' },
  { to: '/intraday', icon: TrendingUp, label: 'Intraday ORB' },
  { to: '/orb-trading', icon: Zap, label: 'ORB Trading' },
  { to: '/paper', icon: LineChart, label: 'Paper Trading' },
  { to: '/advisor', icon: Compass, label: 'Advisor' },
  { to: '/logs', icon: ScrollText, label: 'Logs / Health' },
];

const DOCS_NAV = [
  { to: '/docs/cash-parking', icon: ParkingSquare, label: 'Cash Parking' },
];

const EXPANDED_W = 230;
const COLLAPSED_W = 56;
const STORAGE_KEY = 'sidebar-collapsed';

export function Sidebar() {
  const [collapsed, setCollapsed] = useState(() => {
    try { return localStorage.getItem(STORAGE_KEY) === '1'; } catch { return false; }
  });

  const width = collapsed ? COLLAPSED_W : EXPANDED_W;

  useEffect(() => {
    document.documentElement.style.setProperty('--sidebar-w', `${width}px`);
    try { localStorage.setItem(STORAGE_KEY, collapsed ? '1' : '0'); } catch {}
  }, [collapsed, width]);

  const toggle = () => setCollapsed(c => !c);

  return (
    <aside
      style={{
        width,
        background: 'var(--bg1)',
        borderRight: '1px solid var(--border)',
        display: 'flex',
        flexDirection: 'column',
        position: 'fixed',
        left: 0,
        top: 0,
        height: '100%',
        zIndex: 30,
        transition: 'width 0.18s ease',
        overflow: 'hidden',
      }}
    >
      {/* Logo + Toggle */}
      <div style={{ padding: collapsed ? '20px 0 16px' : '20px 18px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', transition: 'padding 0.18s ease' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: collapsed ? '0 auto' : undefined }}>
          <div
            onClick={collapsed ? toggle : undefined}
            title={collapsed ? 'Expand sidebar' : undefined}
            style={{
              width: 30,
              height: 30,
              borderRadius: 7,
              background: 'linear-gradient(135deg, var(--cyan) 0%, #0052cc 100%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              boxShadow: '0 2px 8px rgba(0,119,182,0.25)',
              flexShrink: 0,
              cursor: collapsed ? 'pointer' : 'default',
            }}
          >
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M3 3h12v3H7v2h5v3H7v4H3V3z" fill="white"/>
            </svg>
          </div>
          {!collapsed && (
            <div>
              <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 16, color: 'var(--text1)', letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>
                Fithia2
              </div>
              <div style={{ fontSize: 12, color: 'var(--text3)', letterSpacing: '0.05em', marginTop: 1, whiteSpace: 'nowrap' }}>
                STRATEGY OS
              </div>
            </div>
          )}
        </div>
        {!collapsed && (
          <button
            onClick={toggle}
            title="Collapse sidebar"
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: 4, background: 'none', border: 'none', cursor: 'pointer',
              color: 'var(--text3)', borderRadius: 5, transition: 'color 0.12s',
            }}
            onMouseEnter={e => (e.currentTarget.style.color = 'var(--text1)')}
            onMouseLeave={e => (e.currentTarget.style.color = 'var(--text3)')}
          >
            <PanelLeftClose size={16} />
          </button>
        )}
      </div>

      {/* Nav */}
      <nav style={{ flex: 1, padding: collapsed ? '12px 6px' : '12px 10px', display: 'flex', flexDirection: 'column', gap: 2, overflowY: 'auto', transition: 'padding 0.18s ease' }}>
        {NAV.map(({ to, icon: Icon, label, end }) => (
          <NavLink
            key={to}
            to={to}
            end={end}
            title={collapsed ? label : undefined}
            style={({ isActive }) => ({
              display: 'flex',
              alignItems: 'center',
              gap: 9,
              padding: collapsed ? '9px 0' : '9px 11px',
              justifyContent: collapsed ? 'center' : 'flex-start',
              borderRadius: 8,
              fontSize: 15,
              fontWeight: 500,
              textDecoration: 'none',
              transition: 'all 0.12s',
              position: 'relative',
              color: isActive ? 'var(--cyan)' : 'var(--text2)',
              background: isActive ? 'var(--cyan-dim)' : 'transparent',
              borderLeft: isActive ? '2px solid var(--cyan)' : '2px solid transparent',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            })}
          >
            {({ isActive }) => (
              <>
                <Icon size={15} style={{ opacity: isActive ? 1 : 0.65, flexShrink: 0 }} />
                {!collapsed && <span>{label}</span>}
              </>
            )}
          </NavLink>
        ))}

        {/* Docs section */}
        <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
          {!collapsed && (
            <div style={{ padding: '2px 11px 8px', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text3)', whiteSpace: 'nowrap' }}>
              Docs
            </div>
          )}
          {DOCS_NAV.map(({ to, icon: Icon, label }) => (
            <NavLink
              key={to}
              to={to}
              title={collapsed ? label : undefined}
              style={({ isActive }) => ({
                display: 'flex',
                alignItems: 'center',
                gap: 9,
                padding: collapsed ? '8px 0' : '8px 11px',
                justifyContent: collapsed ? 'center' : 'flex-start',
                borderRadius: 8,
                fontSize: 14,
                fontWeight: 500,
                textDecoration: 'none',
                transition: 'all 0.12s',
                color: isActive ? 'var(--orange)' : 'var(--text3)',
                background: isActive ? 'color-mix(in srgb, var(--orange) 10%, transparent)' : 'transparent',
                borderLeft: isActive ? '2px solid var(--orange)' : '2px solid transparent',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              })}
            >
              {({ isActive }) => (
                <>
                  <Icon size={14} style={{ opacity: isActive ? 1 : 0.55, flexShrink: 0 }} />
                  {!collapsed && <span>{label}</span>}
                </>
              )}
            </NavLink>
          ))}
        </div>
      </nav>

      {/* Footer */}
      <div style={{ padding: collapsed ? '14px 0' : '14px 18px', borderTop: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: collapsed ? 'center' : 'flex-start', gap: 7 }}>
        <div
          style={{
            width: 7,
            height: 7,
            borderRadius: '50%',
            background: 'var(--green)',
            animation: 'pulse-line 2s infinite',
            flexShrink: 0,
          }}
        />
        {!collapsed && (
          <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text3)', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>
            LOCAL · v1.0
          </span>
        )}
      </div>
    </aside>
  );
}
