"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
  MapPin,
  Settings2,
  Moon,
  Sun,
  Sunset,
  CloudMoon,
  Bell,
  BellOff,
  Volume2,
  VolumeX,
  Clock,
  RefreshCw,
  Loader2,
  ChevronRight,
  X,
  Check,
  Navigation,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

// ── Types ──
interface PrayerTimings {
  Fajr: string;
  Dhuhr: string;
  Asr: string;
  Maghrib: string;
  Isha: string;
}

interface PrayerApiResponse {
  code: number;
  data: {
    timings: PrayerTimings;
    date: {
      readable: string;
      gregorian: { date: string };
      hijri?: { date: string; month: { en: string }; day: string };
    };
    meta: {
      timezone: string;
      method: { name: string };
      latitude: number;
      longitude: number;
    };
  };
}

interface LocationSettings {
  city: string;
  country: string;
}

// ── Constants ──
const PRAYER_ORDER: (keyof PrayerTimings)[] = [
  "Fajr",
  "Dhuhr",
  "Asr",
  "Maghrib",
  "Isha",
];

const PRAYER_INFO: Record<
  keyof PrayerTimings,
  { label: string; icon: typeof Moon; subtitle: string }
> = {
  Fajr: { label: "Fajr", icon: Moon, subtitle: "Dawn" },
  Dhuhr: { label: "Dhuhr", icon: Sun, subtitle: "Noon" },
  Asr: { label: "Asr", icon: Sun, subtitle: "Afternoon" },
  Maghrib: { label: "Maghrib", icon: Sunset, subtitle: "Sunset" },
  Isha: { label: "Isha", icon: CloudMoon, subtitle: "Night" },
};

const DEFAULT_LOCATION: LocationSettings = {
  city: "Kuala Lumpur",
  country: "MY",
};

// ── Helpers ──
function parseTimeToMs(timeStr: string, dayOffset = 0): number {
  const clean = timeStr.replace(/\s*\(.*\)\s*$/, "").trim();
  const [h, m] = clean.split(":").map(Number);
  if (isNaN(h) || isNaN(m)) return 0;
  const d = new Date();
  d.setDate(d.getDate() + dayOffset);
  d.setHours(h, m, 0, 0);
  return d.getTime();
}

function formatCountdown(ms: number): string {
  if (ms <= 0) return "0m 0s";
  const hours = Math.floor(ms / 3600000);
  const minutes = Math.floor((ms % 3600000) / 60000);
  const seconds = Math.floor((ms % 60000) / 1000);
  if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
  if (minutes > 0) return `${minutes}m ${seconds}s`;
  return `${seconds}s`;
}

function getNextPrayerInfo(timings: PrayerTimings | null): {
  name: keyof PrayerTimings | null;
  label: string;
  time: string;
  remaining: number;
  progress: number;
} {
  if (!timings) {
    return { name: null, label: "", time: "", remaining: 0, progress: 0 };
  }

  const now = Date.now();

  // Find next prayer today
  let nextName: keyof PrayerTimings | null = null;
  let nextTimeStr = "";
  let nextTimeMs = Infinity;

  for (const name of PRAYER_ORDER) {
    const t = parseTimeToMs(timings[name]);
    if (t > now && t < nextTimeMs) {
      nextTimeMs = t;
      nextName = name;
      nextTimeStr = timings[name];
    }
  }

  let prevTimeMs: number;

  if (!nextName) {
    // All prayers passed → next is tomorrow's Fajr
    nextName = "Fajr";
    nextTimeStr = timings.Fajr;
    nextTimeMs = parseTimeToMs(timings.Fajr, 1);
    prevTimeMs = parseTimeToMs(timings.Isha);
  } else {
    const idx = PRAYER_ORDER.indexOf(nextName);
    if (idx === 0) {
      // Before Fajr today → previous was yesterday's Isha
      const ishaMs = parseTimeToMs(timings.Isha);
      const yesterdayIsha = new Date(ishaMs);
      yesterdayIsha.setDate(yesterdayIsha.getDate() - 1);
      prevTimeMs = yesterdayIsha.getTime();
    } else {
      prevTimeMs = parseTimeToMs(timings[PRAYER_ORDER[idx - 1]]);
    }
  }

  const remaining = Math.max(0, nextTimeMs - now);
  const totalInterval = nextTimeMs - prevTimeMs;
  const elapsed = now - prevTimeMs;
  const progress =
    totalInterval > 0
      ? Math.min(Math.max(elapsed / totalInterval, 0), 1)
      : 0;

  return {
    name: nextName,
    label: PRAYER_INFO[nextName].label,
    time: nextTimeStr,
    remaining,
    progress,
  };
}

