// ============================================================
// CONTAX · APP SHELL — root component, routing, theme
// ============================================================

const { useState, useEffect } = React;

function getInitialMode() {
  const params = new URLSearchParams(window.location.search);
  const m = params.get('mode');
  if (m === 'web' || m === 'mobile') return m;
  return null;
}

// =================== MODE SELECTOR ===================
function ModeSelector({ onSelect }) {
  const isMobile = window.matchMedia('(max-width: 768px)').matches;

  return (
    <div className="mode-page">
      <div className="mode-page-glow"/>
      <div className="mode-inner">
        <div className="mode-logo">
          <img src="assets/contax-logo.png" alt="CONTAX"/>
          <span className="mode-logo-sub">Cash Flow · Barranquilla</span>
        </div>

        <h1 className="mode-title">¿Desde dónde accedes?</h1>
        <p className="mode-sub">Selecciona la versión adecuada para tu dispositivo</p>

        <div className="mode-cards">
          {/* WEB */}
          <button className={`mode-card ${!isMobile ? 'mode-card-rec' : ''}`} onClick={() => onSelect('web')}>
            <div className="mode-card-icon-wrap">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="3" width="20" height="14" rx="2"/>
                <path d="M8 21h8M12 17v4"/>
              </svg>
            </div>
            <div className="mode-card-body">
              <span className="mode-card-role">Dueño · Gerente · Administrador</span>
              <h3 className="mode-card-title">Panel de Control</h3>
              <ul className="mode-card-list">
                <li>Dashboard ejecutivo con reportes</li>
                <li>Control bancario y estado de resultados</li>
                <li>Nómina, inventario y gastos</li>
              </ul>
            </div>
            <div className="mode-card-footer">
              {!isMobile
                ? <span className="pill accent">Recomendado para esta pantalla</span>
                : <span className="mode-card-hint">Optimizado para pantalla grande</span>}
              <span className="mode-card-arrow">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7"/>
                </svg>
              </span>
            </div>
          </button>

          {/* MOBILE */}
          <button className={`mode-card ${isMobile ? 'mode-card-rec' : ''}`} onClick={() => onSelect('mobile')}>
            <div className="mode-card-icon-wrap">
              <svg width="28" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="6" y="2" width="12" height="20" rx="2"/>
                <path d="M11 18h2"/>
              </svg>
            </div>
            <div className="mode-card-body">
              <span className="mode-card-role">Operario · Encargado de turno</span>
              <h3 className="mode-card-title">Vista Operario</h3>
              <ul className="mode-card-list">
                <li>Conteo de vasos del día</li>
                <li>Cuadre de caja en tiempo real</li>
                <li>Cierre rápido y autosave</li>
              </ul>
            </div>
            <div className="mode-card-footer">
              {isMobile
                ? <span className="pill accent">Recomendado para esta pantalla</span>
                : <span className="mode-card-hint">Optimizado para celular</span>}
              <span className="mode-card-arrow">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7"/>
                </svg>
              </span>
            </div>
          </button>
        </div>

        <p className="mode-hint">
          Acceso directo:
          <code onClick={() => onSelect('web')}>?mode=web</code>
          <span style={{ color: 'var(--text-disabled)' }}>·</span>
          <code onClick={() => onSelect('mobile')}>?mode=mobile</code>
        </p>
      </div>
    </div>
  );
}

// =================== APP ROOT ===================
function App() {
  const [mode, setMode]         = useState(getInitialMode);
  const [authed, setAuthed]     = useState(true);
  const [route, setRoute]       = useState('dashboard');
  const [collapsed, setCollapsed] = useState(false);
  const [period, setPeriod]     = useState('month');
  const [theme, setTheme]       = useState('dark');

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  const selectMode = (m) => {
    setMode(m);
    const url = new URL(window.location);
    url.searchParams.set('mode', m);
    window.history.replaceState({}, '', url);
  };

  const exitMode = () => {
    setMode(null);
    const url = new URL(window.location);
    url.searchParams.delete('mode');
    window.history.replaceState({}, '', url);
  };

  // No mode selected → show selector
  if (!mode) return <ModeSelector onSelect={selectMode}/>;

  // ── MOBILE MODE ──────────────────────────────────────────
  if (mode === 'mobile') {
    return (
      <div style={{ background: 'var(--bg-base)', minHeight: '100vh' }}>
        <button className="mode-switch-btn" onClick={exitMode} title="Cambiar vista">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="2" y="3" width="20" height="14" rx="2"/>
            <path d="M8 21h8M12 17v4"/>
          </svg>
          Cambiar vista
        </button>
        <OperarioView/>
      </div>
    );
  }

  // ── WEB MODE ─────────────────────────────────────────────
  if (!authed) return <LoginView onLogin={() => setAuthed(true)}/>;

  if (route === 'operario') {
    return (
      <div style={{ background: 'var(--bg-base)', minHeight: '100vh', position: 'relative' }}>
        <button className="btn ghost" onClick={() => setRoute('dashboard')}
          style={{ position: 'fixed', top: 16, left: 16, zIndex: 50 }}>
          <window.I.ChevronLeft size={14}/> Volver al panel
        </button>
        <OperarioView/>
      </div>
    );
  }

  const crumbsMap = {
    dashboard:  ['Operación', 'Panel ejecutivo'],
    inventario: ['Operación', 'Inventario'],
    gastos:     ['Operación', 'Gastos'],
    informe:    ['Reportes', 'Informe Mensual'],
    nomina:     ['Reportes', 'Nómina'],
  };

  return (
    <ToastProvider>
      <div className={`app-shell ${collapsed ? 'collapsed' : ''}`}>
        <Sidebar active={route} onNav={setRoute} collapsed={collapsed} onToggle={() => setCollapsed(c => !c)}/>
        <div className="main-col">
          <TopBar
            crumbs={crumbsMap[route]}
            period={period}
            setPeriod={setPeriod}
            theme={theme}
            setTheme={setTheme}
            onSwitchMode={exitMode}
          />
          {route === 'dashboard'  && <DashboardView period={period}/>}
          {route === 'inventario' && <InventarioView/>}
          {route === 'gastos'     && <GastosView/>}
          {route === 'informe'    && <InformeView/>}
          {route === 'nomina'     && <NominaView/>}
        </div>
      </div>
    </ToastProvider>
  );
}

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