'use client';

import { useState } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { apiFetch } from '@/lib/api';

interface StepProps { onNext: () => void; }

const HOUSING_OPTIONS = [
  { id: 'squat', name: 'Squat abandonné', desc: 'Gratuit mais dangereux. Pas de serrure.', cost: 0, risk: 'Élevé' },
  { id: 'foyer', name: 'Foyer d\'accueil', desc: 'Gratuit, sécurisé, mais temporaire (30 jours).', cost: 0, risk: 'Faible' },
  { id: 'room', name: 'Chambre chez l\'habitant', desc: '50∞/jour. Modeste mais fonctionnel.', cost: 50, risk: 'Faible' },
];

export function StepHousing({ onNext }: StepProps) {
  const { player } = useGameStore();
  const [loading, setLoading] = useState(false);

  const handleChoose = async (housingId: string) => {
    if (!player?.id || loading) return;
    setLoading(true);
    try {
      await apiFetch(`/api/player/${player.id}/onboarding-choice`, {
        method: 'POST',
        body: JSON.stringify({ step: 'housing', choice: housingId }),
      });
    } catch (err) {
      console.error('Erreur creation residence:', err);
    } finally {
      setLoading(false);
      onNext();
    }
  };

  return (
    <div className="text-center">
      <h1 className="font-gothic text-3xl text-gold-gradient mb-2">Trouver un Toit</h1>
      <p className="mb-8" style={{ color: 'var(--text-secondary)' }}>
        La nuit tombe. Tu as besoin d&apos;un endroit pour dormir.
      </p>

      <div className="space-y-3 max-w-lg mx-auto">
        {HOUSING_OPTIONS.map((h) => (
          <button
            key={h.id}
            onClick={() => handleChoose(h.id)}
            disabled={loading}
            className="w-full text-left p-4 rounded-xl panel-glass hover:scale-[1.02] transition-all disabled:opacity-50"
          >
            <div className="flex justify-between items-start">
              <div>
                <h3 className="font-bold text-sm" style={{ color: 'var(--text-primary)' }}>{h.name}</h3>
                <p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>{h.desc}</p>
              </div>
              <div className="text-right shrink-0 ml-4">
                <div className="text-sm font-bold" style={{ color: h.cost === 0 ? '#22c55e' : 'var(--color-gold)' }}>
                  {h.cost === 0 ? 'Gratuit' : `${h.cost}∞/j`}
                </div>
                <div className="text-[10px]" style={{ color: h.risk === 'Élevé' ? 'var(--color-red-light)' : 'var(--text-muted)' }}>
                  Risque: {h.risk}
                </div>
              </div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}
