import { ReactNode, useEffect, useRef, useState } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import AmbientBackground from '../Ambient/AmbientBackground';
import SystemStatusBar from '../Visual/SystemStatusBar';
import { useWebSocket } from '../../hooks/useWebSocket';
import MatrixRain from './MatrixRain';
import afLogo from '../../assets/af-logo.png';
import CursorFire from '../Visual/CursorFire';
import './Layout.css';

interface LayoutProps {
  children: ReactNode;
}

const NAV = [
  { to: '/dashboard', label: 'Command Deck', icon: 'deck' },
  { to: '/agents', label: 'Fleet Roster', icon: 'fleet' },
  { to: '/crucible', label: 'Crucible', icon: 'crucible' },
  { to: '/forge', label: 'Forge', icon: 'forge' },
  { to: '/builds', label: 'Builds', icon: 'builds' },
  { to: '/guide', label: 'Field Guide', icon: 'guide' },
  { to: '/settings', label: 'Calibrate', icon: 'gear' },
] as const;

function NavIcon({ type }: { type: string }) {
  switch (type) {
    case 'deck':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M4 19V5h16v14M4 9h16M8 5v4M16 5v4" />
          <circle cx="12" cy="14" r="2" />
        </svg>
      );
    case 'fleet':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <rect x="2" y="6" width="20" height="12" rx="1" />
          <path d="M6 10h4M14 10h4M6 14h2M16 14h2" />
        </svg>
      );
    case 'forge':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M14 4l6 6-8 8H6v-6l8-8z" />
          <path d="M8 16l-2 4 4-2" />
        </svg>
      );
    case 'builds':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <rect x="3" y="14" width="18" height="5" rx="1" />
          <rect x="3" y="8" width="18" height="5" rx="1" />
          <rect x="3" y="2" width="18" height="5" rx="1" />
          <path d="M7 4.5h10M7 10.5h10M7 16.5h10" strokeOpacity="0.35" />
        </svg>
      );
    case 'guide':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M4 19.5A2.5 2.5 0 016.5 17H20" />
          <path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z" />
          <path d="M8 7h8M8 11h6" />
        </svg>
      );
    case 'crucible':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M8 3h8l1 5H7L8 3z" />
          <path d="M7 8c0 5 2 8 5 10c3-2 5-5 5-10" />
          <path d="M4 21h16" />
          <path d="M10 12l1.5 2L14 11" />
        </svg>
      );
    default:
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <circle cx="12" cy="12" r="3" />
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
        </svg>
      );
  }
}

function formatHashrate(hs: number): string {
  if (hs >= 1_000_000) return `${(hs / 1_000_000).toFixed(2)} MH/s`;
  if (hs >= 1_000)     return `${(hs / 1_000).toFixed(1)} KH/s`;
  return `${hs.toFixed(0)} H/s`;
}

function FleetReadout() {
  const { agents } = useWebSocket();
  const online = agents.filter((a) => a.status === 'online').length;
  const total  = agents.length;
  const totalHashrate = agents.reduce((sum, a) => sum + (a.hashrate_15s ?? a.hashrate_15m ?? 0), 0);
  const fillPct = total > 0 ? Math.round((online / total) * 100) : 0;

  // Tick animation: flash hashrate value whenever it meaningfully changes
  const [flash, setFlash] = useState(false);
  const prevHash = useRef(0);
  useEffect(() => {
    if (Math.abs(totalHashrate - prevHash.current) > 1) {
      prevHash.current = totalHashrate;
      setFlash(true);
      const t = setTimeout(() => setFlash(false), 600);
      return () => clearTimeout(t);
    }
  }, [totalHashrate]);

  return (
    <div className="fleet-readout">
      <div className="readout-row">
        <span className={`readout-dot ${online > 0 ? 'readout-dot-online' : 'readout-dot-idle'}`} />
        <span className="readout-label">MACHINES</span>
        <span className="readout-value readout-value-machines">
          {online}<span className="readout-dim">/{total}</span>
        </span>
      </div>
      <div className="readout-row">
        <span className="readout-glyph">≈</span>
        <span className="readout-label">HASHRATE</span>
        <span className={`readout-value ${flash ? 'readout-flash' : ''}`}>
          {totalHashrate > 0 ? formatHashrate(totalHashrate) : <span className="readout-dim">IDLE</span>}
        </span>
      </div>
      <div className="readout-bar-wrap" title={`${online} of ${total} online`}>
        <div className="readout-bar-track">
          <div
            className={`readout-bar-fill ${online > 0 ? 'readout-bar-active' : ''}`}
            style={{ width: `${fillPct}%` }}
          />
        </div>
        <span className="readout-bar-pct">{fillPct}%</span>
      </div>
    </div>
  );
}

export default function Layout({ children }: LayoutProps) {
  const location = useLocation();

  return (
    <div className="layout">
      <CursorFire />
      <AmbientBackground />
      <nav className="sidebar">
        <div className="sidebar-header">
          <div className="logo">
            <div className="logo-emblem">
              <span className="logo-gear" />
              <img src={afLogo} alt="AetherForge" className="logo-af-img" />
            </div>
            <div className="logo-text-block">
              <span className="logo-text">AetherForge</span>
              <span className="logo-tagline font-tech">COMMAND DECK</span>
            </div>
          </div>
        </div>

        <div className="sidebar-nav">
          {NAV.map((item) => (
            <NavLink
              key={item.to}
              to={item.to}
              className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}
            >
              <span className="nav-icon">
                <NavIcon type={item.icon} />
              </span>
              <span className="nav-label">{item.label}</span>
              {location.pathname === item.to && <span className="nav-glow" />}
            </NavLink>
          ))}
        </div>

        {/* Matrix rain log — fills the lower sidebar between nav and footer */}
        <MatrixRain />

        <div className="sidebar-footer">
          <FleetReadout />
          <div className="sidebar-sig font-tech">
            <span className="sig-love">made with <span className="sig-heart">♥</span> drjones</span>
            <span className="sig-ver">v0.0.1</span>
          </div>
        </div>
      </nav>

      <div className="main-with-status">
        <SystemStatusBar />
        <main className="main-content">{children}</main>
      </div>
    </div>
  );
}
