
const { useState, useEffect } = React;

// ── Icons ────────────────────────────────────────────────────────
const Icons = {
  innerCircle: (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <circle cx="9" cy="9" r="7.5" stroke="currentColor" strokeWidth="1"/>
      <circle cx="9" cy="9" r="4.5" stroke="currentColor" strokeWidth="1"/>
      <circle cx="9" cy="9" r="1.8" fill="currentColor"/>
    </svg>
  ),
  oracle: (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <ellipse cx="9" cy="9" rx="7.5" ry="4.5" stroke="currentColor" strokeWidth="1"/>
      <circle cx="9" cy="9" r="2" fill="currentColor"/>
      <line x1="1.5" y1="9" x2="16.5" y2="9" stroke="currentColor" strokeWidth="0.8" strokeDasharray="2 1.5"/>
    </svg>
  ),
  ledger: (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <rect x="2.5" y="2.5" width="13" height="13" rx="1.5" stroke="currentColor" strokeWidth="1"/>
      <line x1="5" y1="6.5" x2="13" y2="6.5" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
      <line x1="5" y1="9" x2="13" y2="9" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
      <line x1="5" y1="11.5" x2="10" y2="11.5" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
    </svg>
  ),
  vault: (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <rect x="2" y="3.5" width="14" height="11" rx="1.5" stroke="currentColor" strokeWidth="1"/>
      <circle cx="9" cy="9" r="2.5" stroke="currentColor" strokeWidth="1"/>
      <line x1="11.5" y1="9" x2="14.5" y2="9" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
      <circle cx="9" cy="9" r="0.8" fill="currentColor"/>
    </svg>
  ),
  shadow: (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <rect x="5" y="8" width="8" height="7" rx="1.2" stroke="currentColor" strokeWidth="1"/>
      <path d="M6.5 8V6a2.5 2.5 0 0 1 5 0v2" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
      <line x1="9" y1="11" x2="9" y2="12.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
    </svg>
  ),
};

const navItems = [
  { id: 'inner-circle',  label: 'Command Center',       sub: 'System Overview',       icon: Icons.innerCircle },
  { id: 'oracle',        label: 'The Oracle Stream',    sub: 'AI Intelligence',       icon: Icons.oracle },
  { id: 'ledger',        label: 'The Sovereign Ledger', sub: 'Financial Suite',       icon: Icons.ledger },
  { id: 'vault',         label: "The Architect's Vault",sub: 'Project Dossiers',      icon: Icons.vault },
  { id: 'shadow',        label: 'Shadow Protocols',     sub: 'Future Tools',          icon: Icons.shadow },
];

