"use client"

import { useState } from "react"

export function GpsUpdater() {
  const [loading, setLoading] = useState(false)

  const updateLocation = () => {
    if (navigator.geolocation) {
      setLoading(true)
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          setLoading(false)
          const latInput = document.getElementById("input-lat") as HTMLInputElement;
          const lngInput = document.getElementById("input-lng") as HTMLInputElement;
          if (latInput && lngInput) {
            latInput.value = pos.coords.latitude.toFixed(7);
            lngInput.value = pos.coords.longitude.toFixed(7);
          } else {
            alert("Eroare interfață: Nu s-au găsit câmpurile (ID: input-lat, input-lng).");
          }
        },
        (err) => {
          setLoading(false)
          alert("Eroare la obținerea locației (verificați permisiunile browser-ului): " + err.message)
        },
        { timeout: 10000, maximumAge: 0, enableHighAccuracy: true }
      )
    } else {
      alert("Geolocația nu este suportată de acest browser.")
    }
  }

  return (
    <button
      type="button"
      onClick={updateLocation}
      disabled={loading}
      style={{
        marginTop: "1rem",
        gridColumn: "1 / -1",
        width: "fit-content",
        display: "flex",
        alignItems: "center",
        gap: "0.5rem",
        padding: "0.5rem 1rem",
        background: "var(--surface-hover)",
        border: "1px solid var(--border-color)",
        borderRadius: "var(--radius-md)",
        cursor: loading ? "wait" : "pointer",
        fontWeight: 500,
        color: "var(--text-main)",
        opacity: loading ? 0.7 : 1
      }}
    >
      {loading ? (
        <span style={{ display: "inline-block", width: "16px", height: "16px", border: "2px solid var(--primary)", borderTopColor: "transparent", borderRadius: "50%", animation: "spin 1s linear infinite" }} />
      ) : (
        <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>
      )}
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      {loading ? "Se obține locația..." : "Localizare GPS curentă"}
    </button>
  )
}
