/* global React, ReactDOM, Sidebar, DashboardTab, FieldsTab, FleetTab, IrrigationTab, ClimateTab, PestsTab, ChemicalsTab, InventoryTab, ReportsTab, NotificationsTab, SettingsTab, HelpTab */
const { useState, useEffect } = React;

const TABS = {
  dashboard: DashboardTab,
  fields: FieldsTab,
  fleet: FleetTab,
  irrigation: IrrigationTab,
  climate: ClimateTab,
  pests: PestsTab,
  chemicals: ChemicalsTab,
  inventory: InventoryTab,
  reports: ReportsTab,
  notifications: NotificationsTab,
  settings: SettingsTab,
  help: HelpTab,
};

function cleanAuthUrl() {
  try {
    const u = new URL(window.location.href);
    ["code", "state", "error", "error_description", "error_code"].forEach((k) => u.searchParams.delete(k));
    if (u.hash && u.hash.includes("access_token")) u.hash = "";
    const next = u.pathname + (u.searchParams.toString() ? `?${u.searchParams}` : "");
    window.history.replaceState(null, "", next);
  } catch { /* ignore */ }
}

function App() {
  // Local preview / missing Supabase keys → enter as demo
  const [authed, setAuthed] = useState(() => !!window.__PAMPA_DEMO__);
  const [authReady, setAuthReady] = useState(() => !!window.__PAMPA_DEMO__);
  const [user, setUser] = useState(null);
  const [route, setRoute] = useState(() => {
    try {
      const tab = new URLSearchParams(window.location.search).get("tab");
      if (tab) return tab;
    } catch { /* ignore */ }
    return localStorage.getItem("harvesta_route") || "dashboard";
  });
  const go = (r) => { setRoute(r); localStorage.setItem("harvesta_route", r); };

  useEffect(() => {
    const sb = window.supabaseClient;
    if (!sb || !sb.auth) {
      setAuthed(true);
      setAuthReady(true);
      return;
    }

    const applySession = (session) => {
      if (window.__PAMPA_DEMO__) {
        setAuthed(true);
        if (session?.user) setUser(session.user);
        return;
      }
      setAuthed(!!session);
      setUser(session?.user || null);
      if (session) cleanAuthUrl();
    };

    // Subscribe first so we don't miss SIGNED_IN from the Google ?code= return.
    const { data: { subscription } } = sb.auth.onAuthStateChange((_event, session) => {
      applySession(session);
      setAuthReady(true);
    });

    (async () => {
      try {
        const params = new URLSearchParams(window.location.search);
        if (params.get("code") && sb.auth.exchangeCodeForSession) {
          await sb.auth.exchangeCodeForSession(window.location.href).catch(() => null);
        }
        const { data: { session } } = await sb.auth.getSession();
        applySession(session);
      } catch {
        if (window.__PAMPA_DEMO__) setAuthed(true);
      } finally {
        setAuthReady(true);
      }
    })();

    return () => subscription && subscription.unsubscribe && subscription.unsubscribe();
  }, []);

  const handleLogout = async () => {
    const sb = window.supabaseClient;
    if (sb && sb.auth && sb.auth.signOut) {
      try { await sb.auth.signOut(); } catch { /* demo client / offline — proceed anyway */ }
    }
    setUser(null);
    setAuthed(false);
  };

  useEffect(() => {
    const el = document.querySelector("#tabscroll");
    if (el) el.scrollTop = 0;
  }, [route]);

  const Tab = TABS[route] || DashboardTab;
  return (
    <React.Fragment>
      <Sidebar route={route} go={go} user={user} onLogout={handleLogout} />
      <Tab go={go} key={route} />
      <window.DetailLayer />
      <window.AIAgronomo />
      {authReady && !authed && <window.LoginModal onAuthed={() => setAuthed(true)} />}
    </React.Fragment>
  );
}

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