"use client"

import { useEffect, useMemo, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { ArrowRight, CheckCircle2, Lock } from "lucide-react"
import { loadWizard, saveWizard } from "../../src/lib/wizardStorage"
import { apiSelectCountry } from "../../src/lib/apiClient"

interface Country {
  id: string
  name: string
  flag: string
  active: boolean
  color?: string
}

export default function UnetePage() {
  const router = useRouter()
  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null)
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const countries: Country[] = useMemo(
    () => [
      { id: "PE", name: "Perú", flag: "https://flagcdn.com/w80/pe.png", active: true, color: "border-l-[#53389B]" },
      { id: "CO", name: "Colombia", flag: "https://flagcdn.com/w80/co.png", active: true, color: "border-l-[#FFB800]" },
      { id: "CL", name: "Chile", flag: "https://flagcdn.com/w80/cl.png", active: false },
      { id: "MX", name: "México", flag: "https://flagcdn.com/w80/mx.png", active: false },
      { id: "US", name: "USA", flag: "https://flagcdn.com/w80/us.png", active: false },
      { id: "CA", name: "Canadá", flag: "https://flagcdn.com/w80/ca.png", active: false },
    ],
    []
  )

  useEffect(() => {
    const w = loadWizard()
    if (w.countryId) {
      const found = countries.find((c) => c.id === w.countryId)
      if (found) setSelectedCountry(found)
    }
  }, [countries])

  const handleContinue = async () => {
    setError(null)
    if (!selectedCountry) {
      setError("Por favor, selecciona un país para continuar.")
      return
    }

    // ✅ Guarda local (como tu JS viejo)
    saveWizard({ countryId: selectedCountry.id, countryName: selectedCountry.name })

    // ✅ Intento backend (si falla, igual continuamos)
    setIsSaving(true)
    try {
      await apiSelectCountry(selectedCountry.id)
    } catch (e) {
      console.warn("No se pudo guardar país en backend. Continuo igual.")
    } finally {
      setIsSaving(false)
    }

    router.push(/unete/registro?country=${encodeURIComponent(selectedCountry.id)})
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex flex-col items-center justify-center p-4 font-sans">
      <Link href="/" className="mb-8 flex items-center gap-2">
        <Image src="/images/careguard-logo.png" alt="CareGuard" width={180} height={45} className="h-10 w-auto" />
      </Link>

      <div className="bg-white w-full max-w-md rounded-[30px] shadow-xl shadow-gray-200/50 border border-gray-100 overflow-hidden p-8">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-gray-900 mb-2">¿De qué país eres?</h1>
          <p className="text-gray-500 text-sm">Selecciona tu país para personalizar tu experiencia.</p>
        </div>

        <div className="space-y-3">
          {countries.map((country) => (
            <button
              key={country.id}
              onClick={() => {
                if (!country.active || isSaving) return
                setSelectedCountry(country)
                setError(null)
                saveWizard({ countryId: country.id, countryName: country.name })
              }}
              disabled={!country.active || isSaving}
              className={
                w-full relative flex items-center gap-4 p-4 rounded-2xl border-2 transition-all duration-200 text-left group
                ${!country.active
                  ? "bg-gray-50 border-gray-100 opacity-60 cursor-not-allowed grayscale-[0.5]"
                  : selectedCountry?.id === country.id
                    ? "bg-[#53389B]/5 border-[#53389B] shadow-md"
                    : bg-white border-gray-100 hover:border-gray-300 hover:shadow-sm ${country.color} border-l-4
                }
              }
            >
              <Image
                src={country.flag}
                alt={country.name}
                width={40}
                height={40}
                className="w-10 h-10 rounded-full object-cover border border-gray-100 shadow-sm flex-shrink-0"
              />

              <div className="flex-1">
                <span className={font-bold ${selectedCountry?.id === country.id ? "text-gray-900" : "text-gray-600"}}>
                  {country.name}
                </span>
              </div>

              {country.active ? (
                <div className={
                  w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all
                  ${selectedCountry?.id === country.id ? "bg-[#53389B] border-[#53389B]" : "border-gray-300"}
                }>
                  {selectedCountry?.id === country.id && <CheckCircle2 className="w-4 h-4 text-white" />}
                </div>
              ) : (
                <span className="text-[10px] font-bold bg-gray-200 text-gray-500 px-2 py-1 rounded-md flex items-center gap-1">
                  <Lock className="w-3 h-3" /> Pronto
                </span>
              )}
            </button>
          ))}
        </div>

        {error && (
          <div className="mt-4 text-sm font-medium text-red-600 bg-red-50 border border-red-100 rounded-xl px-4 py-3">
            {error}
          </div>
        )}

        <div className="mt-8 pt-4 border-t border-gray-50 flex justify-end">
          <button
            onClick={handleContinue}
            disabled={!selectedCountry || isSaving}
            className={
              px-8 py-3.5 rounded-xl font-bold text-sm flex items-center gap-2 transition-all
              ${selectedCountry ? "bg-[#00A08D] hover:bg-[#008576] text-white shadow-lg shadow-[#00A08D]/20" : "bg-gray-100 text-gray-400 cursor-not-allowed"}
            }
          >
            {isSaving ? "Guardando..." : "Siguiente"} <ArrowRight className="w-4 h-4" />
          </button>
        </div>
      </div>

      <p className="mt-8 text-xs text-gray-400 text-center">
        © 2026 CareGuard Inc. • <Link href="/privacidad" className="hover:text-gray-600">Privacidad</Link> y{" "}
        <Link href="/terminos" className="hover:text-gray-600">Términos</Link>
      </p>
    </div>
  )
}

