/**
 * @fileoverview React component for App.jsx
 * 
 * @module App
 */

import { lazy, Suspense, useEffect, useState } from "react";
import { HashRouter as Router, Routes, Route, useLocation } from "react-router-dom";
import "./App.css";
import HomePage from "./pages/HomePage/HomePage";
import LabPython from "./pages/LabPython/LabPython";
import ScrollToTop from "./components/ScrollToTop";
import { getAnalytics, usePageTracking } from "./services/analytics";
import { initializeAnalytics, analyticsConfig } from "./services/analytics";

// Inline CookieBanner para evitar bloqueio do Brave
function CookieBanner() {
  const [visible, setVisible] = useState(false);
  const enableBanner = import.meta.env.VITE_ENABLE_CONSENT_BANNER === 'true';

  useEffect(() => {
    if (!enableBanner) return;

    try {
      const stored = localStorage.getItem('decoda_consent');
      if (!stored) {
        setVisible(true);
      }
    } catch (e) {
      console.error('Consent check failed:', e);
    }
  }, [enableBanner]);

  const handleAccept = () => {
    try {
      localStorage.setItem('decoda_consent', JSON.stringify({
        version: '1',
        accepted: true,
        timestamp: new Date().toISOString(),
      }));
      getAnalytics()._setConsentGrantedInternal(true);
      setVisible(false);
    } catch (e) {
      console.error('Failed to accept consent:', e);
    }
  };

  const handleReject = () => {
    try {
      localStorage.setItem('decoda_consent', JSON.stringify({
        version: '1',
        accepted: false,
        timestamp: new Date().toISOString(),
      }));
      getAnalytics()._setConsentGrantedInternal(false);
      setVisible(false);
    } catch (e) {
      console.error('Failed to reject consent:', e);
    }
  };

  if (!visible || !enableBanner) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 z-50 p-4 md:p-6" role="dialog" aria-label="Consentimento de cookies">
      <div className="mx-auto max-w-4xl">
        <div className="bg-white rounded-2xl shadow-2xl overflow-hidden border border-gray-200">
          <div className="h-1 bg-gradient-to-r from-red-600 to-pink-600"></div>
          <div className="p-6 md:p-8">
            <div className="flex flex-col md:flex-row gap-6 md:gap-8 items-start">
              <div className="flex-1 min-w-0">
                <h2 className="font-title font-bold text-xl md:text-2xl text-gray-900 mb-2">
                  Sua privacidade é importante
                </h2>
                <p className="font-sans text-sm md:text-base text-gray-700 leading-relaxed">
                  Utilizamos dados sobre como você usa a plataforma para melhorar a experiência educacional
                  e entender quais recursos são mais úteis.{' '}
                  <a
                    href="#/privacy-policy"
                    className="text-red-600 hover:text-red-700 font-semibold underline transition-colors"
                  >
                    Saiba mais
                  </a>
                </p>
              </div>
              <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto flex-shrink-0">
                <button
                  onClick={handleReject}
                  className="px-6 py-2.5 rounded-xl font-sans font-semibold text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 transition-all duration-200 border border-gray-300"
                  aria-label="Rejeitar"
                >
                  Rejeitar
                </button>
                <button
                  onClick={handleAccept}
                  className="px-6 py-2.5 rounded-xl font-sans font-semibold text-sm text-white bg-gradient-to-r from-red-600 to-pink-600 hover:shadow-lg hover:scale-105 transition-all duration-200 transform"
                  aria-label="Aceitar"
                >
                  Aceitar
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

const Playground = lazy(() => import("./pages/Playground/Playground"));
const About = lazy(() => import("./pages/About/About"));
const Faq = lazy(() => import("./pages/Faq/Faq"));
const Atividades = lazy(() => import("./pages/Atividades/Atividades"));
const Educadores = lazy(() => import("./pages/Educadores/Educadores"));
const Iniciativas = lazy(() => import("./pages/Iniciativas/Iniciativas"));
const IniciativaDetalhe = lazy(() => import("./pages/Iniciativas/IniciativaDetalhe"));
const PrimeirosPassos = lazy(() => import("./pages/PrimeirosPassos/PrimeirosPassos"));
const CategoriaLetramentoView = lazy(() => import("./pages/PrimeirosPassos/CategoriaLetramentoView"));
const PrivacyPolicy = lazy(() =>
  import("./pages/PrivacyPolicy/PrivacyPolicy").then(m => ({
    default: m.PrivacyPolicy
  }))
);

//Atividades
const AspiradorGame = lazy(() => import("./atividades/programacao/aspirador/AspiradorGame"));
const AutomatoGame = lazy(() => import("./atividades/programacao/automato/AutomatoGame"));
const SemaforoGame = lazy(() => import("./atividades/programacao/semaforo/SemaforoGame"));
const MoleMashGame = lazy(() => import("./atividades/programacao/mole-mash/MoleMash"));
const OrdenacaoGame = lazy(() => import("./atividades/programacao/ordenacao/OrdenacaoGame"));
const PuzzleGame = lazy(() => import("./atividades/programacao/puzzle/PuzzleGame"));
const TurtleGame = lazy(() => import("./atividades/programacao/turtle/TurtleGame"));
const CriptoGame = lazy(() => import("./atividades/programacao/cripto/CriptoGame"));

const LoadingFallback = () => (
  <div
    className="primary-gradient text-white"
    style={{
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      height: "100vh",
      fontSize: "1.5rem",
      fontWeight: "600",
    }}
  >
    <div style={{ textAlign: "center" }}>
      <div
        style={{
          width: "50px",
          height: "50px",
          border: "4px solid rgba(255,255,255,0.3)",
          borderTop: "4px solid white",
          borderRadius: "50%",
          animation: "spin 1s linear infinite",
          margin: "0 auto 20px",
        }}
      ></div>
      Carregando...
    </div>
  </div>
);

// Separated so we can call useLocation (requires being inside Router)
function AppRoutes({ analyticsReady = false }) {
  const location = useLocation();
  // When navigating to a letramento category, the caller passes
  // { state: { backgroundLocation: location } } so the previous page
  // keeps rendering behind the modal overlay.
  const backgroundLocation = location.state?.backgroundLocation;

  usePageTracking(analyticsReady);

  return (
    <>
      <ScrollToTop />
      {/* Main routes — rendered at the background location when a modal is open */}
      <Routes location={backgroundLocation ?? location}>
        <Route path="/" element={<HomePage />} />
        <Route path="/playground" element={<Playground />} />
        <Route path="/laboratorio" element={<Playground />} />
        <Route path="/laboratorio-python" element={<LabPython />} />
        <Route path="/sobre" element={<About />} />
        <Route path="/faq" element={<Faq />} />
        <Route path="/privacy-policy" element={<PrivacyPolicy />} />
        <Route path="/atividades" element={<Atividades />} />
        <Route path="/educadores" element={<Educadores />} />
        <Route path="/iniciativas" element={<Iniciativas />} />
        <Route path="/iniciativas/:id" element={<IniciativaDetalhe />} />
        <Route path="/primeiros-passos" element={<PrimeirosPassos />} />
        {/* Fallback: direct URL access without backgroundLocation */}
        <Route path="/primeiros-passos/:categoria" element={<CategoriaLetramentoView />} />
        <Route path="/atividades/programacao/aspirador" element={<AspiradorGame />} />
        <Route path="/atividades/programacao/automato" element={<AutomatoGame />} />
        <Route path="/atividades/programacao/cripto" element={<CriptoGame />} />
        <Route path="/atividades/programacao/ordenacao" element={<OrdenacaoGame />} />
        <Route path="/atividades/programacao/puzzle" element={<PuzzleGame />} />
        <Route path="/atividades/programacao/semaforo" element={<SemaforoGame />} />
        <Route path="/atividades/programacao/molemash" element={<MoleMashGame />} />
        <Route path="/atividades/programacao/turtle" element={<TurtleGame />} />
      </Routes>

      {/* Modal overlay routes — rendered on top of the background page */}
      {backgroundLocation && (
        <Routes>
          <Route path="/primeiros-passos/:categoria" element={<CategoriaLetramentoView />} />
        </Routes>
      )}
    </>
  );
}

export default function App() {
  const [analyticsReady, setAnalyticsReady] = useState(false);

  useEffect(() => {
    initializeAnalytics({
      providerType: analyticsConfig.providerType,
      measurementId: analyticsConfig.measurementId,
      hasConsent: true,
      debugMode: analyticsConfig.debugMode,
    });

    setAnalyticsReady(true);
  }, []);

  return (
    <Router>
      <Suspense fallback={<LoadingFallback />}>
        <AppRoutes analyticsReady={analyticsReady} />
      </Suspense>
      <CookieBanner />
    </Router>
  );
}

// Note: many imports are used only via lazy() or in route elements.
// If ESLint still reports unused vars here, we prefer keeping changes minimal
// and addressing remaining warnings in targeted files.
