import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import PinProtection from "@/components/dashboard/PinProtection";
import StudioMobile from "@/components/dashboard/mobile/StudioMobile";
import PageLoading from "@/components/ui/page-loading";
import { apiFetch } from "@/utils/api";

// Pin Protected Layout
const PinProtectedLayout = ({ children }: { children: React.ReactNode }) => {
  const [isPinVerified, setIsPinVerified] = useState(() => {
    return sessionStorage.getItem("pinVerified") === "true";
  });

  const handlePinSuccess = () => {
    setIsPinVerified(true);
    sessionStorage.setItem("pinVerified", "true");
  };

  if (!isPinVerified) {
    return <PinProtection onSuccess={handlePinSuccess} />;
  }

  return <>{children}</>;
};

// Same three-way gate as /small: office IP gets PIN, authenticated users skip
// PIN, everyone else is bounced to login. Identity comes from
// /api/dashboard/whoami (behind Caddy's office-IP allowlist for the kiosk case).
type Identity = "probing" | "kiosk" | "authenticated" | "anonymous";

const AccessGate = ({ children }: { children: React.ReactNode }) => {
  const [identity, setIdentity] = useState<Identity>("probing");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await apiFetch("/api/dashboard/whoami");
        if (cancelled) return;
        if (res.status === 401) {
          setIdentity("anonymous");
          return;
        }
        const body = await res.json();
        setIdentity(body.is_kiosk ? "kiosk" : "authenticated");
      } catch {
        if (!cancelled) setIdentity("anonymous");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  if (identity === "probing") return <PageLoading />;
  if (identity === "anonymous") return <Navigate to="/login?redirect=/mobile" replace />;
  if (identity === "kiosk") return <PinProtectedLayout>{children}</PinProtectedLayout>;
  return <>{children}</>;
};

export function MobileDashboard() {
  return (
    <AccessGate>
      <StudioMobile />
    </AccessGate>
  );
}

export default MobileDashboard;