Ese es mi diseño actual que quiero y debes ponerlo aca:
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Seleccionar País - Careguard</title>
  <link rel="stylesheet" href="css/base.css">
  <link rel="stylesheet" href="css/seleccionar-pais.css">
  <script src="js/common.js" defer></script>
  <script src="js/seleccionar-pais.js" defer></script>
</head>
<body>
  <header class="wizard-header">
    <a href="https://careguard.es/" class="back-link">← Volver al inicio</a>
    <div class="logo">
      <img src="Recursos/careguard_logo.ico" alt="Careguard" class="logo-image">Careguard
    </div>
  </header>

  <main class="wizard-container">
    <!-- Formulario de Selección de País -->
    <section class="form-card country-card">
      <div class="form-header">
        <h2>¿De qué país eres?</h2>
        <p class="subtitle">Selecciona tu país para continuar con el registro</p>
      </div>

      <form id="countrySelectionForm">
        <div class="countries-container">
          <label class="country-option">
            <input type="radio" name="country" value="1" id="country-peru" required>
            <div class="country-card-item">
              <img src="Recursos/peru.png" alt="Perú" class="country-flag-img">
              <span class="country-name">Perú</span>
              <span class="checkmark">✓</span>
            </div>
          </label>

          <label class="country-option">
            <input type="radio" name="country" value="2" id="country-mexico" required>
            <div class="country-card-item">
              <img src="Recursos/mexico.png" alt="México" class="country-flag-img">
              <span class="country-name">México</span>
              <span class="checkmark">✓</span>
            </div>
          </label>

          <label class="country-option">
            <input type="radio" name="country" value="3" id="country-colombia" required>
            <div class="country-card-item">
              <img src="Recursos/colombia.png" alt="Colombia" class="country-flag-img">
              <span class="country-name">Colombia</span>
              <span class="checkmark">✓</span>
            </div>
          </label>
        </div>

        <!-- Mensaje de error -->
        <div id="errorMessage" class="error-message" style="display: none;">
          Por favor, selecciona un país para continuar
        </div>

        <!-- Botón Siguiente -->
        <div class="form-actions">
          <button type="submit" class="btn-primary">
            Siguiente →
          </button>
        </div>
      </form>
    </section>
  </main>

  <footer class="footer">
    <p>Powered by Viy.ai</p>
  </footer>
</body>
</html>