import { useState, useEffect } from 'react';
import type { ReactNode } from 'react';
import Sidebar from './Sidebar';
import MobileNav from './MobileNav';

interface Props {
  children: ReactNode;
  userName?: string;
  botName?: string;
}

export default function DashboardLayout({ children, userName, botName = 'Bloby' }: Props) {
  const [status, setStatus] = useState<'healthy' | 'restarting'>('healthy');

  useEffect(() => {
    const check = () => {
      fetch('/app/api/health', { signal: AbortSignal.timeout(3000) })
        .then((r) => {
          setStatus(r.ok ? 'healthy' : 'restarting');
        })
        .catch((err) => {
          setStatus('restarting');
        });
    };
    check();
    const id = setInterval(check, 10_000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="flex h-dvh flex-col">
      {/* Mobile header */}
      <header className="flex items-center justify-between px-4 py-3 md:hidden">
        <MobileNav userName={userName} botName={botName} backendStatus={status} />
        <div className="flex items-center gap-2">
          <img src="/morphy.png" alt={botName} className="h-6 w-auto" />
          <span className="font-semibold text-base">{botName}</span>
        </div>
        <div className="w-10" />
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* Desktop sidebar — floating card with shiny border */}
        <div id="tour-sidebar" className="hidden md:flex shrink-0 pl-3 pt-3 pb-3">
          <div className="relative rounded-3xl overflow-hidden h-full">
            {/* Shiny border highlight */}
            <div className="absolute inset-0 rounded-3xl bg-gradient-to-b from-white/[0.12] via-white/[0.04] to-transparent pointer-events-none" />
            <div className="relative rounded-3xl bg-[#1A1A1A] m-px h-full">
              <Sidebar userName={userName} botName={botName} backendStatus={status} />
            </div>
          </div>
        </div>

        {/* Main content + footer */}
        <div className="flex flex-1 flex-col overflow-hidden">
          <main id="tour-dashboard" className="flex-1 overflow-y-auto">{children}</main>
        </div>
      </div>
    </div>
  );
}
