import React from 'react';
import { createRoot } from 'react-dom/client';
import { Activity, BarChart3, Gauge, KeyRound, LockKeyhole, PenLine, Settings, Shield, SlidersHorizontal } from 'lucide-react';
import './styles.css';

const routes = ['product', 'leaderboards', 'pricing', 'docs', 'login', 'signup', 'app'];

const leaderboardRows = [
  { model: 'Astra-4.1', rank: '01', speed: '812ms', cost: '$0.42', quality: '94', provider: 'Northline' },
  { model: 'Vela Mini', rank: '02', speed: '344ms', cost: '$0.08', quality: '82', provider: 'Kite' },
  { model: 'Helio Reason', rank: '03', speed: '1.1s', cost: '$0.61', quality: '96', provider: 'Prism' },
  { model: 'Sable Chat', rank: '04', speed: '520ms', cost: '$0.13', quality: '87', provider: 'Orbit' },
];

const docs = [
  ['01', 'Create an API key in the app.'],
  ['02', 'Point requests at the Laminarity endpoint.'],
  ['03', 'Use aliases like balanced, fast, or low-cost.'],
  ['04', 'Set limits before traffic ramps up.'],
];

const appTabs = [
  { id: 'overview', label: 'Overview', icon: Activity },
  { id: 'keys', label: 'Keys', icon: KeyRound },
  { id: 'usage', label: 'Usage', icon: BarChart3 },
  { id: 'limits', label: 'Limits', icon: SlidersHorizontal },
  { id: 'aliases', label: 'Aliases', icon: PenLine },
  { id: 'settings', label: 'Settings', icon: Settings },
];

function getInitialRoute() {
  const hash = window.location.hash.replace('#/', '').replace('#', '');
  return routes.includes(hash) ? hash : 'product';
}

