import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import { ThemeProvider } from "@/components/dashboard/theme/ThemeProvider";
import PinProtection from "@/components/dashboard/PinProtection";
import NightboardSmall from "@/components/dashboard/nightboard/NightboardSmall";
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}</>;
};

// Three-way gate: office IP gets PIN, authenticated users skip PIN,
// everyone else is bounced to login. Identity comes from /api/dashboard/whoami,
// which sits 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=/small" replace />;
  if (identity === "kiosk") return <PinProtectedLayout>{children}</PinProtectedLayout>;
  return <>{children}</>;
};

// Small Layout — Nightboard kiosk board, built at the panel's real resolution
// (10.1" 1920×1200); no transform-scale hacks.
const SmallLayout = () => <NightboardSmall />;

export function SmallDashboard() {
  return (
    <ThemeProvider>
      <AccessGate>
        <SmallLayout />
      </AccessGate>
    </ThemeProvider>
  );
}

export default SmallDashboard; 