// ── Sidebar ──────────────────────────────────────────────────────
const Sidebar = ({ active, onNav, onSettingsOpen }) => {
  const [profileMenuOpen, setProfileMenuOpen] = React.useState(false);
  const s = {
    sidebar: {
      position: 'fixed', top: 0, left: 0, bottom: 0,
      width: 'var(--sidebar-w)',
      background: 'rgba(8,8,8,0.96)',
      borderRight: '1px solid var(--border)',
      backdropFilter: 'blur(20px)',
      display: 'flex', flexDirection: 'column',
      zIndex: 20,
    },
    logoArea: {
      padding: '28px 24px 22px',
      borderBottom: '1px solid var(--border)',
    },
    logoMark: {
      display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12,
    },
    logoText: {
      fontFamily: "'JetBrains Mono'", fontSize: 11, fontWeight: 600,
      letterSpacing: '0.2em', color: 'var(--text)', textTransform: 'uppercase',
    },
    logoSub: {
      fontFamily: "'JetBrains Mono'", fontSize: 8,
      letterSpacing: '0.25em', color: 'var(--gold)', textTransform: 'uppercase',
    },
    statusBar: {
      display: 'flex', alignItems: 'center', gap: 6,
      padding: '6px 8px', borderRadius: 3,
      background: 'rgba(76,175,130,0.08)', border: '1px solid rgba(76,175,130,0.15)',
    },
    nav: {
      flex: 1, padding: '16px 12px', display: 'flex', flexDirection: 'column', gap: 3,
      overflowY: 'auto',
    },
    navItem: (isActive) => ({
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px', borderRadius: 6, cursor: 'pointer',
      transition: 'all 0.2s',
      background: isActive ? 'rgba(201,168,76,0.08)' : 'transparent',
      border: `1px solid ${isActive ? 'rgba(201,168,76,0.2)' : 'transparent'}`,
      color: isActive ? 'var(--gold)' : 'var(--text3)',
      position: 'relative',
    }),
    navIcon: { flexShrink: 0, opacity: 0.9 },
    navLabel: {
      display: 'flex', flexDirection: 'column', gap: 2,
    },
    navText: (isActive) => ({
      fontFamily: "'JetBrains Mono'", fontSize: 10, fontWeight: 500,
      letterSpacing: '0.1em', textTransform: 'uppercase',
      color: isActive ? 'var(--gold)' : 'inherit',
    }),
    navSub: {
      fontFamily: "'Inter'", fontSize: 9, color: 'var(--text3)', letterSpacing: '0.02em',
    },
    activePip: {
      position: 'absolute', left: 0, top: '50%', transform: 'translateY(-50%)',
      width: 2, height: 18, background: 'var(--gold)',
      borderRadius: '0 2px 2px 0',
      boxShadow: '0 0 8px rgba(201,168,76,0.6)',
    },
    footer: {
      padding: '16px 20px',
      borderTop: '1px solid var(--border)',
    },
    footerUser: {
      display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10,
    },
    avatar: {
      width: 28, height: 28, borderRadius: '50%',
      background: 'linear-gradient(135deg, #C9A84C, #8B6914)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'JetBrains Mono'", fontSize: 10, fontWeight: 700, color: '#0A0A0A',
      flexShrink: 0,
    },
    footerText: {
      fontFamily: "'JetBrains Mono'", fontSize: 9, color: 'var(--text3)', letterSpacing: '0.15em',
    },
  };

  return (
    <div style={s.sidebar}>
      <div style={s.logoArea}>
        <div style={s.logoMark}>
          <svg viewBox="0 0 40 40" width="28" height="28" style={{ filter:'drop-shadow(0 0 6px rgba(201,168,76,0.5))' }}>
            <polygon points="20,2 32,8 38,20 32,32 20,38 8,32 2,20 8,8"
              fill="none" stroke="#C9A84C" strokeWidth="1.5"/>
            <polygon points="20,10 30,20 20,30 10,20"
              fill="none" stroke="#4FC3F7" strokeWidth="1" opacity="0.7"/>
            <circle cx="20" cy="20" r="3" fill="none" stroke="#C9A84C" strokeWidth="1.2"/>
            <circle cx="20" cy="20" r="1" fill="#C9A84C"/>
          </svg>
          <div>
            <div style={s.logoText}>Cipher</div>
            <div style={s.logoSub}>Intelligence Hub</div>
          </div>
        </div>
        <div style={s.statusBar}>
          <div style={{ width:5, height:5, borderRadius:'50%', background:'#4CAF82',
            boxShadow:'0 0 5px rgba(76,175,130,0.8)', animation:'pulse-dot 2s ease-in-out infinite' }}/>
          <span style={{ fontFamily:"'JetBrains Mono'", fontSize:8, letterSpacing:'0.2em', color:'#4CAF82' }}>ALL SYSTEMS OPERATIONAL</span>
        </div>
      </div>

      <div style={{ padding:'12px 20px 4px' }}>
        <div style={{ fontFamily:"'JetBrains Mono'", fontSize:8, letterSpacing:'0.3em', color:'var(--text3)', textTransform:'uppercase' }}>
          Navigation
        </div>
      </div>

      <nav style={s.nav}>
        {navItems.map(item => {
          const isActive = active === item.id;
          return (
            <div key={item.id} style={s.navItem(isActive)} onClick={() => onNav(item.id)}
              onMouseEnter={e => { if (!isActive) { e.currentTarget.style.background='rgba(255,255,255,0.03)'; e.currentTarget.style.color='var(--text2)'; }}}
              onMouseLeave={e => { if (!isActive) { e.currentTarget.style.background='transparent'; e.currentTarget.style.color='var(--text3)'; }}}>
              {isActive && <div style={s.activePip}/>}
              <div style={s.navIcon}>{item.icon}</div>
              <div style={s.navLabel}>
                <span style={s.navText(isActive)}>{item.label}</span>
                <span style={s.navSub}>{item.sub}</span>
              </div>
            </div>
          );
        })}
      </nav>

      <div style={s.footer}>
        <div style={s.footerUser} onClick={() => setProfileMenuOpen(!profileMenuOpen)}
          style={{...s.footerUser, cursor: 'pointer', borderRadius: 4, padding: '8px 6px', marginLeft: -6, marginRight: -6,
            transition: 'background 0.2s', background: profileMenuOpen ? 'rgba(255,255,255,0.05)' : 'transparent'}}
          onMouseEnter={e => { if (!profileMenuOpen) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
          onMouseLeave={e => { if (!profileMenuOpen) e.currentTarget.style.background = 'transparent'; }}>
          <div style={s.avatar}>A</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily:"'JetBrains Mono'", fontSize: 9, color:'var(--text2)', letterSpacing:'0.1em' }}>AFONSO MARÇAL</div>
            <div style={s.footerText}>CLEARANCE LEVEL V</div>
          </div>
          <div style={{ fontSize: 10, color: 'var(--text3)', marginLeft: 6 }}>⌄</div>
        </div>
        {profileMenuOpen && (
          <div style={{ marginTop: 12, padding: '12px 10px', background: 'rgba(10,10,10,0.6)',
            border: '1px solid rgba(201,168,76,0.15)', borderRadius: 5, animation: 'slideInUp 0.2s ease-out' }}>
            <button onClick={() => { setProfileMenuOpen(false); onSettingsOpen?.(); }}
              style={{ width: '100%', padding: '8px 10px', marginBottom: 6, background: 'rgba(201,168,76,0.1)',
                border: '1px solid rgba(201,168,76,0.2)', borderRadius: 3, fontFamily: "'JetBrains Mono'", fontSize: 9,
                color: 'var(--gold)', cursor: 'pointer', letterSpacing: '0.1em', transition: 'all 0.2s' }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(201,168,76,0.2)'; e.currentTarget.style.boxShadow = '0 0 8px rgba(201,168,76,0.3)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(201,168,76,0.1)'; e.currentTarget.style.boxShadow = 'none'; }}>
              ⚙ Platform Settings
            </button>
            <button onClick={() => { setProfileMenuOpen(false); alert('Tool integrations coming soon'); }}
              style={{ width: '100%', padding: '8px 10px', marginBottom: 6, background: 'rgba(79,195,247,0.1)',
                border: '1px solid rgba(79,195,247,0.2)', borderRadius: 3, fontFamily: "'JetBrains Mono'", fontSize: 9,
                color: 'var(--blue)', cursor: 'pointer', letterSpacing: '0.1em', transition: 'all 0.2s' }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(79,195,247,0.2)'; e.currentTarget.style.boxShadow = '0 0 8px rgba(79,195,247,0.3)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(79,195,247,0.1)'; e.currentTarget.style.boxShadow = 'none'; }}>
              🔗 Connected Tools
            </button>
            <button onClick={() => { setProfileMenuOpen(false); alert('API keys management coming soon'); }}
              style={{ width: '100%', padding: '8px 10px', background: 'rgba(255,255,255,0.05)',
                border: '1px solid rgba(255,255,255,0.1)', borderRadius: 3, fontFamily: "'JetBrains Mono'", fontSize: 9,
                color: 'var(--text3)', cursor: 'pointer', letterSpacing: '0.1em', transition: 'all 0.2s' }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.05)'; }}>
              🔐 API Keys
            </button>
          </div>
        )}
        <div style={{ fontFamily:"'JetBrains Mono'", fontSize:8, color:'var(--text3)', letterSpacing:'0.12em', lineHeight:1.8, marginTop: profileMenuOpen ? 0 : 10 }}>
          SESSION: ACTIVE<br/>
          CIPHER SYS v4.1 · 2026
        </div>
      </div>
    </div>
  );
};

// ── Page renderer ────────────────────────────────────────────────
const pageMap = {
  'inner-circle': InnerCircle,
  'oracle':       OracleStream,
  'ledger':       SovereignLedger,
  'vault':        ArchitectsVault,
  'shadow':       ShadowProtocols,
};

// ── Dashboard shell ──────────────────────────────────────────────
const Dashboard = () => {
  const [activePage, setActivePage] = useState('inner-circle');
  const [pageKey, setPageKey] = useState(0);
  const [settingsOpen, setSettingsOpen] = useState(false);

  const navigate = (id) => {
    setActivePage(id);
    setPageKey(k => k + 1);
  };

  const PageComponent = pageMap[activePage] || InnerCircle;

  return (
    <div style={{ display:'flex', height:'100vh', background:'var(--bg)' }}>
      {/* Subtle grid background */}
      <div style={{ position:'fixed', inset:0, pointerEvents:'none', zIndex:0, overflow:'hidden' }}>
        <svg width="100%" height="100%" style={{ opacity:0.018 }}>
          <defs>
            <pattern id="grid" width="60" height="60" patternUnits="userSpaceOnUse">
              <path d="M 60 0 L 0 0 0 60" fill="none" stroke="white" strokeWidth="0.8"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#grid)"/>
        </svg>
        {/* Radial vignette */}
        <div style={{ position:'absolute', inset:0,
          background:'radial-gradient(ellipse at 60% 40%, rgba(201,168,76,0.025) 0%, transparent 60%)' }}/>
      </div>

      <Sidebar active={activePage} onNav={navigate} onSettingsOpen={() => setSettingsOpen(true)}/>
      <window.SettingsModal isOpen={settingsOpen} onClose={() => setSettingsOpen(false)}/>

      <main style={{ marginLeft:'var(--sidebar-w)', flex:1, height:'100vh', overflow:'hidden', position:'relative', zIndex:1 }}>
        {/* Top bar */}
        <div style={{ height:52, borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center',
          justifyContent:'space-between', padding:'0 36px', background:'rgba(10,10,10,0.8)', backdropFilter:'blur(12px)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <span style={{ fontFamily:"'JetBrains Mono'", fontSize:8, letterSpacing:'0.3em', color:'var(--text3)', textTransform:'uppercase' }}>
              {navItems.find(n => n.id === activePage)?.label}
            </span>
            <span style={{ color:'var(--text3)', opacity:0.4, fontSize:10 }}>·</span>
            <span style={{ fontFamily:"'JetBrains Mono'", fontSize:8, color:'var(--text3)', letterSpacing:'0.2em' }}>
              {navItems.find(n => n.id === activePage)?.sub}
            </span>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:16 }}>
            {[['SECURE','#4CAF82'],['ENCRYPTED','#C9A84C'],['LEVEL V','#4FC3F7']].map(([label, color]) => (
              <div key={label} style={{ display:'flex', alignItems:'center', gap:5 }}>
                <div style={{ width:4, height:4, borderRadius:'50%', background:color, boxShadow:`0 0 5px ${color}80` }}/>
                <span style={{ fontFamily:"'JetBrains Mono'", fontSize:8, letterSpacing:'0.2em', color:'var(--text3)' }}>{label}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Page content */}
        <div key={pageKey} style={{ height:'calc(100vh - 52px)', overflowY:'auto' }}>
          <PageComponent/>
        </div>
      </main>
    </div>
  );
};

// ── App root ─────────────────────────────────────────────────────
const App = () => {
  const [appReady, setAppReady] = useState(false);

  return appReady
    ? <Dashboard/>
    : <BreachGate onUnlock={() => setAppReady(true)}/>;
};

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
