import React, { useState, useEffect, useRef } from 'react';
import './botaoacessibilidade.css'; // Importando o CSS
import { setTheme } from '../assets/static/js/components/dark';

// Componente para o Guia de Leitura
function GuiaDeLeitura() {
  const topMaskRef = useRef(null);
  const bottomMaskRef = useRef(null);
  useEffect(() => {
    const handleMouseMove = (e) => {
      if (topMaskRef.current && bottomMaskRef.current) {
        const windowHeight = 40;
        const offset = windowHeight / 2;
        topMaskRef.current.style.height = `${e.clientY - offset}px`;
        bottomMaskRef.current.style.top = `${e.clientY + offset}px`;
      }
    };
    window.addEventListener('mousemove', handleMouseMove);
    return () => { window.removeEventListener('mousemove', handleMouseMove); };
  }, []);

  return (
    <>
      <div ref={topMaskRef} className="reading-guide-mask reading-guide-top"></div>
      <div ref={bottomMaskRef} className="reading-guide-mask reading-guide-bottom"></div>
    </>
  );
}

// --- COMPONENTE PRINCIPAL ---
function BotaoAcessibilidade() {
  // Estados de todas as funcionalidades
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [isReadOnHoverActive, setIsReadOnHoverActive] = useState(false);
  const [fontSize, setFontSize] = useState(1);
  const [isBigCursor, setIsBigCursor] = useState(false);
  const [colorblindMode, setColorblindMode] = useState('none');
  const [isReadingGuide, setIsReadingGuide] = useState(false);
  const [isDyslexiaFont, setIsDyslexiaFont] = useState(false);
  const [isLetterSpacing, setIsLetterSpacing] = useState(false);
  const [isLineHeight, setIsLineHeight] = useState(false);
  const lastSpokenTargetRef = useRef(null);

  // Efeitos para aplicar as funcionalidades na página
  useEffect(() => { setTheme(isDarkMode ? "dark" : "light", true); }, [isDarkMode]);
  useEffect(() => {
    const originalFontSize = document.documentElement.style.fontSize;
    document.documentElement.style.fontSize = `${fontSize * 100}%`;
    return () => { document.documentElement.style.fontSize = originalFontSize; };
  }, [fontSize]);
  useEffect(() => {
    document.body.classList.toggle('big-cursor-active', isBigCursor);
    return () => { document.body.classList.remove('big-cursor-active'); };
  }, [isBigCursor]);
  useEffect(() => {
    document.body.classList.toggle('dyslexia-font-active', isDyslexiaFont);
    return () => { document.body.classList.remove('dyslexia-font-active'); };
  }, [isDyslexiaFont]);
  useEffect(() => {
    document.body.classList.toggle('letter-spacing-active', isLetterSpacing);
    return () => { document.body.classList.remove('letter-spacing-active'); };
  }, [isLetterSpacing]);
  useEffect(() => {
    document.body.classList.toggle('line-height-active', isLineHeight);
    return () => { document.body.classList.remove('line-height-active'); };
  }, [isLineHeight]);
  useEffect(() => {
    const classesToRemove = ['colorblind-protanopia', 'colorblind-deuteranopia', 'colorblind-tritanopia', 'colorblind-achromatopsia'];
    document.documentElement.classList.remove(...classesToRemove);
    if (colorblindMode !== 'none') {
      document.documentElement.classList.add(`colorblind-${colorblindMode}`);
    }
  }, [colorblindMode]);
// VERSÃO DEFINITIVA - Muito mais abrangente
useEffect(() => {
  if (!isReadOnHoverActive) {
    window.speechSynthesis.cancel();
    return;
  }

  const handleMouseOver = (event) => {
    // Seletor muito mais completo, incluindo DIVs, SPANs, células de tabela, imagens e papéis de acessibilidade
    const selector = 'P, H1, H2, H3, H4, H5, H6, BUTTON, A, LI, LABEL, SPAN, TD, TH, DT, DD, FIGCAPTION, [role="button"], [role="link"], [role="menuitem"], IMG';
    const relevantElement = event.target.closest(selector);

    if (relevantElement && relevantElement !== lastSpokenTargetRef.current) {
      let textToSpeak = '';

      // Lógica especial para IMAGENS: lê o atributo "alt"
      if (relevantElement.tagName === 'IMG') {
        textToSpeak = relevantElement.getAttribute('alt');
      } 
      // Lógica para outros elementos: prioriza aria-label, depois title, e por último o texto interno
      else {
        textToSpeak = 
          relevantElement.getAttribute('aria-label') || 
          relevantElement.getAttribute('title') ||
          relevantElement.innerText;
      }
      
      if (textToSpeak) {
        textToSpeak = textToSpeak.trim();

        // Evita ler elementos que só têm elementos filhos, mas nenhum texto próprio direto
        const hasTextAndNoChildren = textToSpeak.length > 0 && relevantElement.children.length === 0;
        const hasTextAndIsBlock = textToSpeak.length > 0 && !['SPAN', 'A', 'STRONG', 'EM'].includes(relevantElement.tagName);

        if (hasTextAndNoChildren || hasTextAndIsBlock) {
          lastSpokenTargetRef.current = relevantElement;
          window.speechSynthesis.cancel();
          const utterance = new SpeechSynthesisUtterance(textToSpeak);
          utterance.lang = 'pt-BR';
          window.speechSynthesis.speak(utterance);
        }
      }
    }
  };

  document.body.addEventListener('mouseover', handleMouseOver);
  return () => {
    document.body.removeEventListener('mouseover', handleMouseOver);
    window.speechSynthesis.cancel();
  };
}, [isReadOnHoverActive]);

  // Funções de controle
  const handleIncreaseFontSize = () => setFontSize(prevSize => Math.min(prevSize + 0.1, 1.6));
  const handleDecreaseFontSize = () => setFontSize(prevSize => Math.max(prevSize - 0.1, 0.8));
  const handleVlibrasClick = () => {
    const originalVlibrasButton = document.querySelector('[vw-access-button]');
    if (originalVlibrasButton) {
      originalVlibrasButton.click();
    } else {
      alert("O Vlibras não pôde ser ativado.");
    }
    setIsMenuOpen(false);
  };

  return (
    <div className={`container-acessibilidade ${isDarkMode ? 'dark-mode' : ''}`}>
      {isReadingGuide && <GuiaDeLeitura />}
      <svg style={{ position: 'absolute', height: 0, width: 0 }}>
        <defs>
          <filter id="protanopia"><feColorMatrix in="SourceGraphic" type="matrix" values="0.567, 0.433, 0, 0, 0, 0.558, 0.442, 0, 0, 0, 0, 0.242, 0.758, 0, 0, 0, 0, 0, 1, 0"/></filter>
          <filter id="deuteranopia"><feColorMatrix in="SourceGraphic" type="matrix" values="0.625, 0.375, 0, 0, 0, 0.7, 0.3, 0, 0, 0, 0, 0.3, 0.7, 0, 0, 0, 0, 0, 1, 0"/></filter>
          <filter id="tritanopia"><feColorMatrix in="SourceGraphic" type="matrix" values="0.95, 0.05, 0, 0, 0, 0, 0.433, 0.567, 0, 0, 0, 0.475, 0.525, 0, 0, 0, 0, 0, 1, 0"/></filter>
          <filter id="achromatopsia"><feColorMatrix in="SourceGraphic" type="matrix" values="0.299, 0.587, 0.114, 0, 0, 0.299, 0.587, 0.114, 0, 0, 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 1, 0"/></filter>
        </defs>
      </svg>
      <div className={`menu-opcoes ${isMenuOpen ? 'aberto' : ''}`}>
        <div className="menu-titulo">Acessibilidade</div>
        
        <div className="font-size-control">
          <div className="font-size-label">
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="4 7 4 4 20 4 20 7"></polyline><line x1="9" y1="20" x2="15" y2="20"></line><line x1="12" y1="4" x2="12" y2="20"></line></svg>
            Tamanho da Fonte
          </div>
          <div className="font-size-buttons">
            <button onClick={handleDecreaseFontSize} title="Diminuir Fonte">A-</button>
            <span>{`${Math.round(fontSize * 100)}%`}</span>
            <button onClick={handleIncreaseFontSize} title="Aumentar Fonte">A+</button>
          </div>
        </div>
        
        <div className="acessibilidade-select-control">
           <label htmlFor="colorblind-select">
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>
            Modo Daltonismo
           </label>
           <select id="colorblind-select" value={colorblindMode} onChange={(e) => setColorblindMode(e.target.value)}>
              <option value="none">Desativado</option>
              <option value="protanopia">Protanopia</option>
              <option value="deuteranopia">Deuteranopia</option>
              <option value="tritanopia">Tritanopia</option>
              <option value="achromatopsia">Monocromático</option>
           </select>
        </div>

        <label htmlFor="darkModeCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
          Modo Escuro
          <input type="checkbox" id="darkModeCheckbox" checked={isDarkMode} onChange={() => setIsDarkMode(!isDarkMode)} />
        </label>
        
        <label htmlFor="dyslexiaFontCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
          Fonte para Dislexia
          <input type="checkbox" id="dyslexiaFontCheckbox" checked={isDyslexiaFont} onChange={() => setIsDyslexiaFont(!isDyslexiaFont)} />
        </label>
        
        <label htmlFor="letterSpacingCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
          Espaçamento entre Letras
          <input type="checkbox" id="letterSpacingCheckbox" checked={isLetterSpacing} onChange={() => setIsLetterSpacing(!isLetterSpacing)} />
        </label>

        <label htmlFor="lineHeightCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
          Altura da Linha
          <input type="checkbox" id="lineHeightCheckbox" checked={isLineHeight} onChange={() => setIsLineHeight(!isLineHeight)} />
        </label>
        
        <label htmlFor="readingGuideCheckbox" className="checkbox-label-button">
           <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>
           Guia de Leitura
           <input type="checkbox" id="readingGuideCheckbox" checked={isReadingGuide} onChange={() => setIsReadingGuide(!isReadingGuide)} />
        </label>
        
        <label htmlFor="bigCursorCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"></path><path d="M13 13l6 6"></path></svg>
          Cursor Grande
          <input type="checkbox" id="bigCursorCheckbox" checked={isBigCursor} onChange={() => setIsBigCursor(!isBigCursor)} />
        </label>

        <label htmlFor="readOnHoverCheckbox" className="checkbox-label-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"></path><path d="M13 13l6 6"></path></svg>
          Leitura instantânea
          <input type="checkbox" id="readOnHoverCheckbox" checked={isReadOnHoverActive} onChange={() => setIsReadOnHoverActive(!isReadOnHoverActive)} />
        </label>
        
        {/* ADICIONADO DE VOLTA: Botão para LIBRAS */}
        <button onClick={handleVlibrasClick}>
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0" /><path d="M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v2" /><path d="M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8" /><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h2.3" /></svg>
            Traduzir para LIBRAS
        </button>
      </div>

      <button className="botao-flutuante-acessibilidade" onClick={() => setIsMenuOpen(!isMenuOpen)} title="Menu de Acessibilidade">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="30" height="30" fill="white">
          <path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z" />
        </svg>
      </button>
    </div>
  );
}
export default BotaoAcessibilidade;