import { NavLink, Outlet } from 'react-router-dom';
import { getApiKey, promptForApiKey, clearApiKey } from '../api';
import { PipelineStatus } from './PipelineStatus';
import { OrgSwitcher } from './OrgSwitcher';
import { useOrg } from '../hooks/useOrg';

const links = [
  { to: '/', label: 'Overview' },
  { to: '/sessions', label: 'Sessions' },
];

// VITE_API_URL is set at build time for display only (env badge).
// Actual requests always go through the Vite proxy (relative URLs).
const API_URL = import.meta.env.VITE_API_URL || '';
const isLocal = !API_URL;

export function Layout() {
  const { org, setOrg } = useOrg();

  return (
    <div className="min-h-screen flex flex-col bg-surface">
      {/* Top bar */}
      <header className="bg-surface-raised border-b border-border">
        <div className="max-w-7xl mx-auto w-full px-6 flex items-center justify-between h-14">
          {/* Left: brand + env badge */}
          <div className="flex items-center gap-3">
            <NavLink to="/" className="flex items-center gap-2 group">
              <div className="w-7 h-7 rounded-lg bg-accent flex items-center justify-center">
                <span className="text-white font-bold text-xs">QC</span>
              </div>
              <span className="text-sm font-semibold text-text-primary tracking-tight">
                Quickcall <span className="text-text-muted font-normal">Trace</span>
              </span>
            </NavLink>
            <span
              className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${
                isLocal
                  ? 'bg-green-500/10 text-green-600 dark:text-green-400'
                  : 'bg-blue-500/10 text-blue-600 dark:text-blue-400'
              }`}
            >
              <span className={`w-1.5 h-1.5 rounded-full ${isLocal ? 'bg-green-500' : 'bg-blue-500'}`} />
              {isLocal ? 'Local' : new URL(API_URL).host}
            </span>
          </div>

          {/* Right: controls */}
          <div className="flex items-center gap-3">
            <OrgSwitcher org={org} setOrg={setOrg} />
            <div className="w-px h-5 bg-border" />
            <PipelineStatus />
            <div className="w-px h-5 bg-border" />
            <button
              onClick={() => {
                if (getApiKey()) {
                  if (window.confirm('Clear stored API key?')) {
                    clearApiKey();
                    window.location.reload();
                  }
                } else {
                  promptForApiKey().then((k) => { if (k) window.location.reload(); });
                }
              }}
              className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${
                getApiKey()
                  ? 'bg-green-500/10 text-green-600 dark:text-green-400 hover:bg-green-500/20'
                  : 'bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/20'
              }`}
              title={getApiKey() ? 'API key set — click to clear' : 'No API key — click to set'}
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="w-4 h-4">
                <path fillRule="evenodd" d="M8 7a5 5 0 113.61 4.804l-1.903 1.903A1 1 0 019 14H8v1a1 1 0 01-1 1H6v1a1 1 0 01-1 1H3a1 1 0 01-1-1v-2a1 1 0 01.293-.707L8.196 8.39A5.002 5.002 0 018 7zm5-3a.75.75 0 000 1.5A1.5 1.5 0 0114.5 7 .75.75 0 0016 7a3 3 0 00-3-3z" clipRule="evenodd" />
              </svg>
            </button>
          </div>
        </div>

        {/* Nav tabs — second row, tight under header */}
        <div className="max-w-7xl mx-auto w-full px-6">
          <nav className="flex gap-0 -mb-px">
            {links.map((l) => (
              <NavLink
                key={l.to}
                to={l.to}
                end
                className={({ isActive }) =>
                  `px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                    isActive
                      ? 'border-accent text-accent'
                      : 'border-transparent text-text-muted hover:text-text-primary hover:border-border'
                  }`
                }
              >
                {l.label}
              </NavLink>
            ))}
          </nav>
        </div>
      </header>

      <main className="flex-1 p-6 max-w-7xl mx-auto w-full">
        <Outlet context={{ org }} />
      </main>
    </div>
  );
}
