import { NavLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '../../stores/authStore';
import { check as healthCheck } from '../../api/health';
import { getRunningJobs } from '../../api/jobs';
import { useMarketRegime } from '../../hooks/useMarketRegime';
import { regimeDot, regimeHeadline } from '../../lib/regime';
import TickerSearch from './TickerSearch';

const navItems = [
  { to: '/', label: 'Overview', end: true },
  { to: '/market', label: 'Market', end: false },
  { to: '/signals', label: 'Signals', end: false },
  { to: '/regime', label: 'Regime', end: false },
];

const linkClasses = (isActive: boolean) =>
  `pb-0.5 text-[13.5px] font-medium transition-colors border-b ${
    isActive
      ? 'border-blue-500 text-gray-100'
      : 'border-transparent text-gray-400 hover:text-gray-200'
  }`;

/** Desktop command bar — the mockup's top navigation. MobileNav covers <lg. */
export default function TopBar() {
  const { role, username, logout } = useAuthStore();

  const health = useQuery({
    queryKey: ['health'],
    queryFn: healthCheck,
    refetchInterval: 30_000,
    retry: 1,
  });

  const isBackendUp = health.isSuccess;

  const jobs = useQuery({
    queryKey: ['jobs', 'running'],
    queryFn: getRunningJobs,
    refetchInterval: 10_000,
    retry: 1,
    enabled: isBackendUp,
  });

  const running = jobs.data?.running ?? [];
  const regime = useMarketRegime();

  return (
    <header className="glass sticky top-0 z-40 hidden items-center gap-7 rounded-none border-x-0 border-t-0 px-8 py-3 lg:flex">
      {/* Wordmark */}
      <NavLink to="/" className="flex items-center" aria-label="Signal — overview">
        <span className="font-display text-[15px] font-bold tracking-[0.4em] text-gray-100">
          SIGNAL
        </span>
        <span
          className="ml-0.5 inline-block h-[7px] w-[7px] rounded-full bg-[#ff6a45]"
          style={{ boxShadow: '0 0 10px rgba(255,106,69,.7)' }}
        />
      </NavLink>

      <nav className="flex items-center gap-6" aria-label="Sections">
        {navItems.map(({ to, label, end }) => (
          <NavLink key={to} to={to} end={end} className={({ isActive }) => linkClasses(isActive)}>
            {label}
          </NavLink>
        ))}
        {role === 'admin' && (
          <NavLink to="/admin" className={({ isActive }) => linkClasses(isActive)}>
            Admin
          </NavLink>
        )}
      </nav>

      <div className="w-56">
        <TickerSearch />
      </div>

      <div className="ml-auto flex items-center gap-5">
        {/* Market regime — ambient status; the full picture lives on /regime */}
        {regime.data && (
          <NavLink
            to="/regime"
            className="group flex items-center gap-2"
            title={`${regimeHeadline(regime.data)}${
              regime.data.label === 'bearish'
                ? ' — be cautious on new longs'
                : regime.data.label === 'bullish'
                  ? ' — shorts are counter-trend'
                  : ''
            }`}
          >
            <span className={`inline-block h-1.5 w-1.5 rounded-full ${regimeDot(regime.data.label)}`} />
            <span className="text-[11px] capitalize text-gray-500 transition-colors group-hover:text-gray-300">
              {regime.data.label} regime
            </span>
          </NavLink>
        )}
        {/* Live background-job activity, condensed */}
        {running.length > 0 && (
          <span className="flex max-w-[220px] items-center gap-2" title={running.map((j) => j.label).join(' · ')}>
            <span className="inline-block h-1.5 w-1.5 shrink-0 animate-signal-pulse rounded-full bg-blue-400" />
            <span className="truncate text-[11px] text-gray-400">
              {running[0].label}
              {running[0].progress_pct != null && (
                <span className="num text-gray-500"> {Math.round(running[0].progress_pct)}%</span>
              )}
              {running.length > 1 && <span className="text-gray-500"> +{running.length - 1}</span>}
            </span>
          </span>
        )}
        <span
          className={`inline-block h-2 w-2 rounded-full ${
            isBackendUp ? 'bg-emerald-400 shadow-lg shadow-emerald-400/50' : 'bg-red-400 shadow-lg shadow-red-400/50'
          }`}
          title={isBackendUp ? 'Backend online' : 'Backend offline'}
          aria-label={isBackendUp ? 'Backend online' : 'Backend offline'}
        />
        {username && <span className="max-w-[140px] truncate text-xs text-gray-500">{username}</span>}
        <button
          onClick={logout}
          className="text-[13px] text-gray-400 transition-colors hover:text-gray-200"
        >
          Logout
        </button>
      </div>
    </header>
  );
}
