'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { useUser } from './useUser';
import { useI18n } from '@/lib/i18n';
import { API_BASE } from '@/lib/config';

/**
 * /dashboard — point d'entrée après connexion.
 *
 * Unique rôle : synchroniser le paiement Stripe si `session_id` est présent
 * dans l'URL (retour depuis Stripe Checkout), puis rediriger vers /dashboard/translate.
 */
export default function DashboardPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const checkoutSessionId = searchParams.get('session_id');
  const [syncError, setSyncError] = useState<string | null>(null);
  const { refetch } = useUser();
  const { t } = useI18n();

  useEffect(() => {
    if (!checkoutSessionId) {
      router.replace('/dashboard/translate');
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      router.replace('/dashboard/translate');
      return;
    }

    let cancelled = false;
    const runSync = async () => {
      setSyncError(null);
      try {
        const res = await fetch(
          `${API_BASE}/api/v1/auth/checkout/sync?session_id=${encodeURIComponent(checkoutSessionId)}`,
          { headers: { Authorization: `Bearer ${token}` } }
        );
        if (!cancelled) {
          if (!res.ok) {
            const errData = await res.json().catch(() => ({}));
            setSyncError(errData.message || t('dashboard.checkoutSyncError'));
          } else {
            await refetch();
            router.replace('/dashboard/translate');
          }
        }
      } catch {
        if (!cancelled) setSyncError(t('dashboard.networkRefresh'));
      }
    };

    runSync();
    return () => { cancelled = true; };
  }, [checkoutSessionId, refetch, router, t]);

  if (syncError) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-20">
        <p className="text-sm text-destructive">{syncError}</p>
        <button
          onClick={() => router.replace('/dashboard/translate')}
          className="text-xs text-muted-foreground underline"
        >
          {t('dashboard.continueToTranslate')}
        </button>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-center py-20">
      <Loader2 className="size-6 animate-spin text-muted-foreground" />
    </div>
  );
}
