function useHashRoute(defaultKey = "login") {
  const get = () => (location.hash.startsWith('#/') ? location.hash.slice(2) : defaultKey);
  const [route, setRoute] = React.useState(get);
  React.useEffect(() => {
    const onHash = () => setRoute(get());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const go = (key) => { location.hash = `#/${key}`; };
  return [route, go];
}


const PUBLIC_ROUTES = new Set(["login", "termos", "suporte"]);
const isProtected = (r) => !PUBLIC_ROUTES.has(r);


function setChromeHidden(hidden){ document.body.classList.toggle('hide-chrome', hidden); }

function Spinner() {
  return (
    <window.__CRM__.Box sx={{ display:"grid", placeItems:"center", py: 8 }}>
      <MaterialUI.CircularProgress />
    </window.__CRM__.Box>
  );
}

function Dash() {
  return (
    <MaterialUI.Container maxWidth="lg" sx={{ py: 3 }}>
      <MaterialUI.Typography variant="h5" sx={{ fontWeight: 700, mb: 2 }}>Dashboard</MaterialUI.Typography>
      <window.__CRM__.Box sx={{ display:"grid", gridTemplateColumns:{ xs:"1fr", md:"1fr 1fr 1fr" }, gap:2 }}>
        <MaterialUI.Paper sx={{ p:2 }}><MaterialUI.Typography variant="subtitle2">Contatos</MaterialUI.Typography><MaterialUI.Typography variant="h4">—</MaterialUI.Typography></MaterialUI.Paper>
        <MaterialUI.Paper sx={{ p:2 }}><MaterialUI.Typography variant="subtitle2">Envios</MaterialUI.Typography><MaterialUI.Typography variant="h4">—</MaterialUI.Typography></MaterialUI.Paper>
        <MaterialUI.Paper sx={{ p:2 }}><MaterialUI.Typography variant="subtitle2">Status</MaterialUI.Typography><MaterialUI.Typography variant="h4">—</MaterialUI.Typography></MaterialUI.Paper>
      </window.__CRM__.Box>
    </MaterialUI.Container>
  );
}


function Config() {
  return (
    <MaterialUI.Container maxWidth="sm" sx={{ py: 3 }}>
      <MaterialUI.Typography variant="h5" sx={{ fontWeight: 700, mb: 2 }}>Configurações</MaterialUI.Typography>
      <MaterialUI.Paper sx={{ p:2 }}>
        <MaterialUI.Typography color="text.secondary">Ajustes por usuário em user_settings. UI em breve.</MaterialUI.Typography>
      </MaterialUI.Paper>
    </MaterialUI.Container>
  );
}

function App() {
  const { AppBootstrap, Box } = window.__CRM__;
  const [route, go] = useHashRoute("login");
  const [auth, setAuth] = React.useState({ loading: true, ok: false, user: null });
  const [error, setError] = React.useState("");

  React.useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const res = await fetch("/auth/ping.php", { credentials: "include", cache: "no-store" });
        if (!alive) return;
        if (res.ok) {
          const j = await res.json();
          setAuth({ loading: false, ok: j.ok === true, user: j.user || null });
          if (j.ok && route === "login") go("dashboard");
        } else {
          setAuth({ loading: false, ok: false, user: null });
          if (isProtected(route)) go("login");
        }
      } catch {
        if (!alive) return;
        setAuth({ loading: false, ok: false, user: null });
        setError("Falha ao verificar sessão.");
        if (isProtected(route)) go("login");
      }
    })();
    return () => { alive = false; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

    React.useEffect(() => {
      const hidden = (route === "login") || (!auth.ok);
      setChromeHidden(hidden);
    }, [route, auth]);
    
  const pages = {
    login: window.LoginPage ? <window.LoginPage /> : <Spinner />,
    dashboard: <Dash />,
    contacts: window.ContactsPage ? <window.ContactsPage/> : <Spinner/>,
    lists: window.ListsPage ? <window.ListsPage/> : <Spinner />,
    campaigns: window.CampaignsPage ? <window.CampaignsPage/> : <Spinner />, // <- aqui
    whatsapp: <MaterialUI.Container sx={{ py:3 }}><MaterialUI.Typography variant="h5">WhatsApp</MaterialUI.Typography><MaterialUI.Paper sx={{ p:2, mt:2 }}>Wireframe.</MaterialUI.Paper></MaterialUI.Container>,
    email: <MaterialUI.Container sx={{ py:3 }}><MaterialUI.Typography variant="h5">Email</MaterialUI.Typography><MaterialUI.Paper sx={{ p:2, mt:2 }}>Wireframe.</MaterialUI.Paper></MaterialUI.Container>,
    config: window.SettingsChatwootPage ? <window.SettingsChatwootPage/> : <Spinner />,
    termos: <MaterialUI.Container sx={{ py:3 }}><MaterialUI.Typography variant="h6">Termos</MaterialUI.Typography></MaterialUI.Container>,
    suporte: <MaterialUI.Container sx={{ py:3 }}><MaterialUI.Typography variant="h6">Suporte</MaterialUI.Typography></MaterialUI.Container>,
  };

  const view = pages[route] || <Dash />;
  
    // dynamic route: lists/{id}
    if (route.startsWith('lists/')) {
      const id = route.split('/')[1];
      if (window.ListEditPage) {
        return (
          <AppBootstrap>
            <window.ListEditPage listId={id} />
          </AppBootstrap>
        );
      }
      return <Spinner />;
    }
    
    if (route.startsWith('campaigns/')) {
      const parts = route.split('/'); // ['campaigns', ':id', 'analytics'?]
      const id = parts[1];
      const sub = parts[2] || '';
      if (sub === 'analytics' && window.AnalyticsPage) {
        return (
          <AppBootstrap>
            {auth.loading ? <Spinner/> : (
              <window.AnalyticsPage />
            )}
          </AppBootstrap>
        );
      }
    }

  return (
    <AppBootstrap>
      {auth.loading ? <Spinner /> : (
        <Box sx={{ pt: 2 }}>
          {error && <MaterialUI.Container sx={{ mb:2 }}><MaterialUI.Alert severity="error">{error}</MaterialUI.Alert></MaterialUI.Container>}
          {view}
        </Box>
      )}
    </AppBootstrap>
  );
}

(() => {
  const el = document.getElementById("crm-app");
  ReactDOM.createRoot(el).render(<App />);
})();