function getDayProgress(): number {
  const now = new Date();
  const start = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    0,
    0,
    0,
    0
  );
  const end = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    23,
    59,
    59,
    999
  );
  const elapsed = now.getTime() - start.getTime();
  const total = end.getTime() - start.getTime();
  return total > 0 ? elapsed / total : 0;
}

// ── SVG Circular Progress ──
function CircularProgress({
  percent,
  size = 80,
  strokeWidth = 5,
}: {
  percent: number;
  size?: number;
  strokeWidth?: number;
}) {
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference * (1 - percent);
  return (
    <svg
      width={size}
      height={size}
      className="transform -rotate-90"
      viewBox={`0 0 ${size} ${size}`}
    >
      {/* Background circle */}
      <circle
        cx={size / 2}
        cy={size / 2}
        r={radius}
        fill="none"
        stroke="rgba(255,255,255,0.05)"
        strokeWidth={strokeWidth}
      />
      {/* Progress arc */}
      <circle
        cx={size / 2}
        cy={size / 2}
        r={radius}
        fill="none"
        stroke="url(#goldGradient)"
        strokeWidth={strokeWidth}
        strokeLinecap="round"
        strokeDasharray={circumference}
        strokeDashoffset={offset}
        className="transition-all duration-500 ease-out"
      />
      <defs>
        <linearGradient id="goldGradient" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#D4AF37" />
          <stop offset="100%" stopColor="#f0d060" />
        </linearGradient>
      </defs>
    </svg>
  );
}

