'use client';

/**
 * Предупреждение гостям: история теряется при закрытии
 * docs/architecture: 05-gaps-and-best-practices.md §8
 */

import { useChat } from '@/lib/hooks/useChat';
import { useEffect, useState } from 'react';
import Link from 'next/link';

export default function GuestWarningBanner() {
  const { messages } = useChat();
  const [isGuest, setIsGuest] = useState(false);

  useEffect(() => {
    const token =
      typeof window !== 'undefined'
        ? localStorage.getItem('auth_token') ?? localStorage.getItem('access_token')
        : null;
    setIsGuest(!token);
  }, []);

  useEffect(() => {
    if (!isGuest || messages.length === 0) return;

    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      e.preventDefault();
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [isGuest, messages.length]);

  if (!isGuest || messages.length === 0) return null;

  return (
    <div
      role="alert"
      className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 max-w-lg w-[calc(100%-2rem)]"
    >
      <div className="rounded-xl bg-amber-500/95 dark:bg-amber-600/95 text-amber-950 dark:text-amber-50 px-4 py-3 shadow-lg flex flex-col sm:flex-row items-center justify-between gap-2">
        <span className="text-sm font-medium">
          Your chat history will be lost when you close the browser.
        </span>
        <Link
          href="/profile"
          className="text-sm font-semibold underline underline-offset-2 hover:no-underline whitespace-nowrap"
        >
          Save to account →
        </Link>
      </div>
    </div>
  );
}
