"use client"

import { useState, useCallback } from "react"
import { useSession } from "next-auth/react"
import { useRouter } from "next/navigation"
import { romaniaCounties } from "@/lib/counties"
import styles from "./Wizard.module.css"

// Dynamically import exifr (it's a heavy library, browser-only)
async function extractExifGps(file: File): Promise<{ latitude: number; longitude: number } | null> {
  try {
    const exifr = await import("exifr")
    const gps = await exifr.gps(file)
    if (gps && gps.latitude && gps.longitude) {
      return { latitude: gps.latitude, longitude: gps.longitude }
    }
  } catch {
    // No EXIF or no GPS data
  }
  return null
}

const STEPS = [
  "Autor",
  "Date despre obiectiv",
  "Fotografie",
  "Documentare și analiză",
  "Elemente suplimentare",
]

type PhotoEntry = {
  file: File
  preview: string
  dateOfCapture: string
  equipment: string
  technicalSettings: string
  exifLat?: number
  exifLng?: number
}

export function WizardForm() {
  const { data: session } = useSession()
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(0)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState("")

  const [formData, setFormData] = useState({
    title: "",
    subjectName: "",
    address: "",
    city: "",
    county: "",
    latitude: "",
    longitude: "",
    lmiRanCode: "",
    estimatedPeriod: "",
    photos: [] as PhotoEntry[],
    copyrightConfirmed: false,
    motivation: "",
    context: "",
    historicalDesc: "",
    bibliographicSources: "",
    personalObservations: "",
    dataVeracityConfirmed: false,
  })

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target
    const checked = (e.target as HTMLInputElement).checked
    
    let processedValue = value
    if (name === "latitude" || name === "longitude") {
      processedValue = value.replace(/,/g, ".")
    }

    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : processedValue,
    }))
  }

  const handleFileChange = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (!e.target.files || e.target.files.length === 0) return
      const files = Array.from(e.target.files)
      const validFiles = files.filter((file) => {
        if (file.size > 10 * 1024 * 1024) {
          alert(`Fișierul "${file.name}" depășește limita de 10 MB.`)
          return false
        }
        return true
      })
      
      const remaining = 5 - formData.photos.length
      const toProcess = validFiles.slice(0, remaining)

      const newPhotos: PhotoEntry[] = await Promise.all(
        toProcess.map(async (file) => {
          const preview = URL.createObjectURL(file)
          const gps = await extractExifGps(file)

          // Auto-populate GPS from first photo that has EXIF
          if (gps && !formData.latitude && !formData.longitude) {
            setFormData((prev) => ({
              ...prev,
              latitude: gps.latitude.toFixed(7),
              longitude: gps.longitude.toFixed(7),
            }))
          }

          return {
            file,
            preview,
            dateOfCapture: new Date().toISOString().split("T")[0],
            equipment: "",
            technicalSettings: "",
            exifLat: gps?.latitude,
            exifLng: gps?.longitude,
          }
        })
      )

      setFormData((prev) => ({
        ...prev,
        photos: [...prev.photos, ...newPhotos].slice(0, 5),
      }))

      e.target.value = ""
    },
    [formData.photos.length, formData.latitude, formData.longitude]
  )

  const removePhoto = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      photos: prev.photos.filter((_, i) => i !== index),
    }))
  }

  const applyExifGps = (photo: PhotoEntry) => {
    if (photo.exifLat && photo.exifLng) {
      setFormData((prev) => ({
        ...prev,
        latitude: photo.exifLat!.toFixed(7),
        longitude: photo.exifLng!.toFixed(7),
      }))
    }
  }

  const handleNext = () => {
    if (currentStep < STEPS.length - 1) {
      setCurrentStep((c) => c + 1)
      window.scrollTo(0, 0)
    }
  }

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep((c) => c - 1)
      window.scrollTo(0, 0)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    setSubmitError("")

    try {
      // Convert files to base64 for transmission
      const photosPayload = await Promise.all(
        formData.photos.map(async (p) => {
          const buffer = await p.file.arrayBuffer()
          const base64 = Buffer.from(buffer).toString("base64")
          return {
            filename: p.file.name,
            size: p.file.size,
            mimeType: p.file.type,
            base64,
            dateOfCapture: p.dateOfCapture,
            equipment: p.equipment,
            technicalSettings: p.technicalSettings,
          }
        })
      )

      const res = await fetch("/rovibe/api/entries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: formData.title,
          subjectName: formData.subjectName,
          address: formData.address,
          city: formData.city,
          county: formData.county,
          latitude: formData.latitude,
          longitude: formData.longitude,
          lmiRanCode: formData.lmiRanCode || null,
          estimatedPeriod: formData.estimatedPeriod || null,
          motivation: formData.motivation,
          context: formData.context,
          historicalDesc: formData.historicalDesc,
          bibliographicSources: formData.bibliographicSources,
          personalObservations: formData.personalObservations || null,
          copyrightConfirmed: formData.copyrightConfirmed,
          dataVeracityConfirmed: formData.dataVeracityConfirmed,
          photos: photosPayload,
        }),
      })

      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.message || "Eroare la salvare.")
      }

      router.push("/dashboard?success=1")
      router.refresh()
    } catch (err: any) {
      setSubmitError(err.message || "A apărut o eroare. Te rugăm să încerci din nou.")
      setIsSubmitting(false)
    }
  }

  return (
    <div className={styles.wizardContainer}>
      {/* Loading Overlay */}
      {isSubmitting && (
        <div style={{
          position: "fixed",
          top: 0, left: 0, right: 0, bottom: 0,
          backgroundColor: "rgba(255, 255, 255, 0.8)",
          zIndex: 9999,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          backdropFilter: "blur(4px)"
        }}>
          <div style={{
            width: "60px",
            height: "60px",
            border: "6px solid var(--border-color)",
            borderTopColor: "var(--primary)",
            borderRadius: "50%",
            animation: "spin 1s linear infinite",
            marginBottom: "1.5rem"
          }} />
          <style>{`
            @keyframes spin {
              0% { transform: rotate(0deg); }
              100% { transform: rotate(360deg); }
            }
          `}</style>
          <h2 style={{ color: "var(--text-main)", fontWeight: 700, marginBottom: "0.5rem" }}>Se încarcă contribuția...</h2>
          <p style={{ color: "var(--text-muted)", fontSize: "0.95rem" }}>Acest proces poate dura câteva momente, în funcție de mărimea fotografiilor.</p>
        </div>
      )}

      {/* Stepper Header */}
      <div className={styles.stepper}>
        <div className={styles.stepConnector}>
          <div
            className={styles.stepProgress}
            style={{ width: `${(currentStep / (STEPS.length - 1)) * 100}%` }}
          />
        </div>
        {STEPS.map((step, index) => (
          <div
            key={index}
            className={`${styles.step} ${index === currentStep ? styles.active : ""} ${
              index < currentStep ? styles.completed : ""
            }`}
          >
            <div className={styles.stepIcon}>{index < currentStep ? "✓" : index + 1}</div>
            <div className={styles.stepLabel}>{step}</div>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit}>
        {/* SECȚIUNEA I : AUTOR */}
        {currentStep === 0 && (
          <div className="animate-fade-in">
            <h2 className={styles.sectionTitle}>I. Date Autor (Elev)</h2>
            <p className={styles.helpText} style={{ marginBottom: "1.5rem" }}>
              Aceste date sunt preluate automat din contul dumneavoastră.
            </p>
            <div className={styles.formGrid}>
              <div className={styles.formGroup}>
                <label className={styles.label}>Nume și prenume</label>
                <input type="text" disabled value={session?.user?.name || ""} className={styles.input} />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>Clasa</label>
                <input
                  type="text"
                  disabled
                  value={session?.user?.class ? `Clasa a ${session.user.class}-a` : ""}
                  className={styles.input}
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>E-mail contact</label>
                <input type="email" disabled value={session?.user?.email || ""} className={styles.input} />
              </div>
            </div>
          </div>
        )}

        {/* SECȚIUNEA II : DATE DESPRE OBIECTIV */}
        {currentStep === 1 && (
          <div className="animate-fade-in">
            <h2 className={styles.sectionTitle}>II. Date despre obiectiv</h2>
            <div className={styles.formGrid}>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Titlul lucrării *</label>
                <input
                  type="text"
                  name="title"
                  value={formData.title}
                  onChange={handleChange}
                  className={styles.input}
                  required
                  maxLength={100}
                  placeholder="Ex: Cetatea Poenari — Bastion al Rezistenței"
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Denumirea obiectivului / subiectului *</label>
                <input
                  type="text"
                  name="subjectName"
                  value={formData.subjectName}
                  onChange={handleChange}
                  className={styles.input}
                  required
                  maxLength={100}
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Adresa exactă *</label>
                <input
                  type="text"
                  name="address"
                  value={formData.address}
                  onChange={handleChange}
                  className={styles.input}
                  required
                  maxLength={200}
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>Localitate *</label>
                <input
                  type="text"
                  name="city"
                  value={formData.city}
                  onChange={handleChange}
                  className={styles.input}
                  required
                  maxLength={100}
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>Județ *</label>
                <select
                  name="county"
                  value={formData.county}
                  onChange={handleChange}
                  className={styles.select}
                  required
                >
                  <option value="">Selectați județul</option>
                  {romaniaCounties.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>
                  Cod LMI / RAN <span className={styles.optional}>(Opțional)</span>
                </label>
                <input
                  type="text"
                  name="lmiRanCode"
                  value={formData.lmiRanCode}
                  onChange={handleChange}
                  className={styles.input}
                  maxLength={50}
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.label}>
                  An / Perioadă estimată <span className={styles.optional}>(Opțional)</span>
                </label>
                <input
                  type="text"
                  name="estimatedPeriod"
                  value={formData.estimatedPeriod}
                  onChange={handleChange}
                  className={styles.input}
                  maxLength={50}
                />
              </div>
            </div>
          </div>
        )}

        {/* SECȚIUNEA III : FOTOGRAFIE + GPS */}
        {currentStep === 2 && (
          <div className="animate-fade-in">
            <h2 className={styles.sectionTitle}>III. Fotografie (minim 1, maxim 5)</h2>
            <p className={styles.helpText} style={{ marginBottom: "1.5rem" }}>
              Se acceptă efecte fotografice, dar nu postprocesare grea. Format JPG/PNG, max 10 MB per fotografie.
              Dacă fotografiile conțin date GPS (EXIF), coordonatele se vor completa automat.
            </p>

            {formData.photos.length < 5 && (
              <div className={`${styles.formGroup} ${styles.colSpan2}`} style={{ marginBottom: "1.5rem" }}>
                <label
                  htmlFor="photo-upload"
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: "0.75rem",
                    padding: "2rem",
                    border: "2px dashed var(--border-color)",
                    borderRadius: "var(--radius-lg)",
                    cursor: "pointer",
                    background: "var(--surface-hover)",
                    transition: "border-color 0.2s",
                  }}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
                    <circle cx="9" cy="9" r="2" />
                    <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
                  </svg>
                  <span style={{ fontWeight: 600, color: "var(--primary)" }}>
                    Click pentru a adăuga fotografii
                  </span>
                  <span style={{ fontSize: "0.85rem", color: "var(--text-muted)" }}>
                    {formData.photos.length} / 5 încărcate
                  </span>
                  <input
                    id="photo-upload"
                    type="file"
                    accept="image/jpeg,image/png,image/jpg"
                    multiple
                    onChange={handleFileChange}
                    style={{ display: "none" }}
                  />
                </label>
              </div>
            )}

            {/* Photo cards */}
            {formData.photos.map((photo, index) => (
              <div
                key={index}
                style={{
                  background: "var(--surface-color)",
                  border: "1px solid var(--border-color)",
                  borderRadius: "var(--radius-md)",
                  padding: "1rem",
                  marginBottom: "1rem",
                  display: "grid",
                  gridTemplateColumns: "120px 1fr",
                  gap: "1rem",
                  alignItems: "start",
                }}
              >
                <img
                  src={photo.preview}
                  alt={photo.file.name}
                  style={{ width: "120px", height: "90px", objectFit: "cover", borderRadius: "var(--radius-sm)" }}
                />
                <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontWeight: 600, fontSize: "0.9rem" }}>{photo.file.name}</span>
                    <button
                      type="button"
                      onClick={() => removePhoto(index)}
                      style={{ color: "var(--danger)", background: "none", border: "none", cursor: "pointer", fontWeight: 700, fontSize: "1.1rem" }}
                    >
                      ✕
                    </button>
                  </div>

                  {photo.exifLat && photo.exifLng && (
                    <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.4rem 0.75rem", background: "rgba(16,185,129,0.1)", borderRadius: "var(--radius-sm)", fontSize: "0.82rem", color: "var(--success)" }}>
                      <span>📍 GPS EXIF: {photo.exifLat.toFixed(5)}, {photo.exifLng.toFixed(5)}</span>
                      <button
                        type="button"
                        onClick={() => applyExifGps(photo)}
                        style={{ marginLeft: "auto", padding: "0.2rem 0.6rem", background: "var(--success)", color: "white", border: "none", borderRadius: "var(--radius-sm)", cursor: "pointer", fontSize: "0.78rem", fontWeight: 600 }}
                      >
                        Folosește
                      </button>
                    </div>
                  )}

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.5rem" }}>
                    <div>
                      <label className={styles.label} style={{ fontSize: "0.8rem" }}>Data realizării *</label>
                      <input
                        type="date"
                        value={photo.dateOfCapture}
                        onChange={(e) => {
                          const newPhotos = [...formData.photos]
                          newPhotos[index] = { ...newPhotos[index], dateOfCapture: e.target.value }
                          setFormData((prev) => ({ ...prev, photos: newPhotos }))
                        }}
                        className={styles.input}
                        required
                      />
                    </div>
                    <div>
                      <label className={styles.label} style={{ fontSize: "0.8rem" }}>Aparatură <span className={styles.optional}>(Opțional)</span></label>
                      <input
                        type="text"
                        value={photo.equipment}
                        maxLength={100}
                        onChange={(e) => {
                          const newPhotos = [...formData.photos]
                          newPhotos[index] = { ...newPhotos[index], equipment: e.target.value }
                          setFormData((prev) => ({ ...prev, photos: newPhotos }))
                        }}
                        className={styles.input}
                        placeholder="Ex: iPhone 14, DSLR Canon"
                      />
                    </div>
                  </div>
                  <div>
                    <label className={styles.label} style={{ fontSize: "0.8rem" }}>Setări tehnice <span className={styles.optional}>(Opțional)</span></label>
                    <input
                      type="text"
                      value={photo.technicalSettings}
                      maxLength={150}
                      onChange={(e) => {
                        const newPhotos = [...formData.photos]
                        newPhotos[index] = { ...newPhotos[index], technicalSettings: e.target.value }
                        setFormData((prev) => ({ ...prev, photos: newPhotos }))
                      }}
                      className={styles.input}
                      placeholder="Ex: ISO 100, f/8, 1/250s"
                    />
                  </div>
                </div>
              </div>
            ))}

            {/* GPS Coordinates */}
            <div
              style={{
                marginTop: "1.5rem",
                padding: "1.25rem",
                background: "var(--surface-color)",
                border: "1px solid var(--border-color)",
                borderRadius: "var(--radius-md)",
              }}
            >
              <h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.5rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
                Coordonate GPS *
              </h3>
              <p className={styles.helpText} style={{ marginBottom: "1rem" }}>
                Dacă fotografiile au EXIF, coordonatele se completează automat. Altfel, poți folosi butonul GPS sau le introduci manual.
              </p>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
                <div>
                  <label className={styles.label}>Latitudine (format zecimal) *</label>
                  <input
                    type="text"
                    inputMode="decimal"
                    name="latitude"
                    value={formData.latitude}
                    onChange={handleChange}
                    className={styles.input}
                    required
                    placeholder="Ex: 44.4268"
                  />
                </div>
                <div>
                  <label className={styles.label}>Longitudine (format zecimal) *</label>
                  <input
                    type="text"
                    inputMode="decimal"
                    name="longitude"
                    value={formData.longitude}
                    onChange={handleChange}
                    className={styles.input}
                    required
                    placeholder="Ex: 26.1025"
                  />
                </div>
              </div>
              <button
                type="button"
                onClick={() => {
                  if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                      (pos) =>
                        setFormData((prev) => ({
                          ...prev,
                          latitude: pos.coords.latitude.toFixed(7),
                          longitude: pos.coords.longitude.toFixed(7),
                        })),
                      (err) => alert("Eroare la obținerea locației: " + err.message)
                    )
                  } else {
                    alert("Geolocația nu este suportată de acest browser.")
                  }
                }}
                className={styles.locationBtn}
                style={{ marginTop: "0.75rem" }}
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
                Localizare GPS curentă
              </button>
            </div>

            <div className={styles.checkboxGroup} style={{ marginTop: "1.5rem" }}>
              <input
                type="checkbox"
                id="copyrightConfirmed"
                name="copyrightConfirmed"
                checked={formData.copyrightConfirmed}
                onChange={handleChange}
                className={styles.checkbox}
                required
              />
              <label htmlFor="copyrightConfirmed" className={styles.checkboxLabel}>
                Confirm drepturile de autor și originalitatea fotografiilor încărcate. *
              </label>
            </div>
          </div>
        )}

        {/* SECȚIUNEA IV : DOCUMENTARE ȘI ANALIZĂ */}
        {currentStep === 3 && (
          <div className="animate-fade-in">
            <h2 className={styles.sectionTitle}>IV. Documentare și analiză</h2>
            <div className={styles.formGrid}>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Motivația personală a alegerii subiectului *</label>
                <textarea
                  name="motivation"
                  value={formData.motivation}
                  onChange={handleChange}
                  className={styles.textarea}
                  maxLength={500}
                  required
                  placeholder="De ce ați ales acest subiect? (max 500 caractere)"
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Context urban/social/cultural *</label>
                <textarea
                  name="context"
                  value={formData.context}
                  onChange={handleChange}
                  className={styles.textarea}
                  maxLength={500}
                  required
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Scurtă descriere istorică/geografică *</label>
                <textarea
                  name="historicalDesc"
                  value={formData.historicalDesc}
                  onChange={handleChange}
                  className={styles.textarea}
                  maxLength={500}
                  required
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>Surse bibliografice/web *</label>
                <textarea
                  name="bibliographicSources"
                  value={formData.bibliographicSources}
                  onChange={handleChange}
                  className={styles.textarea}
                  maxLength={1000}
                  required
                />
              </div>
              <div className={`${styles.formGroup} ${styles.colSpan2}`}>
                <label className={styles.label}>
                  Alte observații personale <span className={styles.optional}>(Opțional)</span>
                </label>
                <textarea
                  name="personalObservations"
                  value={formData.personalObservations}
                  onChange={handleChange}
                  className={styles.textarea}
                  maxLength={500}
                />
              </div>
            </div>
          </div>
        )}

        {/* SECȚIUNEA V : ELEMENTE SUPLIMENTARE */}
        {currentStep === 4 && (
          <div className="animate-fade-in">
            <h2 className={styles.sectionTitle}>V. Elemente suplimentare</h2>
            <div
              className={styles.checkboxGroup}
              style={{
                marginTop: "2rem",
                padding: "1.5rem",
                background: "rgba(16, 185, 129, 0.1)",
                borderRadius: "var(--radius-md)",
                border: "1px solid var(--success)",
              }}
            >
              <input
                type="checkbox"
                id="dataVeracityConfirmed"
                name="dataVeracityConfirmed"
                checked={formData.dataVeracityConfirmed}
                onChange={handleChange}
                className={styles.checkbox}
                required
              />
              <label htmlFor="dataVeracityConfirmed" className={styles.checkboxLabel} style={{ fontWeight: 500 }}>
                Declarație pe proprie răspundere privind veridicitatea datelor: Confirm că toate informațiile introduse sunt corecte și verificate. *
              </label>
            </div>

            {submitError && (
              <div
                style={{
                  marginTop: "1rem",
                  padding: "1rem",
                  background: "rgba(239,68,68,0.1)",
                  color: "var(--danger)",
                  borderRadius: "var(--radius-md)",
                  border: "1px solid var(--danger)",
                }}
              >
                {submitError}
              </div>
            )}
          </div>
        )}

        {/* Navigation Buttons */}
        <div className={styles.buttonsContainer}>
          <div style={{ display: "flex", gap: "1rem" }}>
            <button
              type="button"
              onClick={() => router.push("/dashboard")}
              className={styles.btnSecondary}
              style={{ color: "var(--danger)", borderColor: "var(--danger)" }}
            >
              ✕ Anulare
            </button>
            <button
              type="button"
              onClick={handlePrev}
              disabled={currentStep === 0}
              className={styles.btnSecondary}
            >
              ← Înapoi
            </button>
          </div>

          {currentStep < STEPS.length - 1 ? (
            <button type="button" onClick={handleNext} className={styles.btnPrimary}>
              Înainte →
            </button>
          ) : (
            <button
              type="submit"
              className={styles.btnPrimary}
              disabled={isSubmitting}
              style={{ background: "var(--success)", opacity: isSubmitting ? 0.7 : 1 }}
            >
              {isSubmitting ? "Se salvează..." : "Salvează Transmiterea ✓"}
            </button>
          )}
        </div>
      </form>
    </div>
  )
}