function App() {
  const [route, setRoute] = React.useState(getInitialRoute);
  const [loggedIn, setLoggedIn] = React.useState(() => localStorage.getItem('laminarity-auth') === 'true');
  const [appTab, setAppTab] = React.useState('overview');

  React.useEffect(() => {
    const onHashChange = () => setRoute(getInitialRoute());
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  function navigate(nextRoute) {
    window.location.hash = `/${nextRoute}`;
    setRoute(nextRoute);
  }

  function setAuth(nextValue) {
    setLoggedIn(nextValue);
    localStorage.setItem('laminarity-auth', String(nextValue));
    navigate(nextValue ? 'app' : 'product');
  }

  return (
    <div className="app-shell">
      <Header route={route} loggedIn={loggedIn} navigate={navigate} setAuth={setAuth} />
      <main>
        {route === 'product' && <ProductPage navigate={navigate} />}
        {route === 'leaderboards' && <LeaderboardsPage />}
        {route === 'pricing' && <PricingPage navigate={navigate} />}
        {route === 'docs' && <DocsPage />}
        {route === 'login' && <AuthPage mode="login" setAuth={setAuth} navigate={navigate} />}
        {route === 'signup' && <AuthPage mode="signup" setAuth={setAuth} navigate={navigate} />}
        {route === 'app' && <AppDashboard appTab={appTab} setAppTab={setAppTab} loggedIn={loggedIn} setAuth={setAuth} />}
      </main>
    </div>
  );
}

function Header({ route, loggedIn, navigate, setAuth }) {
  const publicLinks = [
    ['product', 'Product'],
    ['leaderboards', 'Leaderboards'],
    ['pricing', 'Pricing'],
    ['docs', 'Docs'],
  ];

  return (
    <header className="site-header">
      <button className="brand" onClick={() => navigate('product')} aria-label="Laminarity product page">
        <span className="brand-mark">L</span>
        <span className="brand-word">Laminarity</span>
      </button>
      <nav className="nav-links" aria-label="Main navigation">
        {publicLinks.map(([id, label]) => (
          <button key={id} className={route === id ? 'active' : ''} onClick={() => navigate(id)}>
            {label}
          </button>
        ))}
      </nav>
      <div className="auth-actions">
        {loggedIn ? (
          <>
            <button className={route === 'app' ? 'ghost active' : 'ghost'} onClick={() => navigate('app')}>
              Launch App
            </button>
            <button className="icon-button" onClick={() => setAuth(false)} aria-label="Log out">
              <LockKeyhole size={18} />
            </button>
          </>
        ) : (
          <>
            <button className={route === 'login' ? 'ghost active' : 'ghost'} onClick={() => navigate('login')}>
              Login
            </button>
            <button className="primary" onClick={() => navigate('signup')}>
              Sign Up
            </button>
          </>
        )}
      </div>
    </header>
  );
}

function ProductPage({ navigate }) {
  return (
    <section className="page product-page">
      <div className="hero-grid">
        <div className="hero-copy">
          <p className="eyebrow">&lt;alpha_frontend / product&gt;</p>
          <h1>Intelligent API Routing for the AI Era</h1>
          <div className="value-list">
            <p><span>01</span> One key, unlimited access</p>
            <p><span>02</span> Transparency you can trust</p>
            <p><span>03</span> Unified billing at every scale</p>
          </div>
          <div className="button-row">
            <button className="primary" onClick={() => navigate('signup')}>Start Building</button>
            <button className="ghost" onClick={() => navigate('docs')}>View Docs</button>
          </div>
        </div>
        <RoutingPanel />
      </div>
    </section>
  );
}

function RoutingPanel() {
  return (
    <aside className="routing-panel" aria-label="Routing preview">
      <div className="panel-top">
        <span>route.preview</span>
        <Gauge size={18} />
      </div>
      <div className="route-stack">
        <div className="route-card strong">
          <span>input</span>
          <strong>POST /v1/chat</strong>
        </div>
        <div className="flow-line" />
        <div className="route-card">
          <span>policy</span>
          <strong>balanced</strong>
        </div>
        <div className="flow-line" />
        <div className="route-card accent">
          <span>selected</span>
          <strong>Astra-4.1</strong>
        </div>
      </div>
    </aside>
  );
}

function LeaderboardsPage() {
  return (
    <section className="page">
      <PageIntro kicker="leaderboards" title="Model rankings for the routes that matter." text="Alpha data is mocked for now, but the shape is ready for real telemetry." />
      <div className="leaderboard">
        <div className="leaderboard-head">
          <span>Rank</span>
          <span>Model</span>
          <span>Speed</span>
          <span>Cost / 1K</span>
          <span>Quality</span>
        </div>
        {leaderboardRows.map((row) => (
          <div className="leaderboard-row" key={row.model}>
            <span className="rank">{row.rank}</span>
            <span>
              <strong>{row.model}</strong>
              <small>{row.provider}</small>
            </span>
            <span>{row.speed}</span>
            <span>{row.cost}</span>
            <span>{row.quality}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function PricingPage({ navigate }) {
  return (
    <section className="page">
      <PageIntro kicker="pricing" title="Simple alpha pricing." text="Start small, set limits, and scale only when routing is worth it." />
      <div className="pricing-grid">
        {['Free', 'Pro', 'Team'].map((tier, index) => (
          <article className={index === 1 ? 'price-card featured' : 'price-card'} key={tier}>
            <p className="eyebrow">{tier}</p>
            <h2>{index === 0 ? '$0' : index === 1 ? '$19' : 'Contact'}</h2>
            <p>{index === 0 ? 'Prototype routing with mock-friendly limits.' : index === 1 ? 'Higher caps and alias controls.' : 'Shared usage and project controls.'}</p>
            <button className={index === 1 ? 'primary' : 'ghost'} onClick={() => navigate('signup')}>
              Select
            </button>
          </article>
        ))}
      </div>
    </section>
  );
}

function DocsPage() {
  return (
    <section className="page docs-page">
      <PageIntro kicker="docs" title="Alpha quickstart." text="The first docs page stays focused on the minimum path to a routed request." />
      <div className="docs-grid">
        <div className="code-panel">
          <p className="eyebrow">request</p>
          <pre>{`curl https://api.laminarity.ai/v1/chat \\
  -H "Authorization: Bearer $LAMINARITY_KEY" \\
  -d '{ "model": "balanced", "messages": [...] }'`}</pre>
        </div>
        <div className="doc-steps">
          {docs.map(([step, label]) => (
            <p key={step}><span>{step}</span>{label}</p>
          ))}
        </div>
      </div>
    </section>
  );
}

function AuthPage({ mode, setAuth, navigate }) {
  const isSignup = mode === 'signup';
  return (
    <section className="page auth-page">
      <div className="auth-card">
        <p className="eyebrow">{isSignup ? 'sign_up' : 'login'}</p>
        <h1>{isSignup ? 'Request alpha access.' : 'Return to Laminarity.'}</h1>
        <label>Email<input type="email" placeholder="you@example.com" /></label>
        <label>Password<input type="password" placeholder="••••••••" /></label>
        {isSignup && <label>Invite Code<input type="text" placeholder="optional" /></label>}
        <button className="primary" onClick={() => setAuth(true)}>
          {isSignup ? 'Create Account' : 'Login'}
        </button>
        <button className="text-button" onClick={() => navigate(isSignup ? 'login' : 'signup')}>
          {isSignup ? 'Already have access?' : 'Need alpha access?'}
        </button>
      </div>
    </section>
  );
}

function AppDashboard({ appTab, setAppTab, loggedIn, setAuth }) {
  if (!loggedIn) {
    return (
      <section className="page auth-page">
        <div className="auth-card">
          <p className="eyebrow">app_access</p>
          <h1>Login to launch the app.</h1>
          <button className="primary" onClick={() => setAuth(true)}>Use Alpha Session</button>
        </div>
      </section>
    );
  }

  const ActiveIcon = appTabs.find((tab) => tab.id === appTab)?.icon ?? Activity;

  return (
    <section className="app-page">
      <aside className="app-sidebar">
        <p className="eyebrow">web_app</p>
        {appTabs.map((tab) => {
          const Icon = tab.icon;
          return (
            <button key={tab.id} className={appTab === tab.id ? 'active' : ''} onClick={() => setAppTab(tab.id)}>
              <Icon size={17} />
              {tab.label}
            </button>
          );
        })}
      </aside>
      <div className="app-content">
        <div className="app-title">
          <ActiveIcon size={24} />
          <div>
            <p className="eyebrow">{appTab}</p>
            <h1>{appTabs.find((tab) => tab.id === appTab)?.label}</h1>
          </div>
        </div>
        <DashboardPanel appTab={appTab} />
      </div>
    </section>
  );
}

function DashboardPanel({ appTab }) {
  if (appTab === 'keys') {
    return <SimplePanel title="API Keys" rows={['Create a new alpha key', 'Copy key once after creation', 'Revoke inactive keys']} action="Create Key" icon={KeyRound} />;
  }
  if (appTab === 'usage') {
    return <MetricPanel />;
  }
  if (appTab === 'limits') {
    return <SimplePanel title="Limits" rows={['Monthly spend cap: $25', 'Requests per minute: 60', 'Warning threshold: 80%']} action="Edit Limits" icon={Shield} />;
  }
  if (appTab === 'aliases') {
    return <SimplePanel title="Aliases" rows={['balanced -> best current route', 'fast -> lowest latency route', 'low-cost -> lowest price route']} action="Edit Aliases" icon={PenLine} />;
  }
  if (appTab === 'settings') {
    return <SimplePanel title="Settings" rows={['Account email', 'Default project', 'Billing placeholder']} action="Save Settings" icon={Settings} />;
  }
  return <MetricPanel />;
}

function MetricPanel() {
  return (
    <div className="metric-grid">
      {[
        ['Requests', '12,408'],
        ['Avg Latency', '612ms'],
        ['Spend', '$14.82'],
        ['Active Keys', '3'],
      ].map(([label, value]) => (
        <article className="metric-card" key={label}>
          <span>{label}</span>
          <strong>{value}</strong>
        </article>
      ))}
    </div>
  );
}

function SimplePanel({ title, rows, action, icon: Icon }) {
  return (
    <div className="simple-panel">
      <div className="simple-title">
        <Icon size={22} />
        <h2>{title}</h2>
      </div>
      {rows.map((row) => <p key={row}>{row}</p>)}
      <button className="primary">{action}</button>
    </div>
  );
}

function PageIntro({ kicker, title, text }) {
  return (
    <div className="page-intro">
      <p className="eyebrow">&lt;{kicker}&gt;</p>
      <h1>{title}</h1>
      <p>{text}</p>
    </div>
  );
}

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