'use client';

import { useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { getBrowserSupabase } from '@/lib/supabase';

function CallbackInner() {
  const router = useRouter();
  const search = useSearchParams();

  useEffect(() => {
    // Supabase JS picks up the access_token from the URL fragment automatically
    // (detectSessionInUrl: true). We wait for the session to materialize and
    // then route forward.
    const sb = getBrowserSupabase();
    if (!sb) {
      router.replace('/login?error=auth-not-configured');
      return;
    }

    const next = search.get('next') || '/dashboard';

    const { data: sub } = sb.auth.onAuthStateChange((event) => {
      if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED' || event === 'INITIAL_SESSION') {
        sb.auth.getSession().then(({ data }) => {
          if (data.session?.access_token) {
            // Keep the legacy localStorage token in sync for any older fetch
            // helpers that still read `sb-token` directly.
            localStorage.setItem('sb-token', data.session.access_token);
            if (data.session.refresh_token) {
              localStorage.setItem('sb-refresh-token', data.session.refresh_token);
            }
            router.replace(next);
          }
        });
      }
    });

    // Fallback: if no auth event fires within 4s, bail to login.
    const timer = setTimeout(() => router.replace('/login?error=callback-timeout'), 4000);
    return () => {
      sub.subscription.unsubscribe();
      clearTimeout(timer);
    };
  }, [router, search]);

  return (
    <section style={{ minHeight: '80vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <p className="mono" style={{ color: 'var(--text-tertiary)', fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
        Signing you in…
      </p>
    </section>
  );
}

export default function AuthCallback() {
  return (
    <Suspense fallback={null}>
      <CallbackInner />
    </Suspense>
  );
}
