"use client";

import { useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";

export default function ClientReadout() {
  const [out, setOut] = useState<any>({ status: "loading…" });

  useEffect(() => {
    (async () => {
      const documentCookie = typeof document !== "undefined" ? document.cookie : "(no document)";
      const sbCookieNames = (documentCookie || "")
        .split(";")
        .map((c) => c.trim().split("=")[0])
        .filter((n) => n.startsWith("sb-"));

      let sessionState: any = null;
      let userState: any = null;
      let getSessionErr: string | null = null;
      let getUserErr: string | null = null;

      try {
        const supabase = createClient();
        const sess = await supabase.auth.getSession();
        sessionState = sess.data?.session
          ? {
              access_token_len: sess.data.session.access_token?.length,
              user_id: sess.data.session.user?.id,
              user_email: sess.data.session.user?.email,
            }
          : null;
        if (sess.error) getSessionErr = sess.error.message;

        const userRes = await supabase.auth.getUser();
        userState = userRes.data?.user
          ? { id: userRes.data.user.id, email: userRes.data.user.email }
          : null;
        if (userRes.error) getUserErr = userRes.error.message;
      } catch (e: any) {
        getSessionErr = e?.message || String(e);
      }

      setOut({
        note: "Client-side view (after hydration) on the same request.",
        document_cookie_length: documentCookie.length,
        document_cookie_sample: documentCookie.slice(0, 120),
        sb_cookie_names_visible_to_js: sbCookieNames,
        client_getSession_error: getSessionErr,
        client_getUser_error: getUserErr,
        client_has_session: !!sessionState,
        client_session: sessionState,
        client_user: userState,
      });
    })();
  }, []);

  return (
    <pre style={{ padding: 20, fontFamily: "monospace", whiteSpace: "pre-wrap", background: "#FFFFFF", color: "#bbb", borderTop: "1px solid #333" }}>
      {JSON.stringify(out, null, 2)}
    </pre>
  );
}
