import { useEffect, useState } from 'react';
import Mark from '../ui/Mark';
import ChatWindow from './ChatWindow';
import { useApp } from '../../store/AppContext';
import { storage } from '../../lib/storage';
import { STRINGS } from './prompts';
import './chat.css';

const QUIZ_EVENT = 'respellion:quiz-state';

/**
 * Global floating launcher. Hidden while a quiz is active (set via
 * the `respellion:quiz-state` window event from Testen.jsx) to protect
 * quiz integrity.
 */
export default function ChatLauncher() {
  const { state } = useApp();
  const user = state.currentUser;
  const isAdmin = user?.role === 'admin';

  const [open, setOpen] = useState(false);
  const [quizActive, setQuizActive] = useState(() => {
    if (!user) return false;
    return storage.get(`quiz:active:${user.id}`, false) === true;
  });

  useEffect(() => {
    if (!user) return;
    setQuizActive(storage.get(`quiz:active:${user.id}`, false) === true);
  }, [user]);

  useEffect(() => {
    const handler = (e) => {
      setQuizActive(Boolean(e?.detail?.active));
      if (e?.detail?.active) setOpen(false);
    };
    window.addEventListener(QUIZ_EVENT, handler);
    return () => window.removeEventListener(QUIZ_EVENT, handler);
  }, []);

  if (!user || quizActive) return null;

  return (
    <>
      {open && (
        <ChatWindow user={user} isAdmin={isAdmin} onClose={() => setOpen(false)} />
      )}
      <button
        type="button"
        className={`r42-fab ${open ? 'open' : ''}`}
        onClick={() => setOpen(o => !o)}
        aria-label={open ? STRINGS.closeAria : STRINGS.openAria}
        aria-expanded={open}
      >
        <Mark state="idle" size={open ? 28 : 36} brace="#ECE9E9" letter="#ECE9E9" />
      </button>
    </>
  );
}
