import React, { useState, useEffect } from 'react';
import App from './App.tsx';
import AdminApp from './AdminApp.tsx';
import { Globe, Shield, RefreshCw } from 'lucide-react';

export default function Root() {
  const [simulatedDomain, setSimulatedDomain] = useState<'student' | 'admin'>(() => {
    // 1. Check hostname
    if (window.location.hostname.includes('admin')) {
      return 'admin';
    }
    // 2. Check path
    if (window.location.pathname.startsWith('/admin')) {
      return 'admin';
    }
    // 3. Fallback to localStorage
    const saved = localStorage.getItem('microtecflix_simulated_domain');
    return saved === 'admin' ? 'admin' : 'student';
  });

  const handleToggleDomain = (domain: 'student' | 'admin') => {
    localStorage.setItem('microtecflix_simulated_domain', domain);
    setSimulatedDomain(domain);
    // Reload to clear state and re-route properly
    window.location.reload();
  };

  const isAdmin = simulatedDomain === 'admin';

  return (
    <div className="relative min-h-screen">
      {isAdmin ? <AdminApp /> : <App />}

      {/* FLOATING SIMULATED DOMAIN SWITCHER (SANDBOX / DEVELOPMENT ONLY) */}
      <div className="fixed bottom-4 right-4 z-[9999] flex flex-col items-end gap-1 font-sans">
        <div className="bg-black/80 border border-white/10 backdrop-blur-md rounded-xl p-2.5 shadow-2xl flex items-center space-x-3 text-xs">
          <div className="flex flex-col">
            <span className="text-[10px] text-zinc-500 font-extrabold uppercase tracking-wider leading-none">
              Ambiente de Desenvolvimento
            </span>
            <span className="text-white font-bold tracking-tight mt-0.5 flex items-center gap-1">
              <Globe className="w-3.5 h-3.5 text-[#E50914] animate-spin" style={{ animationDuration: '6s' }} />
              {isAdmin ? 'admin-estudo.microtecinformaticacurso.com.br' : 'estudo.microtecinformaticacurso.com.br'}
            </span>
          </div>

          <div className="flex bg-zinc-900 p-0.5 rounded-lg border border-white/5">
            <button
              onClick={() => handleToggleDomain('student')}
              className={`px-2 py-1 rounded-md font-bold text-[10px] uppercase tracking-wider transition-all cursor-pointer ${!isAdmin ? 'bg-[#E50914] text-white' : 'text-zinc-500 hover:text-zinc-300'}`}
            >
              Aluno
            </button>
            <button
              onClick={() => handleToggleDomain('admin')}
              className={`px-2 py-1 rounded-md font-bold text-[10px] uppercase tracking-wider transition-all cursor-pointer ${isAdmin ? 'bg-[#E50914] text-white' : 'text-zinc-500 hover:text-zinc-300'}`}
            >
              Admin
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
