import { useEffect } from 'react';
import { Outlet } from 'react-router-dom';

import { useAuth } from '../context/AuthContext';
import { startConversationKeySync } from '../lib/conversationKeySync';
import { ensureNotificationPermission } from '../lib/osNotify';
import { CallUI } from './CallUI';
import { Sidebar } from './Sidebar';

export function AppShell() {
  const { session, device } = useAuth();
  useEffect(() => {
    // Prompt once per authenticated shell mount. Module-level guard prevents
    // re-asking if the user already responded this session.
    void ensureNotificationPermission();
  }, []);

  useEffect(() => {
    if (!session?.user.id || !device?.id) return;
    return startConversationKeySync(session.user.id, device.id);
  }, [session?.user.id, device?.id]);

  return (
    <div className="relative flex min-h-screen overflow-hidden bg-ink-950 text-neutral-100">
      <ShellBackground />
      <div className="relative z-10 flex min-h-screen w-full">
        <Sidebar />
        <main className="relative flex-1 overflow-hidden">
          <div className="h-screen overflow-y-auto">
            <Outlet />
          </div>
        </main>
      </div>
      <CallUI />
    </div>
  );
}

// Calmer than the auth-screen background — full-bleed grid + 2 large blobs.
// No animation here so message lists stay readable.
function ShellBackground() {
  return (
    <div aria-hidden="true" className="pointer-events-none absolute inset-0">
      <div className="bg-grid absolute inset-0 opacity-[0.18]" />
      <div className="absolute -left-32 top-1/4 h-[420px] w-[420px] rounded-full bg-brand-500/20 blur-3xl" />
      <div className="absolute -right-32 bottom-0 h-[420px] w-[420px] rounded-full bg-fuchsia-500/10 blur-3xl" />
      <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,transparent_45%,rgba(5,5,7,0.6)_100%)]" />
    </div>
  );
}
