import { useEffect } from "react";
import { fetchMeta, startSession, parseUtm } from "./api/client";
import { useSession } from "./store/session";
import { BotRenderer } from "./components/BotRenderer";

export default function App() {
  const { meta, status, error, setMeta, startSession: setSession, setError } = useSession();

  useEffect(() => {
    (async () => {
      try {
        const m = await fetchMeta();
        setMeta(m);
        applyTheme(m.theme);
        const utm = parseUtm();
        const { session_id, step } = await startSession(
          Object.keys(utm).length > 0 ? utm : undefined,
        );
        setSession(session_id, step);
      } catch (err) {
        setError((err as Error).message);
      }
    })();
  }, [setMeta, setSession, setError]);

  if (status === "error") {
    return (
      <div className="flex h-full items-center justify-center p-6 text-center">
        <div>
          <p className="text-lg text-red-300">Erro ao carregar bot</p>
          <p className="mt-2 text-sm opacity-70">{error}</p>
        </div>
      </div>
    );
  }

  if (!meta) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="h-10 w-10 animate-spin rounded-full border-2 border-white/30 border-t-white" />
      </div>
    );
  }

  return <BotRenderer />;
}

function applyTheme(theme: { primary_color: string; secondary_color: string; bg_dark?: string; text_on_primary: string; font: string }): void {
  const r = document.documentElement;
  r.style.setProperty("--bot-primary", theme.primary_color);
  r.style.setProperty("--bot-secondary", theme.secondary_color);
  if (theme.bg_dark) r.style.setProperty("--bot-bg-dark", theme.bg_dark);
  r.style.setProperty("--bot-text-on-primary", theme.text_on_primary);
  r.style.setProperty("--bot-font", theme.font);
}
