// Main app — router across landing, login, admin, client portal
const { useState: useStateApp, useEffect: useEffectApp } = React;

function getCrumb(view, role) {
  const adminCrumbs = {
    dashboard: ['Dashboard', 'Panel QA'],
    clients: ['Clientes', 'Gestión'],
    projects: ['Proyectos', 'Gestión'],
    hours: ['Registro de horas', 'Trabajo'],
    bugs: ['Incidencias', 'Calidad'],
    reports: ['Reportes y evidencia', 'Documentos'],
    quincena: ['Resumen quincenal', 'Facturación'],
    profile: ['Perfil y ajustes', 'Cuenta'],
    'project-detail': ['Detalle de proyecto', 'Proyectos'],
  };
  const clientCrumbs = {
    'client-overview': ['Resumen', 'Portal cliente'],
    'client-projects': ['Mis proyectos', 'Portal cliente'],
    'client-bugs': ['Incidencias', 'Calidad'],
    'client-reports': ['Reportes', 'Documentos'],
    'client-hours': ['Horas y costo', 'Periodo'],
    'client-project-detail': ['Detalle de proyecto', 'Mis proyectos'],
    profile: ['Perfil', 'Cuenta'],
  };
  const map = role === 'admin' ? adminCrumbs : clientCrumbs;
  return map[view] || ['', ''];
}

function App() {
  const isQaPanel = window.location.hostname === 'qa.bugzero.mx';
  const [route, setRoute] = useStateApp({ kind: isQaPanel ? 'login' : 'landing' });
  const [adminView, setAdminView] = useStateApp('dashboard');
  const [clientView, setClientView] = useStateApp('client-overview');
  const [openProjectId, setOpenProjectId] = useStateApp(null);
  const [loading, setLoading] = useStateApp(true);

  // Check existing session on mount
  useEffectApp(() => {
    async function init() {
      if (BugzeroAPI.isAuthenticated()) {
        try {
          await refreshData();
          const user = BugzeroAPI.getUser();
          if (user?.role === 'admin') setRoute({ kind: 'admin' });
          else setRoute({ kind: 'client' });
        } catch (e) {
          BugzeroAPI.clearSession();
        }
      } else if (isQaPanel) {
        setRoute({ kind: 'login' });
      }
      setLoading(false);
    }
    init();
  }, []);

  // Hash-based simple routing for quick navigation
  useEffectApp(() => {
    const apply = () => {
      const raw = window.location.hash.slice(1);
      const [h] = raw.split('?');
      if (h === 'login') setRoute({ kind: 'login' });
      else if (h === 'reset-password') setRoute({ kind: 'login', resetToken: new URLSearchParams(raw.includes('?') ? raw.slice(raw.indexOf('?')) : '').get('token') });
      else if (h === 'admin') setRoute({ kind: 'admin' });
      else if (h === 'client') setRoute({ kind: 'client' });
      else if (!h || h === 'landing') setRoute({ kind: isQaPanel ? 'login' : 'landing' });
    };
    apply();
    window.addEventListener('hashchange', apply);
    return () => window.removeEventListener('hashchange', apply);
  }, []);

  const goto = (kind, hash) => {
    setRoute({ kind });
    window.location.hash = hash || kind;
  };

  const handleLogout = async () => {
    await BugzeroAPI.auth.logout();
    setAdminView('dashboard');
    setClientView('client-overview');
    setOpenProjectId(null);
    goto('landing');
  };

  if (loading) {
    return (
      <div style={{display:'flex',alignItems:'center',justifyContent:'center',height:'100vh',background:'var(--bg)'}}>
        <div style={{textAlign:'center'}}>
          <div className="brand-mark" style={{margin:'0 auto 16px',width:40,height:40}}/>
          <div style={{fontSize:14,color:'var(--text-2)'}}>Cargando estación de mando…</div>
        </div>
      </div>
    );
  }

  // -------- Landing
  if (route.kind === 'landing') {
    return <Landing onLogin={() => goto('login')}/>;
  }

  // -------- Login
  if (route.kind === 'login') {
    return (
      <Login
        resetToken={route.resetToken || null}
        onAdmin={() => { refreshData().then(() => goto('admin')); }}
        onClient={() => { refreshData().then(() => goto('client')); }}
        onBack={() => goto('landing')}
      />
    );
  }

  // -------- Admin app
  if (route.kind === 'admin') {
    const isDetail = adminView === 'project-detail';
    const [title, crumb] = getCrumb(isDetail ? 'project-detail' : adminView, 'admin');
    const handleNav = (id) => {
      setAdminView(id);
      setOpenProjectId(null);
    };
    return (
      <div className="app-shell">
        <Sidebar active={adminView} onNav={handleNav} role="admin" onLogout={handleLogout}/>
        <div className="main">
          <Topbar title={title} crumb={crumb}>
            <button className="btn btn-sm"><Icon.Sparkles width="13" height="13"/> Novedades</button>
            <button className="btn btn-sm" onClick={() => goto('client')}><Icon.External width="13" height="13"/> Ver portal cliente</button>
          </Topbar>
          {adminView === 'dashboard' && <AdminDashboard onNav={handleNav} onOpenProject={(id)=>{setOpenProjectId(id); setAdminView('project-detail');}}/>}
          {adminView === 'clients' && <AdminClients onOpenClient={(id)=>{setOpenProjectId(id); setAdminView('project-detail');}}/>}
          {adminView === 'projects' && <AdminProjects onOpenProject={(id)=>{setOpenProjectId(id); setAdminView('project-detail');}}/>}
          {adminView === 'hours' && <AdminHours/>}
          {adminView === 'bugs' && <AdminBugs/>}
          {adminView === 'reports' && <AdminReports/>}
          {adminView === 'quincena' && <AdminQuincena/>}
          {adminView === 'profile' && <AdminProfile/>}
          {adminView === 'project-detail' && <ProjectDetail projectId={openProjectId} onBack={()=>setAdminView('projects')}/>}
        </div>
      </div>
    );
  }

  // -------- Client portal
  if (route.kind === 'client') {
    const isDetail = clientView === 'client-project-detail';
    const [title, crumb] = getCrumb(isDetail ? 'client-project-detail' : clientView, 'client');
    const handleNav = (id) => { setClientView(id); setOpenProjectId(null); };
    return (
      <div className="app-shell">
        <Sidebar active={clientView} onNav={handleNav} role="client" onLogout={handleLogout}/>
        <div className="main">
          <Topbar title={title} crumb={crumb}>
            <span className="badge accent"><span className="dot"/>Cierre en 1 día</span>
          </Topbar>
          {clientView === 'client-overview' && <ClientOverview onNav={handleNav} onOpenProject={(id)=>{setOpenProjectId(id); setClientView('client-project-detail');}}/>}
          {clientView === 'client-projects' && <ClientProjects onOpenProject={(id)=>{setOpenProjectId(id); setClientView('client-project-detail');}}/>}
          {clientView === 'client-bugs' && <ClientBugs/>}
          {clientView === 'client-reports' && <ClientReports/>}
          {clientView === 'client-hours' && <ClientHours/>}
          {clientView === 'profile' && <AdminProfile/>}
          {clientView === 'client-project-detail' && <ClientProjectDetail projectId={openProjectId} onBack={()=>setClientView('client-projects')}/>}
        </div>
      </div>
    );
  }

  return null;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
