// admin-app.jsx — Wrapper principal: auth → tabs → CRUD
const { useState, useEffect } = React;

const AdminApp = () => {
  const [booting, setBooting] = useState(true);
  const [authed, setAuthed] = useState(false);
  const [profile, setProfile] = useState(null);
  const [tab, setTab] = useState('vehiculos');     // 'vehiculos' | 'leads' | 'usuarios'
  const [route, setRoute] = useState('list');      // 'list' | 'new' | 'edit'
  const [editingId, setEditingId] = useState(null);
  const [vehicles, setVehicles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState(null);
  const [configError, setConfigError] = useState(false);

  // Global helpers
  window.__adm_toast = (t) => setToast(t);
  const puede = (s) => profile?.role === 'admin' || (profile?.secciones || []).includes(s);
  useEffect(() => {
    if (!profile) return;
    const ord = [['vehiculos','web_vehiculos'],['leads','web_consultas'],['usuarios','web_usuarios']];
    const ok = ord.filter(([t,sx]) => profile.role==='admin' || (profile.secciones||[]).includes(sx));
    if (ok.length && !ok.some(([t]) => t===tab)) setTab(ok[0][0]);
  }, [profile]);

  // === BOOT: ¿hay sesión activa? ===
  useEffect(() => {
    (async () => {
      try {
        // Si no hay backend (ni Supabase configurado ni store local), mostramos config
        if (!window.OMEGA_STORE) {
          setConfigError(true);
          setBooting(false);
          return;
        }
        await window.OMEGA_STORE.init();
        const p = window.OMEGA_STORE.currentProfile();
        if (p) {
          setProfile(p);
          setAuthed(true);
          await loadVehicles();
        }
      } catch (e) {
        console.warn('Boot error:', e);
      } finally {
        setBooting(false);
      }
    })();
  }, []);

  const loadVehicles = async () => {
    setLoading(true);
    try {
      const list = await window.OMEGA_STORE.getRawVehicles(window.OMEGA_DATA.vehicles);
      setVehicles(list);
    } catch (e) {
      window.__adm_toast({ msg: 'Error al cargar vehículos: ' + e.message, type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const handleAuth = async () => {
    const p = await window.OMEGA_STORE.refreshProfile();
    setProfile(p);
    setAuthed(true);
    await loadVehicles();
  };

  const handleLogout = async () => {
    await window.OMEGA_STORE.signOut();
    setAuthed(false);
    setProfile(null);
    setVehicles([]);
    setRoute('list');
    setTab('vehiculos');
  };

  const handleNew = () => { setEditingId(null); setRoute('new'); };
  const handleEdit = (id) => { setEditingId(id); setRoute('edit'); };
  const handleCancel = async () => { setRoute('list'); await loadVehicles(); };

  const handleSave = async (vehicleData) => {
    try {
      await window.OMEGA_STORE.saveVehicle(vehicleData);
      await loadVehicles();
      setRoute('list');
      setToast({ msg: vehicleData.draft ? 'Auto oculto de la web' : 'Cambios guardados · visible en la web', type:'success' });
    } catch (e) {
      setToast({ msg: 'Error al guardar: ' + e.message, type:'error' });
    }
  };

  const handleDelete = async (id) => {
    try {
      await window.OMEGA_STORE.deleteVehicle(id);
      await loadVehicles();
      setToast({ msg: 'Fotos eliminadas de la web', type:'success' });
    } catch (e) {
      setToast({ msg: 'Error al eliminar: ' + e.message, type:'error' });
    }
  };

  const handleTogglePublished = async (id) => {
    const v = vehicles.find(x => x.id === id);
    if (!v) return;
    try {
      await window.OMEGA_STORE.saveVehicle({ ...v, draft: !v.draft });
      await loadVehicles();
      setToast({ msg: v.draft ? 'Visible en la web' : 'Oculto de la web', type:'success' });
    } catch (e) {
      setToast({ msg: 'Error: ' + e.message, type:'error' });
    }
  };

  // === RENDER ===
  if (configError) {
    return (
      <div className="login-wrap">
        <div className="login-card">
          <div className="login-logo">
            <img src="logo-omega.png" alt="OMEGA"/>
            <div className="login-logo-divider"/>
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--ink-dim)'}}>Configuración pendiente</div>
          </div>
          <h1>Conectar a Supabase</h1>
          <p>El back-office requiere conectarse a la base de datos. Seguí los pasos del archivo <strong style={{color:'var(--ink)'}}>SETUP-SUPABASE.md</strong>:</p>
          <ol style={{color:'var(--ink-dim)', fontSize:14, lineHeight:1.7, paddingLeft:20, margin:'20px 0'}}>
            <li>Crear proyecto en supabase.com</li>
            <li>Ejecutar el schema SQL</li>
            <li>Crear bucket <code style={{background:'var(--bg-elev-2)', padding:'2px 6px'}}>vehicle-photos</code></li>
            <li>Editar <code style={{background:'var(--bg-elev-2)', padding:'2px 6px'}}>supabase-config.js</code> con tu URL y anon key</li>
          </ol>
          <div className="login-error" style={{margin:'16px 0 0'}}>
            Editá supabase-config.js para empezar
          </div>
        </div>
      </div>
    );
  }

  if (booting) {
    return (
      <div className="login-wrap">
        <div style={{color:'var(--ink-dim)', fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase'}}>
          Iniciando back-office...
        </div>
      </div>
    );
  }

  if (!authed) return <LoginScreen onAuth={handleAuth}/>;

  if (loading) {
    return (
      <React.Fragment>
        <AdminTopBar profile={profile} active={tab} onTab={setTab} onLogout={handleLogout}/>
        <div style={{padding:120, textAlign:'center', color:'var(--ink-dim)', fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em'}}>
          CARGANDO INVENTARIO...
        </div>
      </React.Fragment>
    );
  }

  const currentVehicle = route === 'edit' && editingId ? vehicles.find(v => v.id === editingId) : null;

  return (
    <React.Fragment>
      {/* === Vehículos === */}
      {tab === 'vehiculos' && puede('web_vehiculos') && route === 'list' && (
        <Dashboard
          vehicles={vehicles}
          profile={profile}
          onEdit={handleEdit}
          onNew={handleNew}
          onDelete={handleDelete}
          onTogglePublished={handleTogglePublished}
          onLogout={handleLogout}
          onTab={setTab}
        />
      )}
      {tab === 'vehiculos' && puede('web_vehiculos') && (route === 'new' || route === 'edit') && (
        <VehicleEditor
          vehicle={currentVehicle}
          isNew={route === 'new'}
          profile={profile}
          onSave={handleSave}
          onCancel={handleCancel}
          onLogout={handleLogout}
        />
      )}

      {/* === Leads === */}
      {tab === 'leads' && puede('web_consultas') && (
        <LeadsScreen
          profile={profile}
          vehicles={vehicles}
          onTab={setTab}
          onLogout={handleLogout}
        />
      )}

      {/* === Usuarios (solo admin) === */}
      {tab === 'usuarios' && puede('web_usuarios') && (
        <UsersScreen
          profile={profile}
          onTab={setTab}
          onLogout={handleLogout}
        />
      )}

      {/* === Toast === */}
      {toast && <Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </React.Fragment>
  );
};

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