import { useEffect, useState } from 'react';
import { useWizardStore } from '../store/wizardStore';
import CategorySelection from './Steps/CategorySelection';
import OperationSelection from './Steps/OperationSelection';
import AttributeForm from './Steps/AttributeForm';
import TextEditorStep from './Steps/TextEditorStep';
import PhotoUploadStep from './Steps/PhotoUploadStep';
import SummaryStep from './Steps/SummaryStep';
import { wizardService } from '../services/wizardService';
import type { AttributeDefinition } from '../types';
import SEO from '../components/SEO';

export default function PublishPage() {
  const { step, selectedCategory } = useWizardStore();
  const [definitions, setDefinitions] = useState<AttributeDefinition[]>([]);

  useEffect(() => {
    // CAMBIO: Agregamos el guard aquí también
    if (selectedCategory?.id) {
      wizardService.getAttributes(selectedCategory.id)
        .then(setDefinitions)
        .catch(err => console.error("Error en PublishPage:", err));
    }
  }, [selectedCategory?.id]);

  return (
    <div className="min-h-screen bg-slate-50 text-slate-900 font-sans pb-20">
      <SEO
        title="Publicar Aviso"
        description="Publica tu aviso clasificado en simples pasos."
      />

      {/* Header del Wizard interno */}
      <div className="bg-white border-b border-slate-200 sticky top-[80px] z-30 shadow-sm">
        <div className="max-w-3xl mx-auto px-4 h-14 flex items-center justify-between">
          <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">
            Paso {step} de 6
          </span>
          <div className="flex gap-1">
            {[1, 2, 3, 4, 5, 6].map((i) => (
              <div
                key={i}
                className={`w-8 h-1.5 rounded-full transition-colors ${i <= step ? 'bg-blue-600' : 'bg-slate-100'}`}
              />
            ))}
          </div>
        </div>
      </div>

      <main className="max-w-3xl mx-auto p-6 mt-8 bg-white rounded-[2.5rem] shadow-xl shadow-slate-200/50 border border-slate-100">
        {step === 1 && <CategorySelection />}
        {step === 2 && <OperationSelection />}
        {step === 3 && <AttributeForm />}
        {step === 4 && <TextEditorStep />}
        {step === 5 && <PhotoUploadStep />}
        {step === 6 && <SummaryStep definitions={definitions} />}
      </main>
    </div>
  );
}