// ── Main Component ──
export default function PrayerPage() {
  const [timings, setTimings] = useState<PrayerTimings | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [location, setLocation] = useState<LocationSettings>(() => {
    if (typeof window === "undefined") return DEFAULT_LOCATION;
    try {
      const stored = localStorage.getItem("prayer_location");
      return stored ? JSON.parse(stored) : DEFAULT_LOCATION;
    } catch {
      return DEFAULT_LOCATION;
    }
  });
  const [notifications, setNotifications] = useState(() => {
    if (typeof window === "undefined") return true;
    return localStorage.getItem("prayer_notifications") !== "false";
  });
  const [adhanSound, setAdhanSound] = useState(() => {
    if (typeof window === "undefined") return true;
    return localStorage.getItem("prayer_adhan_sound") !== "false";
  });
  const [showSettings, setShowSettings] = useState(false);
  const [editCity, setEditCity] = useState("");
  const [editCountry, setEditCountry] = useState("");
  const [editLoading, setEditLoading] = useState(false);
  const [now, setNow] = useState(Date.now());
  const [showHijri, setShowHijri] = useState(false);
  const [hijriDate, setHijriDate] = useState("");
  const [refreshing, setRefreshing] = useState(false);

  // ── Fetch prayer times ──
  const fetchPrayerTimes = useCallback(
    async (city: string, country: string) => {
      setError(null);
      setLoading(true);
      try {
        const res = await fetch(
          `/mobile/api/prayer?city=${encodeURIComponent(city)}&country=${encodeURIComponent(country)}`
        );
        if (!res.ok) {
          const text = await res.text().catch(() => "Unknown error");
          throw new Error(`API error ${res.status}: ${text}`);
        }
        const json = await res.json();
        if (json.timings) {
          setTimings(json.timings as PrayerTimings);
          if (json.hijri) {
            setHijriDate(json.hijri);
            setShowHijri(true);
          }
        } else {
          throw new Error("Invalid response from prayer API");
        }
      } catch (err: any) {
        setError(err.message || "Failed to load prayer times");
      } finally {
        setLoading(false);
      }
    },
    []
  );

  // ── Initial fetch and refresh ──
  useEffect(() => {
    fetchPrayerTimes(location.city, location.country);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // ── Refresh handler ──
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchPrayerTimes(location.city, location.country);
    setTimeout(() => setRefreshing(false), 500);
  };

  // ── Countdown tick ──
  useEffect(() => {
    const interval = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(interval);
  }, []);

  // ── Persist toggles ──
  useEffect(() => {
    localStorage.setItem("prayer_notifications", String(notifications));
  }, [notifications]);

  useEffect(() => {
    localStorage.setItem("prayer_adhan_sound", String(adhanSound));
  }, [adhanSound]);

  // ── Compute next prayer ──
  const nextPrayer = getNextPrayerInfo(timings);
  const dayProgress = getDayProgress();

  // ── Current prayer index (for highlighting) ──
  const currentPrayerIndex = (() => {
    if (!timings) return -1;
    const nowMs = Date.now();
    for (let i = PRAYER_ORDER.length - 1; i >= 0; i--) {
      const t = parseTimeToMs(timings[PRAYER_ORDER[i]]);
      if (t <= nowMs) return i;
    }
    return -1;
  })();

  // ── Settings modal ──
  const openSettings = () => {
    setEditCity(location.city);
    setEditCountry(location.country);
    setShowSettings(true);
  };

  const saveSettings = async () => {
    const trimmedCity = editCity.trim();
    const trimmedCountry = editCountry.trim().toUpperCase();
    if (!trimmedCity || !trimmedCountry) return;

    setEditLoading(true);
    const newLoc = { city: trimmedCity, country: trimmedCountry };
    setLocation(newLoc);
    localStorage.setItem("prayer_location", JSON.stringify(newLoc));
    await fetchPrayerTimes(newLoc.city, newLoc.country);
    setEditLoading(false);
    setShowSettings(false);
  };

  // ── Countdown display ──
  const countdownText = formatCountdown(nextPrayer.remaining);
  const countdownValue = nextPrayer.remaining;

  // ── Render ──
  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      {/* ── Header ── */}
      <div className="px-4 pt-6 pb-3">
        <div className="flex items-center justify-between mb-1">
          <h1 className="text-xl font-bold text-white flex items-center gap-2">
            🕌 Prayer Times
          </h1>
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            className="w-10 h-10 rounded-xl bg-[#111118] border border-gray-800/60 flex items-center justify-center active:scale-95 transition"
          >
            <RefreshCw
              size={16}
              className={`text-gray-400 ${refreshing ? "animate-spin" : ""}`}
            />
          </button>
        </div>

        {/* Location bar */}
        <button
          onClick={openSettings}
          className="flex items-center gap-1.5 mt-1 active:opacity-70 transition"
        >
          <MapPin size={14} className="text-[#D4AF37]" />
          <span className="text-xs text-gray-400">
            {location.city}, {location.country}
          </span>
          <ChevronRight size={12} className="text-gray-600" />
        </button>

        {/* Hijri date */}
        {showHijri && hijriDate && (
          <p className="text-xs text-gray-600 mt-1">
            📅 {hijriDate}
          </p>
        )}
      </div>

      {/* ── Loading State ── */}
      {loading && (
        <div className="flex flex-col items-center justify-center py-20 gap-3">
          <Loader2 size={24} className="text-[#D4AF37] animate-spin" />
          <p className="text-sm text-gray-500">Fetching prayer times...</p>
        </div>
      )}

      {/* ── Error State ── */}
      {!loading && error && (
        <ErrorFeedback
          error={error}
          kind={error.includes("Network") ? "network" : "default"}
          onRetry={handleRefresh}
          context="Prayer times"
        />
      )}

      {/* ── Content ── */}
      {!loading && !error && timings && (
        <>
          {/* ── Next Prayer Card ── */}
          <div className="mx-4 mb-5">
            <div className="relative overflow-hidden bg-gradient-to-br from-[#D4AF37]/15 via-amber-900/10 to-[#111118] border border-[#D4AF37]/25 rounded-3xl p-6">
              {/* Decorative glow */}
              <div className="absolute -top-10 -right-10 w-32 h-32 bg-[#D4AF37]/10 rounded-full blur-3xl" />
              <div className="absolute -bottom-8 -left-8 w-24 h-24 bg-amber-500/5 rounded-full blur-2xl" />

              <div className="relative">
                <div className="flex items-center justify-between mb-4">
                  <p className="text-xs font-medium text-[#D4AF37]/70 uppercase tracking-wider">
                    Next Prayer
                  </p>
                  <div className="flex items-center gap-1.5">
                    <Clock size={12} className="text-gray-500" />
                    <span className="text-[10px] text-gray-500">
                      {countdownValue <= 3600000
                        ? "Due soon"
                        : countdownText.includes("h")
                          ? `${countdownText.split("h")[0]}h until`
                          : `${countdownText.split("m")[0]}m until`}
                    </span>
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <h2 className="text-3xl font-bold text-white mb-1">
                      {nextPrayer.label}
                    </h2>
                    <div className="flex items-baseline gap-2">
                      <span className="text-4xl font-light text-[#D4AF37] tracking-wider">
                        {nextPrayer.time}
                      </span>
                      <span className="text-xs text-gray-500">
                        {PRAYER_INFO[nextPrayer.name!]?.subtitle ?? ""}
                      </span>
                    </div>
                    <div className="mt-2">
                      <span className="text-lg font-mono font-semibold text-white/80">
                        {countdownText}
                      </span>
                      <span className="text-xs text-gray-500 ml-1.5">
                        remaining
                      </span>
                    </div>
                  </div>

                  {/* Prayer icon */}
                  <div className="w-16 h-16 rounded-2xl bg-[#D4AF37]/10 border border-[#D4AF37]/20 flex items-center justify-center">
                    {nextPrayer.name &&
                      (() => {
                        const Icon = PRAYER_INFO[nextPrayer.name].icon;
                        return (
                          <Icon
                            size={28}
                            className="text-[#D4AF37]"
                          />
                        );
                      })()}
                  </div>
                </div>

                {/* Progress bar */}
                <div className="mt-5">
                  <div className="h-2 bg-black/30 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-r from-[#D4AF37] to-[#f0d060] rounded-full transition-all duration-1000 ease-out"
                      style={{
                        width: `${Math.round(nextPrayer.progress * 100)}%`,
                      }}
                    />
                  </div>
                  <div className="flex justify-between mt-1.5">
                    <span className="text-[10px] text-gray-600">
                      {Math.round(nextPrayer.progress * 100)}%
                    </span>
                    <span className="text-[10px] text-gray-600">
                      towards {nextPrayer.label}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ── Day Progress & Prayer Grid Row ── */}
          <div className="mx-4 mb-5 flex gap-3">
            {/* Day progress circle */}
            <div className="shrink-0 bg-[#111118] border border-gray-800/60 rounded-2xl p-3 flex flex-col items-center justify-center w-[100px]">
              <CircularProgress percent={dayProgress} size={64} strokeWidth={4} />
              <p className="text-[10px] text-gray-500 mt-2">Day Progress</p>
              <p className="text-xs font-bold text-white">
                {Math.round(dayProgress * 100)}%
              </p>
            </div>

            {/* Time info */}
            <div className="flex-1 bg-[#111118] border border-gray-800/60 rounded-2xl p-3 flex flex-col justify-center">
              <p className="text-xs text-gray-500">Current Time</p>
              <p className="text-lg font-bold text-white font-mono">
                {new Date(now).toLocaleTimeString("en-MY", {
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </p>
              <p className="text-[10px] text-gray-600 mt-0.5">
                {new Date(now).toLocaleDateString("en-MY", {
                  weekday: "long",
                  day: "numeric",
                  month: "long",
                })}
              </p>
            </div>
          </div>

          {/* ── Daily Prayer Times ── */}
          <div className="px-4 mb-5">
            <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
              Daily Prayers
            </h2>
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden">
              {PRAYER_ORDER.map((name, idx) => {
                const isCurrent = idx === currentPrayerIndex;
                const isNext = name === nextPrayer.name;
                const Icon = PRAYER_INFO[name].icon;
                return (
                  <div
                    key={name}
                    className={`flex items-center justify-between px-4 py-3.5 min-h-[52px] transition-colors ${
                      isNext
                        ? "bg-[#D4AF37]/8 border-l-2 border-[#D4AF37]"
                        : isCurrent
                          ? "bg-white/[0.03] border-l-2 border-gray-700"
                          : "border-l-2 border-transparent"
                    } ${idx < PRAYER_ORDER.length - 1 ? "border-b border-gray-800/40" : ""}`}
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`w-9 h-9 rounded-xl flex items-center justify-center ${
                          isNext
                            ? "bg-[#D4AF37]/15"
                            : "bg-gray-800/40"
                        }`}
                      >
                        <Icon
                          size={16}
                          className={
                            isNext ? "text-[#D4AF37]" : "text-gray-400"
                          }
                        />
                      </div>
                      <div>
                        <p
                          className={`text-sm font-medium ${
                            isNext ? "text-[#D4AF37]" : "text-white"
                          }`}
                        >
                          {PRAYER_INFO[name].label}
                        </p>
                        <p className="text-[10px] text-gray-600">
                          {PRAYER_INFO[name].subtitle}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <span
                        className={`text-sm font-mono font-medium ${
                          isNext ? "text-[#D4AF37]" : "text-gray-300"
                        }`}
                      >
                        {timings[name]}
                      </span>
                      {isNext && (
                        <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-[#D4AF37]/15 text-[#D4AF37] font-medium">
                          Next
                        </span>
                      )}
                      {isCurrent && !isNext && (
                        <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-gray-700/40 text-gray-400 font-medium">
                          Now
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Settings Toggles ── */}
          <div className="px-4 mb-5">
            <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
              Preferences
            </h2>

            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden">
              {/* Prayer Notifications */}
              <div className="flex items-center justify-between px-4 py-3.5 border-b border-gray-800/40 min-h-[52px]">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-xl bg-gray-800/40 flex items-center justify-center">
                    {notifications ? (
                      <Bell size={16} className="text-[#D4AF37]" />
                    ) : (
                      <BellOff size={16} className="text-gray-500" />
                    )}
                  </div>
                  <div>
                    <p className="text-sm font-medium text-white">
                      Prayer Notifications
                    </p>
                    <p className="text-[10px] text-gray-600">
                      Get reminded at prayer times
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => setNotifications(!notifications)}
                  className={`relative w-11 h-6 rounded-full transition-colors ${
                    notifications
                      ? "bg-[#D4AF37]"
                      : "bg-gray-700"
                  }`}
                >
                  <div
                    className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                      notifications ? "translate-x-[22px]" : "translate-x-0.5"
                    }`}
                  />
                </button>
              </div>

              {/* Adhan Sound */}
              <div className="flex items-center justify-between px-4 py-3.5 min-h-[52px]">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-xl bg-gray-800/40 flex items-center justify-center">
                    {adhanSound ? (
                      <Volume2 size={16} className="text-[#D4AF37]" />
                    ) : (
                      <VolumeX size={16} className="text-gray-500" />
                    )}
                  </div>
                  <div>
                    <p className="text-sm font-medium text-white">
                      Adhan Sound
                    </p>
                    <p className="text-[10px] text-gray-600">
                      Play the call to prayer
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => setAdhanSound(!adhanSound)}
                  className={`relative w-11 h-6 rounded-full transition-colors ${
                    adhanSound ? "bg-[#D4AF37]" : "bg-gray-700"
                  }`}
                >
                  <div
                    className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                      adhanSound ? "translate-x-[22px]" : "translate-x-0.5"
                    }`}
                  />
                </button>
              </div>
            </div>
          </div>

          {/* ── Location Card (quick edit) ── */}
          <div className="px-4 mb-5">
            <button
              onClick={openSettings}
              className="w-full flex items-center justify-between bg-[#111118] border border-gray-800/60 rounded-2xl px-4 py-3.5 active:scale-[0.98] transition min-h-[52px]"
            >
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-xl bg-gray-800/40 flex items-center justify-center">
                  <Navigation size={16} className="text-gray-400" />
                </div>
                <div className="text-left">
                  <p className="text-sm font-medium text-white">
                    Change Location
                  </p>
                  <p className="text-[10px] text-gray-600">
                    {location.city}, {location.country}
                  </p>
                </div>
              </div>
              <ChevronRight size={16} className="text-gray-500" />
            </button>
          </div>
        </>
      )}

      {/* ── No timings but loaded state ── */}
      {!loading && !error && !timings && (
        <div className="mx-4">
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-8 text-center">
            <Moon size={32} className="mx-auto text-gray-700 mb-3" />
            <p className="text-sm text-gray-500">No prayer data available</p>
            <p className="text-xs text-gray-700 mt-1">
              Pull down to refresh or check your location settings
            </p>
            <button
              onClick={handleRefresh}
              className="mt-4 px-5 py-2.5 bg-[#D4AF37]/10 border border-[#D4AF37]/30 text-[#D4AF37] text-sm font-medium rounded-xl active:scale-95 transition"
            >
              Refresh
            </button>
          </div>
        </div>
      )}

      {/* ── Settings Modal ── */}
      {showSettings && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            onClick={() => !editLoading && setShowSettings(false)}
          />

          {/* Sheet */}
          <div className="relative w-full max-w-md bg-[#111118] border border-gray-800/60 rounded-t-3xl sm:rounded-3xl p-6 pb-8 animate-fade-in mx-4">
            <div className="flex items-center justify-between mb-5">
              <h3 className="text-lg font-bold text-white flex items-center gap-2">
                <MapPin size={18} className="text-[#D4AF37]" />
                Location Settings
              </h3>
              <button
                onClick={() => setShowSettings(false)}
                className="w-8 h-8 rounded-lg bg-gray-800/60 flex items-center justify-center active:scale-90 transition"
              >
                <X size={14} className="text-gray-400" />
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  City
                </label>
                <input
                  type="text"
                  value={editCity}
                  onChange={(e) => setEditCity(e.target.value)}
                  placeholder="e.g. Kuala Lumpur"
                  className="w-full bg-[#0a0a0f] border border-gray-800 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 outline-none focus:border-[#D4AF37]/40 transition"
                />
              </div>
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  Country Code
                </label>
                <input
                  type="text"
                  value={editCountry}
                  onChange={(e) => setEditCountry(e.target.value.toUpperCase())}
                  placeholder="e.g. MY"
                  maxLength={2}
                  className="w-full bg-[#0a0a0f] border border-gray-800 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 outline-none focus:border-[#D4AF37]/40 transition uppercase"
                />
                <p className="text-[10px] text-gray-600 mt-1">
                  Two-letter ISO country code
                </p>
              </div>
            </div>

            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowSettings(false)}
                disabled={editLoading}
                className="flex-1 py-3 bg-gray-800/60 text-gray-400 text-sm font-medium rounded-xl active:scale-95 transition disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                onClick={saveSettings}
                disabled={editLoading || !editCity.trim() || !editCountry.trim()}
                className="flex-1 py-3 bg-[#D4AF37] text-black text-sm font-semibold rounded-xl active:scale-95 transition disabled:opacity-50 flex items-center justify-center gap-1.5"
              >
                {editLoading ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : (
                  <Check size={16} />
                )}
                {editLoading ? "Saving..." : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
