const { useState, useEffect } = React;

window.App = function() {
    const [profile, setProfile] = useState(null);
    const [view, setView] = useState('login'); 
    const [loading, setLoading] = useState(true);
    
    const [globalUsers, setGlobalUsers] = useState([]);
    const [logs, setLogs] = useState([]);
    const [roles, setRoles] = useState([]);
    const [reminders, setReminders] = useState([]);
    const [vacations, setVacations] = useState([]);
    const [settings, setSettings] = useState({ vacationRate: 2.5 });
    const [actions, setActions] = useState([]);
    const [absences, setAbsences] = useState([]);

    // Estado del Panel Maestro
    const [masterClients, setMasterClients] = useState([]);
    const [activeClientId, setActiveClientId] = useState(window.SHIFT_CONFIG ? window.SHIFT_CONFIG.clientId : 1);

    // Mantener sincronizada la variable global para config.js
    useEffect(() => {
        window.currentActiveClientId = activeClientId;
    }, [activeClientId]);

    useEffect(() => {
        const savedSession = localStorage.getItem('shift_active_session');
        if (savedSession) {
            try {
                const parsed = JSON.parse(savedSession);
                if (parsed && parsed.expiresAt > Date.now() && parsed.profile) {
                    setProfile(parsed.profile);
                    setView(parsed.profile.role === 'admin' || parsed.profile.role === 'propietario' || parsed.profile.role === 'dueño' ? 'admin' : 'dashboard');
                } else {
                    localStorage.removeItem('shift_active_session');
                    setView('login');
                }
            } catch (e) { 
                localStorage.removeItem('shift_active_session');
                setView('login'); 
            }
        } else {
            setView('login');
        }
    }, []);

    const refreshData = async () => {
        if (window.SHIFT_CONFIG && window.SHIFT_CONFIG.isMaster) {
            const resMaster = await window.apiCall('get_master_clients');
            if (resMaster.success) setMasterClients(resMaster.clients);
        }

        const res = await window.apiCall('get_initial_data', {}, activeClientId);
        if (res.success) {
            const mappedUsers = res.data.users.map(u => ({...u, role: u.role_name}));
            setGlobalUsers(mappedUsers);
            setLogs(res.data.logs);
            setRoles(res.data.roles);
            setAbsences(res.data.absences || []);
            setActions(res.data.actions.length > 0 ? res.data.actions : [
                { id: 'almuerzo', label: 'Almuerzo' }, { id: 'break', label: 'Break / Merienda' },
                { id: 'visita_in', label: 'Visita Cliente' }, { id: 'reunion', label: 'Reunión' },
                { id: 'capacitacion', label: 'Capacitación' }, { id: 'gestiones', label: 'Gestiones de Campo' }
            ]);
            setVacations(res.data.vacations);
            setSettings(res.data.settings);
            setReminders(res.data.reminders);

            if (profile) {
                const updated = mappedUsers.find(u => u.id === profile.id);
                if (updated && updated.status === 'baja') {
                    localStorage.removeItem('shift_active_session');
                    setProfile(null);
                    setView('login');
                }
            }
        }
        setLoading(false);
    };

    useEffect(() => {
        refreshData();
        const interval = setInterval(refreshData, 10000);
        return () => clearInterval(interval);
    }, [activeClientId, profile?.id]);

    if (loading) return (
        <div className="h-screen flex items-center justify-center bg-slate-900 text-white font-bold uppercase text-xs tracking-widest animate-pulse">
            Cargando Entorno Shift...
        </div>
    );

    return (
        <div className="min-h-screen bg-slate-50">
            {view === 'login' && (
                <window.LoginView 
                    setView={setView} 
                    setProfile={setProfile} 
                    hasUsers={globalUsers.length > 0} 
                    activeClientId={activeClientId}
                />
            )}
            
            {view === 'dashboard' && profile && (
                <window.UserDashboard 
                    profile={profile} 
                    logs={logs.filter(l => l.userId === profile.id)} 
                    reminders={reminders}
                    vacations={vacations}
                    settings={settings}
                    actions={actions}
                    onLogout={() => { localStorage.removeItem('shift_active_session'); setProfile(null); setView('login'); }} 
                    setView={setView} 
                    allRoles={roles}
                />
            )}

            {view === 'admin' && (profile?.role === 'admin' || profile?.role === 'propietario' || profile?.role === 'dueño') && (
                <window.AdminDashboard 
                    globalUsers={globalUsers} 
                    logs={logs} 
                    roles={roles} 
                    reminders={reminders}
                    vacations={vacations}
                    settings={settings}
                    actions={actions}
                    absences={absences}
                    masterClients={masterClients}
                    activeClientId={activeClientId}
                    setActiveClientId={setActiveClientId}
                    refreshData={refreshData}
                    setView={setView} 
                    onLogout={() => { localStorage.removeItem('shift_active_session'); setProfile(null); setView('login'); }} 
                />
            )}
        </div>
    );
};

// Renderizado directo
const rootElement = document.getElementById('root');
if (rootElement) {
    if (!window._shiftRoot) window._appRoot = ReactDOM.createRoot(rootElement);
    window._appRoot.render(<window.App />);
}