import { Head, router } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import type { PropsWithChildren } from 'react';
import { BrandMark } from '@/Components/Brand/BrandMark';
import { FlashToast } from '@/Components/UI/FlashToast';
import { DashboardSidebar } from './DashboardSidebar';
import { Topbar } from './Topbar';

type Props = PropsWithChildren<{
  title: string;
}>;

function sendHeartbeat() {
  const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
  fetch('/heartbeat', {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json' },
    credentials: 'same-origin',
  }).catch(() => {});
}

export function AppLayout({ title, children }: Props) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    sendHeartbeat();
    intervalRef.current = setInterval(sendHeartbeat, 120_000);
    return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
  }, []);

  useEffect(() => {
    const stop = router.on('navigate', () => setSidebarOpen(false));
    return stop;
  }, []);

  useEffect(() => {
    document.body.style.overflow = sidebarOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [sidebarOpen]);

  return (
    <div className="dashboard-shell">
      <Head title={title}>
        <meta name="description" content={`دانشیار من | ${title}؛ پنل فارسی اتوماسیون هوشمند مدارس`} />
      </Head>

      {sidebarOpen && (
        <div className="sidebar-overlay active" role="button" tabIndex={-1} aria-label="بستن منو" onClick={() => setSidebarOpen(false)} onKeyDown={() => setSidebarOpen(false)} />
      )}

      <aside className={`dashboard-sidebar${sidebarOpen ? ' sidebar-open' : ''}`}>
        <div className="sidebar-header">
          <BrandMark href="/dashboard" />
          <button className="sidebar-close-btn" type="button" aria-label="بستن منو" onClick={() => setSidebarOpen(false)}>
            <i className="bi bi-x-lg" />
          </button>
        </div>
        <DashboardSidebar />
      </aside>

      <main className="dashboard-main">
        <Topbar title={title} onMenuToggle={() => setSidebarOpen(true)} />
        {children}
      </main>

      <FlashToast />
    </div>
  );
}
