import { useState, useEffect } from 'react';
import { Link, Outlet, useLocation } from 'react-router-dom';
import AppNavigation from './Sidebar';
import { api } from '@/api';
import PageTransition from '@/components/PageTransition';
import { FormatSync } from '@/components/FormatSync';

function SimplefinBadge() {
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    api.simplefinStatus()
      .then(d => setEnabled(!!(d as { enabled?: boolean }).enabled))
      .catch(err => console.error('[Layout] simplefinStatus check failed', err));
  }, []);

  if (!enabled) return null;

  return (
    <span className="inline-flex items-center gap-1.5">
      <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" aria-hidden="true" />
      SimpleFIN
    </span>
  );
}

export default function Layout({ mainContentId }: { mainContentId?: string }) {
  const location = useLocation();

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,oklch(var(--primary)/0.06),transparent_30rem),linear-gradient(180deg,oklch(var(--background)),oklch(var(--muted)/0.12))] text-foreground"
      role="main"
      aria-labelledby={mainContentId}
    >
      <AppNavigation mainContentId={mainContentId} />

      <main className="w-full">
        <div className="mx-auto w-full max-w-[1500px] px-4 py-6 sm:px-6 lg:px-8 lg:py-8"
          id={mainContentId}
        >
          <PageTransition routeKey={location.pathname}>
            <FormatSync>
              <Outlet />
            </FormatSync>
          </PageTransition>
        </div>
      </main>
      <footer className="mx-auto flex w-full max-w-[1500px] flex-wrap items-center justify-center gap-x-4 gap-y-2 px-4 pb-6 text-xs text-muted-foreground sm:px-6 lg:px-8"
        aria-label="Footer"
      >
        <Link to="/about" className="underline-offset-4 hover:text-foreground hover:underline">About</Link>
        <Link to="/release-notes" className="underline-offset-4 hover:text-foreground hover:underline">Release Notes</Link>
        <SimplefinBadge />
      </footer>
    </div>
  );
}
