import './bootstrap';
import '../css/app.css';

import React from 'react';
import { createRoot } from 'react-dom/client';
import Login from './Pages/Auth/Login';
import OwnerDashboard from './Pages/Owner/Dashboard';
import BranchList from './Pages/Owner/Branches/List';
import BranchView from './Pages/Owner/Branches/View';
import StaffList from './Pages/Owner/Staff/List';
import StaffEdit from './Pages/Owner/Staff/Edit';
import StaffAdd from './Pages/Owner/Staff/Add';
import StaffView from './Pages/Owner/Staff/View';
import InvestorList from './Pages/Owner/Investors/List';
import InvestorAdd from './Pages/Owner/Investors/Add';
import InvestorEdit from './Pages/Owner/Investors/Edit';
import InvestorView from './Pages/Owner/Investors/View';
import MasterManagement from './Pages/Owner/Masters/index';
import AccountList from './Pages/Owner/Accounts/List';
import ExpenseList from './Pages/Owner/Expenses/List';
import ReportIndex from './Pages/Owner/Reports/Index';
import InventoryIndex from './Pages/Owner/Inventory/Index';
import CollectionsIndex from './Pages/Owner/Collections/Index';
import ReceptionistDashboard from './Pages/Receptionist/Dashboard';
import POS from './Pages/Receptionist/POS';
import ReceptionistReportIndex from './Pages/Receptionist/Reports/Index';
import ComingSoon from './Pages/Receptionist/ComingSoon';



import Layout from './Pages/Owner/Components/Layout';

function MainApp() {
    const [page, setPage] = React.useState({ component: null, loading: true });
    const [user, setUser] = React.useState(window.__APP_DATA__ || null);

    React.useEffect(() => {
        const path = window.location.pathname;
        const data = user;
        const role = data?.role || null;

        // Sync local user state if needed (optional, for consistency with login)
        const checkAuth = async () => {
            let currentData = data;
            
            // If no data in window, fetch it (fallback)
            if (!currentData || !currentData.role) {
                try {
                    const context = path.startsWith('/receptionist') ? 'receptionist' : 'owner';
                    const res = await fetch(`/api/profile?context=${context}`);
                    if (res.ok) {
                        currentData = await res.json();
                        setUser(currentData);
                    } else if (res.status === 401) {
                         currentData = { message: 'Unauthenticated' };
                         setUser(currentData);
                    }
                } catch (err) {
                    console.error('Core init failure:', err);
                    setPage({ component: <Login />, loading: false });
                    return;
                }
            }

            const currentRole = currentData?.role ? currentData.role.toLowerCase() : null;

            // Handle Login Pages
            if (path === '/') {
                if (currentRole === 'owner') return window.location.href = '/owner/dashboard';
                setPage({ component: <Login type="owner" />, loading: false });
                return;
            }

            if (path === '/receptionist') {
                if (currentRole === 'receptionist') return window.location.href = '/receptionist/dashboard';
                setPage({ component: <Login type="receptionist" />, loading: false });
                return;
            }

            // Unauthenticated
            if (currentData.message === 'Unauthenticated' || !currentRole) {
                if (path !== '/') {
                    window.location.href = '/';
                } else {
                    setPage({ component: <Login />, loading: false });
                }
                return;
            }

            // Role-based redirection
            if (currentRole === 'receptionist' && path.startsWith('/owner/')) {
                return window.location.href = '/receptionist/dashboard';
            }
            if (currentRole === 'owner' && path.startsWith('/receptionist/')) {
                return window.location.href = '/owner/dashboard';
            }

            // Route detection
            let component = null;
            if (path === '/owner/dashboard') {
                component = <OwnerDashboard />;
            } else if (path === '/owner/branches') {
                component = <BranchList />;
            } else if (path.startsWith('/owner/branches/')) {
                const id = path.split('/').pop();
                component = <BranchView id={id} />;
            } else if (path.startsWith('/owner/staff/edit/')) {
                const id = path.split('/').pop();
                component = <StaffEdit id={id} />;
            } else if (path === '/owner/staff/add') {
                component = <StaffAdd />;
            } else if (path.startsWith('/owner/staff/view/')) {
                const id = path.split('/').pop();
                component = <StaffView id={id} />;
            } else if (path === '/owner/staff') {
                component = <StaffList />;
            } else if (path.startsWith('/owner/investors/view/')) {
                const id = path.split('/').pop();
                component = <InvestorView id={id} />;
            } else if (path === '/owner/investors') {
                component = <InvestorList />;
            } else if (path === '/owner/investors/add') {
                component = <InvestorAdd />;
            } else if (path.startsWith('/owner/investors/edit/')) {
                const id = path.split('/').pop();
                component = <InvestorEdit id={id} />;
            } else if (path === '/owner/expenses') {
                component = <ExpenseList />;
            } else if (path === '/owner/reports') {
                component = <ReportIndex />;
            } else if (path === '/owner/inventory') {
                component = <InventoryIndex />;
            } else if (path === '/owner/masters') {
                component = <MasterManagement />;
            } else if (path === '/owner/accounts') {
                component = <AccountList />;
            } else if (path === '/owner/collections') {
                component = <CollectionsIndex />;
            } else if (path === '/owner/pos') {
                component = <POS />;
            } else if (path === '/receptionist/dashboard') {
                component = <ReceptionistDashboard />;
            } else if (path === '/receptionist/pos') {
                component = <POS />;
            } else if (path === '/receptionist/collections') {
                component = <CollectionsIndex />;
            } else if (path === '/receptionist/expenses') {
                component = <ExpenseList />;
            } else if (path === '/receptionist/inventory') {
                component = <InventoryIndex />;
            } else if (path === '/receptionist/staff') {
                component = <StaffList />;
            } else if (path === '/receptionist/staff/add') {
                component = <StaffAdd />;
            } else if (path.startsWith('/receptionist/staff/edit/')) {
                const id = path.split('/').pop();
                component = <StaffEdit id={id} />;
            } else if (path.startsWith('/receptionist/staff/view/')) {
                const id = path.split('/').pop();
                component = <StaffView id={id} />;
            } else if (path === '/receptionist/investors') {
                component = <InvestorList />;
            } else if (path === '/receptionist/investors/add') {
                component = <InvestorAdd />;
            } else if (path.startsWith('/receptionist/investors/edit/')) {
                const id = path.split('/').pop();
                component = <InvestorEdit id={id} />;
            } else if (path.startsWith('/receptionist/investors/view/')) {
                const id = path.split('/').pop();
                component = <InvestorView id={id} />;
            } else if (path === '/receptionist/reports') {
                component = <ReportIndex />;
            }

            if (component) {
                setPage({ component, loading: false });
            } else {
                setPage({ component: <div className="p-20 text-center font-black uppercase tracking-widest text-gray-300">404 - Page Not Found</div>, loading: false });
            }
        };

        checkAuth();
    }, []);

    if (page.loading) {
        return <div className="h-screen w-screen flex items-center justify-center bg-gray-50 text-xs font-bold text-gray-400 uppercase tracking-widest animate-pulse">Initializing...</div>;
    }

    if (window.location.pathname === '/' || window.location.pathname === '/receptionist' || !user || !user.role) {
        return page.component;
    }

    return (
        <Layout user={user} role={user?.role}>
            {page.component}
        </Layout>
    );
}

const appEl = document.getElementById('app');
if (appEl) {
    const root = createRoot(appEl);
    root.render(<MainApp />);
}