"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
import { PortalAside, PanelBrand } from "@/components/portal/parts";
import { RegisterFlow } from "@/components/portal/register-flow";
import { CookieBanner } from "@/components/portal/bits";
import { isShellConfigured } from "@/lib/appshell";

/**
 * Post-OAuth onboarding — a first-time Google user completes their CRM profile
 * (everything except email, which Google already verified).
 *
 * This screen is ONLY a step in the OAuth → onboarding handoff: the login page
 * stashes the verified email in `sessionStorage` right before routing here. Any
 * other way in — a typed URL, a fresh tab, a lost session — has no handoff hint
 * (and possibly no session), so we bounce back to sign in rather than showing an
 * empty form.
 */
export default function OnboardingPage() {
  const router = useRouter();
  const { status } = useAuth();
  const { ready } = useAppShell();
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    if (!isShellConfigured()) { setAllowed(true); return; } // local dev without the Shell
    if (!ready) return;                                     // wait for session restore
    let hasHandoff = false;
    try { hasHandoff = !!sessionStorage.getItem("onboard_email"); } catch { /* ignore */ }
    if (status === "unauthenticated" || !hasHandoff) {
      router.replace("/portal/login");
      return;
    }
    setAllowed(true);
  }, [ready, status, router]);

  if (!allowed) return <main className="portal-main"><span className="portal-grid" /></main>;

  return (
    <main className="portal-main">
      <span className="portal-grid" />
      <div className="portal-split anim-in">
        <PortalAside />
        <section className="portal-panel">
          <div style={{ width: "100%", maxWidth: 420 }}>
            <PanelBrand />
            <RegisterFlow mode="onboard" />
          </div>
        </section>
      </div>
      <CookieBanner />
    </main>
  );
}
