/* global React, ReactDOM */

const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "role": "admin",
  "font": "inter",
  "viewport": "desktop"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [activeId, setActiveId] = useState('inicio');
  const [detalleId, setDetalleId] = useState(null);

  // Slide-overs
  const [nuevaOpen, setNuevaOpen] = useState(false);
  const [cargarOpen, setCargarOpen] = useState(false);
  const [cargarFor, setCargarFor] = useState(null);
  const [nuevaInstOpen, setNuevaInstOpen] = useState(false);
  const [nuevoUserOpen, setNuevoUserOpen] = useState(false);

  // Reset to home when role changes
  useEffect(() => {
    setActiveId('inicio');
    setDetalleId(null);
    setNuevaOpen(false);
    setCargarOpen(false);
  }, [t.role]);

  useEffect(() => {
    document.documentElement.dataset.font = t.font;
  }, [t.font]);

  const user = window.ROLES[t.role] || window.ROLES.admin;
  const modules = window.modulesForRole(t.role);
  const activeModule = modules.find(m => m.id === activeId) || modules[0];

  // ---- Routers
  const goNav = (id) => {
    // Detail closes when changing nav
    setDetalleId(null);
    // Special: "Nueva recomendación" nav opens the slide-over and stays on Compromisos
    if (id === 'nueva_recomendacion') {
      setActiveId('compromisos');
      setNuevaOpen(true);
      return;
    }
    // Special: "Cargar Avance" nav opens the panel and stays on Mis Compromisos
    if (id === 'cargar_avance') {
      setActiveId('mis_compromisos');
      setCargarFor(null); // auto-pick a pending or returned one inside the panel
      setCargarOpen(true);
      return;
    }
    setActiveId(id);
  };

  const openDetalle = (id) => setDetalleId(id);
  const closeDetalle = () => setDetalleId(null);

  const openCargar = (id) => { setCargarFor(id); setCargarOpen(true); };

  // Mobile mode
  if (t.viewport === 'mobile') {
    return (
      <>
        <window.MobileHome user={user} roleId={t.role} onNavigate={() => {}} />
        <Tweaks t={t} setTweak={setTweak} />
      </>
    );
  }

  // What to render in main area
  let screen;
  if (detalleId) {
    screen = (
      <window.DetalleScreen
        onBack={closeDetalle}
        onOpenTablero={closeDetalle}
      />
    );
  } else if (activeId === 'inicio') {
    screen = <window.HomeScreen user={user} roleId={t.role} onNavigate={goNav} />;
  } else if (activeId === 'tablero') {
    screen = <window.TableroScreen onOpenDetalle={openDetalle} />;
  } else if (activeId === 'compromisos') {
    screen = (
      <window.CompromisosScreen
        onOpenDetalle={openDetalle}
        onOpenNueva={() => setNuevaOpen(true)}
      />
    );
  } else if (activeId === 'mis_compromisos') {
    screen = (
      <window.MisCompromisosScreen
        user={user}
        onOpenDetalle={openDetalle}
        onCargar={openCargar}
      />
    );
  } else if (activeId === 'alertas') {
    screen = (
      <window.AlertasScreen
        roleId={t.role}
        user={user}
        onOpenDetalle={openDetalle}
      />
    );
  } else if (activeId === 'mensajeria') {
    screen = (
      <window.MensajeriaScreen
        roleId={t.role}
        user={user}
        onOpenDetalle={openDetalle}
      />
    );
  } else if (activeId === 'reportes') {
    screen = <window.ReportesScreen roleId={t.role} user={user} onOpenDetalle={openDetalle} />;
  } else if (activeId === 'reportes_aprobados') {
    screen = <window.ReportesAprobadosScreen user={user} />;
  } else if (activeId === 'usuarios') {
    screen = <window.UsuariosScreen roleId={t.role} user={user} onOpenNuevo={() => setNuevoUserOpen(true)} />;
  } else if (activeId === 'instituciones') {
    screen = <window.InstitucionesScreen user={user} onOpenNueva={() => setNuevaInstOpen(true)} />;
  } else if (activeId === 'portal') {
    screen = <window.PortalPublicoScreen />;
  } else {
    screen = <window.StubScreen moduleDef={activeModule} onBack={() => setActiveId('inicio')} />;
  }

  // Breadcrumb / topbar title
  let topbarTitle = activeModule.title;
  if (detalleId) topbarTitle = `Detalle · ${detalleId}`;

  return (
    <>
      <div className="app">
        <window.Sidebar
          modules={modules}
          activeId={activeId}
          onNavigate={goNav}
        />
        <window.Topbar user={user} activeModule={topbarTitle} />
        <main className="app__main">
          {screen}
        </main>
      </div>

      {/* Slide-overs */}
      <window.NuevaRecomendacionPanel
        open={nuevaOpen}
        onClose={() => setNuevaOpen(false)}
        onSave={() => { /* mock */ }}
      />
      <window.CargarAvancePanel
        open={cargarOpen}
        compromisoId={cargarFor}
        onClose={() => setCargarOpen(false)}
        onSubmit={() => { /* mock */ }}
      />
      <window.NuevaInstitucionPanel
        open={nuevaInstOpen}
        onClose={() => setNuevaInstOpen(false)}
        onSave={() => { /* mock */ }}
      />
      <window.NuevoUsuarioPanel
        open={nuevoUserOpen}
        onClose={() => setNuevoUserOpen(false)}
        onSave={() => { /* mock */ }}
      />

      <Tweaks t={t} setTweak={setTweak} />
    </>
  );
}

// ---------------- Tweaks ----------------
function Tweaks({ t, setTweak }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakSelect } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Rol del usuario">
        <TweakSelect
          label="Perfil activo"
          value={t.role}
          onChange={v => setTweak('role', v)}
          options={[
            { value: 'superadmin',  label: 'Súper Administrador (CGR)' },
            { value: 'admin',       label: 'Administrador (CGR · Análisis)' },
            { value: 'institucion', label: 'Institución Reportante (UTA)' },
            { value: 'cancilleria', label: 'Cancillería (solo lectura)' },
          ]}
        />
      </TweakSection>

      <TweakSection label="Tipografía">
        <TweakRadio
          value={t.font}
          onChange={v => setTweak('font', v)}
          options={[
            { value: 'inter',   label: 'Inter' },
            { value: 'jakarta', label: 'Jakarta' },
            { value: 'ibm',     label: 'IBM Plex' },
          ]}
        />
      </TweakSection>

      <TweakSection label="Vista">
        <TweakRadio
          value={t.viewport}
          onChange={v => setTweak('viewport', v)}
          options={[
            { value: 'desktop', label: 'Desktop' },
            { value: 'mobile',  label: 'Mobile' },
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

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