"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { ChangeEvent, FormEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  ArrowDown,
  ArrowUp,
  Edit3,
  GripVertical,
  ImagePlus,
  IndianRupee,
  Maximize2,
  Loader2,
  Plus,
  Search,
  Star,
  Trash2,
  X,
} from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import {
  adminRequest,
  loadActiveAdminLocations,
  type AdminAmcPackagePrice,
  type AdminCarLogo,
  type AdminLocation,
  type AdminVehicleTier,
} from "@/lib/admin-api";
import { uploadCarLogoImage } from "@/lib/storage";
import { toStorageUrl } from "@/lib/storage-url";

type LogoFormState = {
  id?: number;
  name: string;
  slug: string;
  logo: string;
  isPopular: boolean;
};

const emptyForm: LogoFormState = {
  name: "",
  slug: "",
  logo: "",
  isPopular: false,
};

function toSlug(value: string) {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "");
}

function formatCurrency(value: number) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value);
}

function getAdjustedPrice(
  basePrice: number,
  discountPercentage: number,
  location: Pick<AdminLocation, "additionalCostPercentage" | "discountPercentage">,
) {
  return Math.max(
    0,
    basePrice *
      (1 - Number(discountPercentage || 0) / 100) *
      (1 + Number(location.additionalCostPercentage || 0) / 100) *
      (1 - Number(location.discountPercentage || 0) / 100),
  );
}

export default function AdminCarLogosPage() {
  const router = useRouter();
  const [logos, setLogos] = useState<AdminCarLogo[]>([]);
  const [popularLogos, setPopularLogos] = useState<AdminCarLogo[]>([]);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isUploadingLogo, setIsUploadingLogo] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [form, setForm] = useState<LogoFormState | null>(null);
  const [pricingLogo, setPricingLogo] = useState<AdminCarLogo | null>(null);
  const [pendingDeleteLogo, setPendingDeleteLogo] = useState<AdminCarLogo | null>(null);
  const [isDeletingId, setIsDeletingId] = useState<number | null>(null);
  const [draggingPopularId, setDraggingPopularId] = useState<number | null>(null);
  const [popularModalOpen, setPopularModalOpen] = useState(false);
  const [clearConfirmOpen, setClearConfirmOpen] = useState(false);
  const [swapSourceId, setSwapSourceId] = useState<number | null>(null);
  const loadMoreRef = useRef<HTMLDivElement | null>(null);

  const popularIds = useMemo(() => new Set(popularLogos.map((logo) => logo.id)), [popularLogos]);

  const loadPopularLogos = useCallback(async () => {
    const data = await adminRequest<{ logos: AdminCarLogo[] }>(
      "/api/admin/vehicle-logos?vehicleType=car&popular=true&limit=60",
    );
    setPopularLogos(data.logos);
  }, []);

  const loadLogos = useCallback(
    async (nextPage: number, mode: "replace" | "append") => {
      if (mode === "append") {
        setIsLoadingMore(true);
      } else {
        setIsLoading(true);
      }
      setErrorMessage("");

      try {
        const params = new URLSearchParams({
          page: String(nextPage),
          limit: "24",
        });

        if (search.trim()) {
          params.set("search", search.trim());
        }

        const data = await adminRequest<{
          logos: AdminCarLogo[];
          page: number;
          total: number;
          hasMore: boolean;
        }>(`/api/admin/vehicle-logos?vehicleType=car&${params.toString()}`);

        setLogos((current) => (mode === "append" ? [...current, ...data.logos] : data.logos));
        setPage(data.page);
        setTotal(data.total);
        setHasMore(data.hasMore);
      } catch (error) {
        setErrorMessage(error instanceof Error ? error.message : "Could not load car companies");
      } finally {
        setIsLoading(false);
        setIsLoadingMore(false);
      }
    },
    [search],
  );

  useEffect(() => {
    const timer = window.setTimeout(() => {
      loadLogos(1, "replace");
    }, 250);

    return () => window.clearTimeout(timer);
  }, [loadLogos]);

  useEffect(() => {
    loadPopularLogos().catch(() => setPopularLogos([]));
  }, [loadPopularLogos]);

  useEffect(() => {
    const target = loadMoreRef.current;

    if (!target || !hasMore || isLoading || isLoadingMore) {
      return;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0]?.isIntersecting) {
          loadLogos(page + 1, "append");
        }
      },
      {
        rootMargin: "500px 0px",
      },
    );

    observer.observe(target);

    return () => observer.disconnect();
  }, [hasMore, isLoading, isLoadingMore, loadLogos, page]);

  useEffect(() => {
    const shouldLockScroll =
      Boolean(form) ||
      Boolean(pricingLogo) ||
      Boolean(pendingDeleteLogo) ||
      popularModalOpen ||
      clearConfirmOpen;

    if (!shouldLockScroll) {
      return;
    }

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [form, pricingLogo, pendingDeleteLogo, popularModalOpen, clearConfirmOpen]);

  function openAddForm() {
    setForm(emptyForm);
  }

  function openEditForm(logo: AdminCarLogo) {
    setForm({
      id: logo.id,
      name: logo.name,
      slug: logo.slug,
      logo: logo.logo,
      isPopular: logo.isPopular,
    });
  }

  async function uploadLogoImage(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];

    if (!file || !form) {
      return;
    }

    const slug = form.slug || toSlug(form.name);

    if (!slug) {
      setErrorMessage("Enter a company name before uploading the company image.");
      event.target.value = "";
      return;
    }

    setIsUploadingLogo(true);
    setErrorMessage("");

    try {
      const imageUrl = await uploadCarLogoImage(file, slug);
      setForm((current) =>
        current
          ? {
              ...current,
              slug,
              logo: imageUrl,
            }
          : current,
      );
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not upload company image");
    } finally {
      setIsUploadingLogo(false);
      event.target.value = "";
    }
  }

  async function saveLogo(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (!form) {
      return;
    }

    setIsSaving(true);
    setErrorMessage("");

    try {
      const slug = form.slug.trim() || toSlug(form.name);

      if (!form.logo) {
        throw new Error("Upload a company logo before saving.");
      }

      const payload = {
        name: form.name.trim(),
        slug,
        logo: form.logo.trim(),
        isPopular: form.isPopular,
      };

      if (form.id) {
        await adminRequest(`/api/admin/car-logos/${form.id}`, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
      } else {
        await adminRequest("/api/admin/car-logos", {
          method: "POST",
          body: JSON.stringify(payload),
        });
      }

      setForm(null);
      await Promise.all([loadLogos(1, "replace"), loadPopularLogos()]);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not save car company");
    } finally {
      setIsSaving(false);
    }
  }

  async function updatePopular(logo: AdminCarLogo, isPopular: boolean) {
    setLogos((current) =>
      current.map((item) => (item.id === logo.id ? { ...item, isPopular } : item)),
    );
    setPopularLogos((current) => {
      if (isPopular) {
        return current.some((item) => item.id === logo.id)
          ? current
          : [...current, { ...logo, isPopular }].sort((a, b) => a.name.localeCompare(b.name));
      }

      return current.filter((item) => item.id !== logo.id);
    });

    try {
      await adminRequest(`/api/admin/car-logos/${logo.id}/popular`, {
        method: "PATCH",
        body: JSON.stringify({ isPopular }),
      });
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not update popular status");
      await Promise.all([loadLogos(page, "replace"), loadPopularLogos()]);
    }
  }

  async function clearPopularCompanies() {
    if (popularLogos.length === 0) {
      return;
    }

    const previousPopularLogos = popularLogos;
    setPopularLogos([]);
    setLogos((current) => current.map((logo) => ({ ...logo, isPopular: false })));
    setClearConfirmOpen(false);

    try {
      await adminRequest("/api/admin/car-logos/popular", {
        method: "DELETE",
      });
    } catch (error) {
      setErrorMessage(
        error instanceof Error ? error.message : "Could not remove popular companies",
      );
      setPopularLogos(previousPopularLogos);
      await loadLogos(page, "replace");
    }
  }

  async function deleteLogo(logo: AdminCarLogo) {
    setIsDeletingId(logo.id);
    setErrorMessage("");

    try {
      await adminRequest(`/api/admin/car-logos/${logo.id}`, {
        method: "DELETE",
      });
      setPendingDeleteLogo(null);
      await Promise.all([loadLogos(1, "replace"), loadPopularLogos()]);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not delete car company");
    } finally {
      setIsDeletingId(null);
    }
  }

  async function savePopularOrder(nextLogos: AdminCarLogo[]) {
    setPopularLogos(nextLogos);

    try {
      await adminRequest("/api/admin/car-logos/popular/reorder", {
        method: "PATCH",
        body: JSON.stringify({ ids: nextLogos.map((logo) => logo.id) }),
      });
    } catch (error) {
      setErrorMessage(
        error instanceof Error ? error.message : "Could not reorder popular companies",
      );
      await loadPopularLogos();
    }
  }

  function movePopularLogo(fromIndex: number, toIndex: number) {
    if (toIndex < 0 || toIndex >= popularLogos.length || fromIndex === toIndex) {
      return;
    }

    const nextLogos = [...popularLogos];
    const [movedLogo] = nextLogos.splice(fromIndex, 1);
    nextLogos.splice(toIndex, 0, movedLogo);
    savePopularOrder(nextLogos);
  }

  function dropPopularLogo(targetId: number) {
    if (!draggingPopularId || draggingPopularId === targetId) {
      setDraggingPopularId(null);
      return;
    }

    const fromIndex = popularLogos.findIndex((logo) => logo.id === draggingPopularId);
    const toIndex = popularLogos.findIndex((logo) => logo.id === targetId);

    if (fromIndex >= 0 && toIndex >= 0) {
      movePopularLogo(fromIndex, toIndex);
    }

    setDraggingPopularId(null);
  }

  function swapPopularCards(targetId: number) {
    if (!swapSourceId) {
      setSwapSourceId(targetId);
      return;
    }

    if (swapSourceId === targetId) {
      setSwapSourceId(null);
      return;
    }

    const fromIndex = popularLogos.findIndex((logo) => logo.id === swapSourceId);
    const toIndex = popularLogos.findIndex((logo) => logo.id === targetId);

    if (fromIndex >= 0 && toIndex >= 0) {
      const nextLogos = [...popularLogos];
      [nextLogos[fromIndex], nextLogos[toIndex]] = [nextLogos[toIndex], nextLogos[fromIndex]];
      savePopularOrder(nextLogos);
    }

    setSwapSourceId(null);
  }

  return (
    <AdminGuard>
      <AdminShell title="Car companies" lead="Search, add, edit, and mark popular companies.">
        <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
          <section className="min-w-0 space-y-5">
            <div className="sticky top-16 z-20 flex flex-col gap-3 rounded-lg border border-border bg-white/95 p-4 shadow-sm backdrop-blur md:flex-row md:items-center md:justify-between">
              <div className="relative min-w-0 flex-1">
                <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <input
                  value={search}
                  onChange={(event) => setSearch(event.target.value)}
                  placeholder="Search by company name"
                  className="h-11 w-full rounded-md border border-border bg-white pl-10 pr-11 text-sm font-semibold outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15"
                />
                {search ? (
                  <button
                    type="button"
                    onClick={() => setSearch("")}
                    className="absolute right-2 top-1/2 grid h-7 w-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                    aria-label="Clear company search"
                  >
                    <X className="h-4 w-4" />
                  </button>
                ) : null}
              </div>
              <button
                type="button"
                onClick={openAddForm}
                className="inline-flex h-11 items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95"
              >
                <Plus className="h-4 w-4" />
                Add company
              </button>
            </div>

            {errorMessage ? (
              <p className="rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm font-semibold text-destructive">
                {errorMessage}
              </p>
            ) : null}

            <div className="flex items-center justify-between gap-4 text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              <span>{isLoading ? "Loading companies" : `${total} companies`}</span>
              <span>{popularLogos.length} popular</span>
            </div>

            {isLoading ? (
              <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
                {Array.from({ length: 12 }).map((_, index) => (
                  <LogoCardSkeleton key={index} />
                ))}
              </div>
            ) : (
              <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
                {logos.map((logo) => (
                  <article
                    key={logo.id}
                    role="button"
                    tabIndex={0}
                    onClick={() => router.push(`/admin/car-models/${logo.slug}`)}
                    onKeyDown={(event) => {
                      if (event.key === "Enter") {
                        router.push(`/admin/car-models/${logo.slug}`);
                      }
                    }}
                    className={`group overflow-hidden rounded-lg border bg-white text-left shadow-sm transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md ${
                      popularIds.has(logo.id)
                        ? "border-primary/40 ring-2 ring-primary/10"
                        : "border-border"
                    }`}
                  >
                    <div className="relative aspect-[4/3] border-b border-border bg-slate-50">
                      <Image
                        src={logo.logo}
                        alt={`${logo.name} logo`}
                        fill
                        sizes="(min-width: 1536px) 220px, (min-width: 1280px) 260px, (min-width: 640px) 50vw, 100vw"
                        className="object-contain p-7 transition-transform duration-300 group-hover:scale-105"
                      />
                      <div className="absolute right-3 top-3 flex gap-2">
                        <button
                          type="button"
                          onClick={(event) => {
                            event.stopPropagation();
                            setPricingLogo(logo);
                          }}
                          className="grid h-9 w-9 place-items-center rounded-md border border-border bg-white/95 text-muted-foreground shadow-sm backdrop-blur transition hover:bg-slate-100 hover:text-foreground"
                          aria-label={`AMC pricing for ${logo.name}`}
                        >
                          <IndianRupee className="h-4 w-4" />
                        </button>
                        <button
                          type="button"
                          onClick={(event) => {
                            event.stopPropagation();
                            openEditForm(logo);
                          }}
                          className="grid h-9 w-9 place-items-center rounded-md border border-border bg-white/95 text-muted-foreground shadow-sm backdrop-blur transition hover:bg-slate-100 hover:text-foreground"
                          aria-label={`Edit ${logo.name}`}
                        >
                          <Edit3 className="h-4 w-4" />
                        </button>
                        <button
                          type="button"
                          onClick={(event) => {
                            event.stopPropagation();
                            setPendingDeleteLogo(logo);
                          }}
                          className="grid h-9 w-9 place-items-center rounded-md border border-destructive/25 bg-white/95 text-destructive shadow-sm backdrop-blur transition hover:bg-destructive/10"
                          aria-label={`Delete ${logo.name}`}
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </div>

                    <div className="p-4">
                      <h2 className="truncate text-lg font-black tracking-tight text-foreground">
                        {logo.name}
                      </h2>
                    </div>

                    <div className="flex items-center border-t border-border px-4 py-3">
                      <label
                        className="inline-flex cursor-pointer items-center gap-2 text-sm font-bold text-muted-foreground transition hover:text-primary"
                        onClick={(event) => event.stopPropagation()}
                      >
                        <input
                          type="checkbox"
                          checked={logo.isPopular}
                          onChange={(event) => updatePopular(logo, event.target.checked)}
                          className="sr-only"
                        />
                        <span
                          className={`relative h-5 w-9 rounded-full border transition ${
                            logo.isPopular
                              ? "border-primary bg-primary"
                              : "border-border bg-slate-200"
                          }`}
                        >
                          <span
                            className={`absolute top-1/2 grid h-4 w-4 -translate-y-1/2 place-items-center rounded-full bg-white shadow-sm transition ${
                              logo.isPopular ? "left-4 text-primary" : "left-0.5 text-slate-400"
                            }`}
                          >
                            <Star
                              className={`h-2.5 w-2.5 ${
                                logo.isPopular ? "fill-current" : "fill-transparent"
                              }`}
                            />
                          </span>
                        </span>
                        Popular
                      </label>
                    </div>
                  </article>
                ))}
              </div>
            )}

            {!isLoading && logos.length === 0 ? (
              <p className="rounded-lg border border-border bg-white px-4 py-8 text-center text-sm font-semibold text-muted-foreground">
                No car companies found.
              </p>
            ) : null}

            {hasMore ? (
              <div ref={loadMoreRef} className="py-2">
                {isLoadingMore ? (
                  <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
                    {Array.from({ length: 4 }).map((_, index) => (
                      <LogoCardSkeleton key={index} />
                    ))}
                  </div>
                ) : null}
              </div>
            ) : null}
          </section>

          <aside className="order-first xl:sticky xl:top-20 xl:order-none xl:self-start">
            <div className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
              <div className="flex items-center justify-between gap-3 border-b border-border bg-slate-100 px-4 py-3">
                <div className="inline-flex items-center gap-2 rounded-md bg-white px-3 py-2 text-sm font-black text-primary shadow-sm">
                  <Star className="h-4 w-4 fill-primary" />
                  Popular companies
                </div>
                <button
                  type="button"
                  onClick={() => setPopularModalOpen(true)}
                  className="grid h-9 w-9 place-items-center rounded-md border border-border bg-white text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                  aria-label="Open popular companies fullscreen"
                >
                  <Maximize2 className="h-4 w-4" />
                </button>
              </div>

              <div className="max-h-[70vh] overflow-y-auto xl:max-h-[calc(100vh-190px)]">
                <div className="space-y-3 p-4">
                  <PopularLogoList
                    logos={popularLogos}
                    draggingPopularId={draggingPopularId}
                    swapSourceId={swapSourceId}
                    onDragStart={setDraggingPopularId}
                    onDrop={dropPopularLogo}
                    onDragEnd={() => setDraggingPopularId(null)}
                    onMove={movePopularLogo}
                    onRemove={(logo) => updatePopular(logo, false)}
                    onSwap={swapPopularCards}
                  />
                </div>
                {popularLogos.length > 0 ? (
                  <div className="sticky bottom-0 border-t border-border bg-white/95 p-4 backdrop-blur">
                    <button
                      type="button"
                      onClick={() => setClearConfirmOpen(true)}
                      className="h-10 w-full rounded-md border border-destructive/25 bg-white px-3 text-xs font-black text-destructive transition hover:bg-destructive/10"
                    >
                      Remove all popular companies
                    </button>
                  </div>
                ) : null}
              </div>
            </div>
          </aside>
        </div>

        {form ? (
          <div className="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-slate-950/45 px-4 py-8">
            <form
              onSubmit={saveLogo}
              className="max-h-full w-full max-w-2xl overflow-y-auto rounded-lg border border-border bg-white p-5 shadow-xl"
            >
              <div className="flex items-start justify-between gap-4">
                <div>
                  <h2 className="text-2xl font-black tracking-tight text-foreground">
                    {form.id ? "Edit company" : "Add company"}
                  </h2>
                  <p className="mt-1 text-sm font-semibold text-muted-foreground">
                    Upload company images and save them in the same shape as the company JSON.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={() => setForm(null)}
                  className="grid h-9 w-9 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                  aria-label="Close company form"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>

              <div className="mt-5">
                <Field label="Name">
                  <input
                    required
                    value={form.name}
                    onChange={(event) => {
                      const name = event.target.value;
                      setForm((current) =>
                        current
                          ? {
                              ...current,
                              name,
                              slug: current.id ? current.slug : toSlug(name),
                            }
                          : current,
                      );
                    }}
                    className="h-11 w-full rounded-md border border-border px-3 text-sm font-semibold outline-none focus:border-primary focus:ring-2 focus:ring-primary/15"
                  />
                </Field>
              </div>

              <div className="mt-4 space-y-4">
                <LogoUploadField
                  label="Company logo"
                  imageUrl={form.logo}
                  isUploading={isUploadingLogo}
                  onChange={uploadLogoImage}
                />
                <label
                  className={`inline-flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2 text-sm font-black transition ${
                    form.isPopular
                      ? "border-primary/35 bg-primary/10 text-primary"
                      : "border-border bg-slate-50 text-foreground hover:border-primary/30"
                  }`}
                >
                  <input
                    type="checkbox"
                    checked={form.isPopular}
                    onChange={(event) =>
                      setForm((current) =>
                        current ? { ...current, isPopular: event.target.checked } : current,
                      )
                    }
                    className="sr-only"
                  />
                  <span
                    className={`relative h-5 w-9 rounded-full border transition ${
                      form.isPopular ? "border-primary bg-primary" : "border-border bg-slate-200"
                    }`}
                  >
                    <span
                      className={`absolute top-1/2 grid h-4 w-4 -translate-y-1/2 place-items-center rounded-full bg-white shadow-sm transition ${
                        form.isPopular ? "left-4 text-primary" : "left-0.5 text-slate-400"
                      }`}
                    >
                      <Star
                        className={`h-2.5 w-2.5 ${
                          form.isPopular ? "fill-current" : "fill-transparent"
                        }`}
                      />
                    </span>
                  </span>
                  <span>
                    <span className="block leading-none">Mark as popular</span>
                  </span>
                </label>
              </div>

              <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                <button
                  type="button"
                  onClick={() => setForm(null)}
                  className="h-10 rounded-md border border-border px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSaving || isUploadingLogo}
                  className="inline-flex h-10 items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95 disabled:opacity-60"
                >
                  {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {form.id ? "Save changes" : "Add company"}
                </button>
              </div>
            </form>
          </div>
        ) : null}

        {pricingLogo ? (
          <AmcPricingDialog logo={pricingLogo} onClose={() => setPricingLogo(null)} />
        ) : null}

        {popularModalOpen ? (
          <div className="fixed inset-0 z-50 overflow-hidden bg-slate-950/55 p-4 backdrop-blur-sm">
            <div className="mx-auto flex h-full max-w-6xl flex-col overflow-hidden rounded-lg border border-border bg-white shadow-2xl">
              <div className="flex items-center justify-between gap-4 border-b border-border bg-slate-100 px-5 py-4">
                <div>
                  <p className="inline-flex items-center gap-2 rounded-md bg-white px-3 py-2 text-sm font-black text-primary shadow-sm">
                    <Star className="h-4 w-4 fill-primary" />
                    Popular companies
                  </p>
                  <p className="mt-2 text-sm font-semibold text-muted-foreground">
                    Drag cards, use arrows, or swap positions directly.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={() => setPopularModalOpen(false)}
                  className="grid h-10 w-10 place-items-center rounded-md border border-border bg-white text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                  aria-label="Close popular companies fullscreen"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              <div className="flex-1 overflow-y-auto">
                <div className="p-5">
                  <PopularLogoList
                    logos={popularLogos}
                    draggingPopularId={draggingPopularId}
                    swapSourceId={swapSourceId}
                    onDragStart={setDraggingPopularId}
                    onDrop={dropPopularLogo}
                    onDragEnd={() => setDraggingPopularId(null)}
                    onMove={movePopularLogo}
                    onRemove={(logo) => updatePopular(logo, false)}
                    onSwap={swapPopularCards}
                    large
                  />
                </div>
                {popularLogos.length > 0 ? (
                  <div className="sticky bottom-0 border-t border-border bg-white/95 p-5 backdrop-blur">
                    <button
                      type="button"
                      onClick={() => setClearConfirmOpen(true)}
                      className="h-11 w-full rounded-md border border-destructive/25 bg-white px-3 text-sm font-black text-destructive transition hover:bg-destructive/10"
                    >
                      Remove all popular companies
                    </button>
                  </div>
                ) : null}
              </div>
            </div>
          </div>
        ) : null}

        {clearConfirmOpen ? (
          <div className="fixed inset-0 z-[60] grid place-items-center bg-slate-950/55 px-4 py-8 backdrop-blur-sm">
            <div className="w-full max-w-md rounded-lg border border-border bg-white p-5 shadow-2xl">
              <div className="grid h-12 w-12 place-items-center rounded-md bg-destructive/10 text-destructive">
                <X className="h-6 w-6" />
              </div>
              <h2 className="mt-5 text-2xl font-black tracking-tight text-foreground">
                Remove all popular companies?
              </h2>
              <p className="mt-2 text-sm font-semibold leading-6 text-muted-foreground">
                This will clear every company from the popular list. You can mark them popular again
                from the company cards later.
              </p>
              <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                <button
                  type="button"
                  onClick={() => setClearConfirmOpen(false)}
                  className="h-10 rounded-md border border-border px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={clearPopularCompanies}
                  className="h-10 rounded-md bg-destructive px-4 text-sm font-black text-destructive-foreground transition hover:brightness-95"
                >
                  Remove all
                </button>
              </div>
            </div>
          </div>
        ) : null}

        {pendingDeleteLogo ? (
          <div className="fixed inset-0 z-[60] grid place-items-center bg-slate-950/55 px-4 py-8 backdrop-blur-sm">
            <div className="w-full max-w-md rounded-lg border border-border bg-white p-5 shadow-2xl">
              <div className="grid h-12 w-12 place-items-center rounded-md bg-destructive/10 text-destructive">
                <Trash2 className="h-6 w-6" />
              </div>
              <h2 className="mt-5 text-2xl font-black tracking-tight text-foreground">
                Delete {pendingDeleteLogo.name}?
              </h2>
              <p className="mt-2 text-sm font-semibold leading-6 text-muted-foreground">
                This will delete the company and all car models saved under it.
              </p>
              <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                <button
                  type="button"
                  onClick={() => setPendingDeleteLogo(null)}
                  disabled={isDeletingId === pendingDeleteLogo.id}
                  className="h-10 rounded-md border border-border px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground disabled:opacity-60"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={() => deleteLogo(pendingDeleteLogo)}
                  disabled={isDeletingId === pendingDeleteLogo.id}
                  className="inline-flex h-10 items-center justify-center gap-2 rounded-md bg-destructive px-4 text-sm font-black text-destructive-foreground transition hover:brightness-95 disabled:opacity-60"
                >
                  {isDeletingId === pendingDeleteLogo.id ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : null}
                  Delete company
                </button>
              </div>
            </div>
          </div>
        ) : null}
      </AdminShell>
    </AdminGuard>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
        {label}
      </span>
      {children}
    </label>
  );
}

function getAmcPriceKey(price: Pick<AdminAmcPackagePrice, "packageId" | "tierId">) {
  return `${price.tierId}:${price.packageId}`;
}

function AmcPricingDialog({ logo, onClose }: { logo: AdminCarLogo; onClose: () => void }) {
  const [activeVehicleType, setActiveVehicleType] = useState<"car" | "ev-car">("car");
  const [prices, setPrices] = useState<AdminAmcPackagePrice[]>([]);
  const [tiers, setTiers] = useState<AdminVehicleTier[]>([]);
  const [activeTierId, setActiveTierId] = useState<number | null>(null);
  const [locations, setLocations] = useState<AdminLocation[]>([]);
  const [priceDrafts, setPriceDrafts] = useState<Record<string, string>>({});
  const [discountDrafts, setDiscountDrafts] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [locationMessage, setLocationMessage] = useState("");

  const loadPricing = useCallback(async () => {
    setIsLoading(true);
    setErrorMessage("");
    setLocationMessage("");

    try {
      let nextLocationMessage = "";
      const [priceData, activeLocations] = await Promise.all([
        adminRequest<{ tiers: AdminVehicleTier[]; prices: AdminAmcPackagePrice[] }>(
          `/api/admin/car-logos/${logo.id}/amc-prices?vehicleType=${activeVehicleType}`,
        ),
        loadActiveAdminLocations().catch((error) => {
          nextLocationMessage =
            error instanceof Error
              ? `Location prices could not be loaded: ${error.message}`
              : "Location prices could not be loaded.";
          return [];
        }),
      ]);

      setTiers(priceData.tiers);
      setPrices(priceData.prices);
      setActiveTierId((currentTierId) =>
        currentTierId && priceData.tiers.some((tier) => tier.id === currentTierId)
          ? currentTierId
          : (priceData.tiers[0]?.id ?? null),
      );
      setPriceDrafts(
        Object.fromEntries(
          priceData.prices.map((price) => [getAmcPriceKey(price), String(price.basePrice)]),
        ),
      );
      setDiscountDrafts(
        Object.fromEntries(
          priceData.prices.map((price) => [
            getAmcPriceKey(price),
            String(price.discountPercentage ?? 0),
          ]),
        ),
      );
      setLocations(activeLocations);
      setLocationMessage(
        nextLocationMessage ||
          (activeLocations.length === 0
            ? "No active locations found. Add or activate locations to preview location prices."
            : ""),
      );
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not load AMC pricing");
    } finally {
      setIsLoading(false);
    }
  }, [activeVehicleType, logo.id]);

  useEffect(() => {
    loadPricing();
  }, [loadPricing]);

  async function savePrices() {
    setIsSaving(true);
    setErrorMessage("");

    try {
      await adminRequest(
        `/api/admin/car-logos/${logo.id}/amc-prices?vehicleType=${activeVehicleType}`,
        {
          method: "PUT",
          body: JSON.stringify({
            prices: prices.map((price) => ({
              tierId: price.tierId,
              packageId: price.packageId,
              basePrice: Number(priceDrafts[getAmcPriceKey(price)] || 0),
              discountPercentage: Number(discountDrafts[getAmcPriceKey(price)] || 0),
            })),
          }),
        },
      );
      await loadPricing();
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not save AMC pricing");
    } finally {
      setIsSaving(false);
    }
  }

  const activeTier = tiers.find((tier) => tier.id === activeTierId) ?? tiers[0];
  const activePrices = activeTier ? prices.filter((price) => price.tierId === activeTier.id) : [];

  return (
    <div className="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-slate-950/45 px-4 py-8">
      <div className="max-h-full w-full max-w-6xl overflow-hidden rounded-lg border border-border bg-white shadow-xl">
        <div className="flex items-start justify-between gap-4 border-b border-border p-5">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.14em] text-primary">
              AMC pricing
            </p>
            <h2 className="mt-1 text-2xl font-black tracking-tight text-foreground">{logo.name}</h2>
            <div className="mt-3 inline-flex rounded-md border border-border bg-slate-50 p-1">
              {(["car", "ev-car"] as const).map((vehicleType) => (
                <button
                  key={vehicleType}
                  type="button"
                  onClick={() => {
                    setActiveVehicleType(vehicleType);
                    setActiveTierId(null);
                  }}
                  className={`w-20 rounded border px-3 py-1.5 text-xs font-black transition ${
                    activeVehicleType === vehicleType
                      ? "border-primary bg-primary text-primary-foreground"
                      : "border-slate-300 bg-white text-muted-foreground hover:border-slate-400 hover:text-foreground"
                  }`}
                >
                  {vehicleType === "car" ? "Car" : "EV Car"}
                </button>
              ))}
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="grid h-9 w-9 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
            aria-label="Close AMC pricing"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="max-h-[calc(100vh-180px)] space-y-5 overflow-y-auto p-5">
          {errorMessage ? (
            <p className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm font-bold text-destructive">
              {errorMessage}
            </p>
          ) : null}

          {isLoading ? (
            <p className="text-sm font-bold text-muted-foreground">Loading AMC pricing...</p>
          ) : tiers.length === 0 || prices.length === 0 ? (
            <p className="rounded-md border border-dashed border-border px-4 py-8 text-center text-sm font-bold text-muted-foreground">
              No {activeVehicleType === "car" ? "car" : "EV car"} tiers or AMC packages available.
            </p>
          ) : (
            <>
              <div className="flex gap-2 overflow-x-auto rounded-lg border border-border bg-slate-50 p-2">
                {tiers.map((tier) => (
                  <button
                    type="button"
                    key={tier.id}
                    onClick={() => setActiveTierId(tier.id)}
                    className={`w-44 shrink-0 rounded-md border px-4 py-2 text-sm font-black transition ${
                      activeTier?.id === tier.id
                        ? "border-primary bg-primary text-primary-foreground shadow-sm"
                        : "border-slate-300 bg-white text-muted-foreground hover:border-slate-400 hover:text-foreground"
                    }`}
                  >
                    Tier {tier.tierLevel} - {tier.name}
                  </button>
                ))}
              </div>

              <section className="rounded-lg border border-border bg-slate-50 p-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <h3 className="text-sm font-black uppercase tracking-[0.14em] text-foreground">
                      Base AMC package prices for {activeTier?.name}
                    </h3>
                    <p className="mt-1 text-xs font-semibold text-muted-foreground">
                      These values are unique to this car company and tier. Location rows are
                      calculated from the selected tier base price.
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={savePrices}
                    disabled={isSaving}
                    className="inline-flex h-10 items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground disabled:opacity-60"
                  >
                    {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                    Save base prices
                  </button>
                </div>

                <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                  {activePrices.map((price) => (
                    <div
                      key={`${price.tierId}-${price.packageId}`}
                      className="rounded-md border border-border bg-white p-3"
                    >
                      <span className="block text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
                        {price.name}
                      </span>
                      <span className="mt-1 block text-[11px] font-bold text-muted-foreground">
                        {price.validityMonths} months
                      </span>
                      <div className="mt-2 grid grid-cols-2 gap-2">
                        <label>
                          <span className="text-[10px] font-black uppercase tracking-[0.1em] text-muted-foreground">
                            Base price
                          </span>
                          <input
                            type="number"
                            min="0"
                            step="1"
                            value={priceDrafts[getAmcPriceKey(price)] ?? "0"}
                            onChange={(event) =>
                              setPriceDrafts((current) => ({
                                ...current,
                                [getAmcPriceKey(price)]: event.target.value,
                              }))
                            }
                            className="mt-1 h-10 w-full rounded-md border border-border px-3 text-sm font-black outline-none focus:border-primary focus:ring-2 focus:ring-primary/15"
                          />
                        </label>
                        <label>
                          <span className="text-[10px] font-black uppercase tracking-[0.1em] text-muted-foreground">
                            Discount %
                          </span>
                          <input
                            type="number"
                            min="0"
                            max="100"
                            step="0.01"
                            value={discountDrafts[getAmcPriceKey(price)] ?? "0"}
                            onChange={(event) =>
                              setDiscountDrafts((current) => ({
                                ...current,
                                [getAmcPriceKey(price)]: event.target.value,
                              }))
                            }
                            className="mt-1 h-10 w-full rounded-md border border-border px-3 text-sm font-black outline-none focus:border-primary focus:ring-2 focus:ring-primary/15"
                          />
                        </label>
                      </div>
                    </div>
                  ))}
                </div>
              </section>

              <section>
                <h3 className="text-sm font-black uppercase tracking-[0.14em] text-foreground">
                  Location calculated prices for {activeTier?.name}
                </h3>
                {locationMessage ? (
                  <p className="mt-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-bold text-amber-800">
                    {locationMessage}
                  </p>
                ) : null}
                <div className="mt-3 max-h-[420px] overflow-auto rounded-lg border border-border bg-white">
                  <table className="w-full min-w-[900px] text-left text-sm">
                    <thead className="sticky top-0 z-10 bg-slate-100 text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
                      <tr>
                        <th className="sticky left-0 z-20 bg-slate-100 px-3 py-3">Location</th>
                        {activePrices.map((price) => (
                          <th key={`${price.tierId}-${price.packageId}`} className="px-3 py-3">
                            {price.name}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {locations.length === 0 ? (
                        <tr>
                          <td
                            colSpan={activePrices.length + 1}
                            className="px-3 py-6 text-center text-sm font-bold text-muted-foreground"
                          >
                            Location price preview is unavailable until active locations are loaded.
                          </td>
                        </tr>
                      ) : (
                        locations.map((location) => (
                          <tr key={location.id}>
                            <td className="sticky left-0 bg-white px-3 py-3 font-black text-foreground">
                              {location.name}
                            </td>
                            {activePrices.map((price) => (
                              <td
                                key={`${price.tierId}-${price.packageId}`}
                                className="px-3 py-3 font-black"
                              >
                                {formatCurrency(
                                  getAdjustedPrice(
                                    Number(priceDrafts[getAmcPriceKey(price)] || 0),
                                    Number(discountDrafts[getAmcPriceKey(price)] || 0),
                                    location,
                                  ),
                                )}
                              </td>
                            ))}
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
              </section>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function LogoCardSkeleton() {
  return (
    <div className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
      <div className="relative aspect-[4/3] overflow-hidden border-b border-border bg-slate-100">
        <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.35s_infinite] bg-gradient-to-r from-transparent via-white/70 to-transparent" />
        <div className="absolute inset-7 rounded-md bg-slate-200/80" />
      </div>
      <div className="space-y-3 p-4">
        <div className="relative h-5 overflow-hidden rounded bg-slate-200">
          <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.35s_infinite] bg-gradient-to-r from-transparent via-white/70 to-transparent" />
        </div>
      </div>
      <div className="flex items-center justify-between border-t border-border px-4 py-3">
        <div className="relative h-5 w-24 overflow-hidden rounded bg-slate-200">
          <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.35s_infinite] bg-gradient-to-r from-transparent via-white/70 to-transparent" />
        </div>
        <div className="relative h-8 w-20 overflow-hidden rounded bg-slate-200">
          <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.35s_infinite] bg-gradient-to-r from-transparent via-white/70 to-transparent" />
        </div>
      </div>
    </div>
  );
}

function PopularLogoList({
  logos,
  draggingPopularId,
  swapSourceId,
  onDragStart,
  onDrop,
  onDragEnd,
  onMove,
  onRemove,
  onSwap,
  large = false,
}: {
  logos: AdminCarLogo[];
  draggingPopularId: number | null;
  swapSourceId: number | null;
  onDragStart: (id: number) => void;
  onDrop: (id: number) => void;
  onDragEnd: () => void;
  onMove: (fromIndex: number, toIndex: number) => void;
  onRemove: (logo: AdminCarLogo) => void;
  onSwap: (id: number) => void;
  large?: boolean;
}) {
  if (logos.length === 0) {
    return (
      <p className="text-sm font-semibold text-muted-foreground">
        Mark companies as popular to show them here.
      </p>
    );
  }

  return (
    <div className={large ? "grid gap-4 md:grid-cols-2 xl:grid-cols-3" : "space-y-3"}>
      {logos.map((logo, index) => (
        <div
          key={logo.id}
          draggable
          onDragStart={() => onDragStart(logo.id)}
          onDragOver={(event) => event.preventDefault()}
          onDrop={() => onDrop(logo.id)}
          onDragEnd={onDragEnd}
          className={`rounded-md border bg-white p-3 transition ${
            swapSourceId === logo.id
              ? "border-primary bg-primary/5 ring-2 ring-primary/15"
              : draggingPopularId === logo.id
                ? "border-primary/50 opacity-60"
                : "border-border hover:border-primary/30"
          }`}
        >
          <div className={large ? "flex flex-col gap-3" : "flex items-center gap-3"}>
            <div className="flex items-center gap-3">
              <div className="grid h-9 w-6 shrink-0 place-items-center text-muted-foreground">
                <GripVertical className="h-4 w-4" />
              </div>
              <div
                className={`relative shrink-0 overflow-hidden rounded-md border border-border bg-slate-50 ${
                  large ? "h-28 w-28" : "h-20 w-20"
                }`}
              >
                <Image
                  src={logo.logo}
                  alt={`${logo.name} logo`}
                  fill
                  sizes={large ? "112px" : "80px"}
                  className="object-contain p-3"
                />
              </div>
            </div>
            <div className="min-w-0 flex-1">
              <p className="truncate text-base font-black text-foreground">{logo.name}</p>
              <p className="mt-1 text-xs font-semibold text-muted-foreground">
                Position {index + 1}
              </p>
            </div>
          </div>

          <div className="mt-3 flex items-center justify-between gap-2 border-t border-border pt-3">
            <div className="flex gap-1">
              <button
                type="button"
                onClick={() => onMove(index, index - 1)}
                disabled={index === 0}
                className="grid h-8 w-8 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
                aria-label={`Move ${logo.name} up`}
              >
                <ArrowUp className="h-4 w-4" />
              </button>
              <button
                type="button"
                onClick={() => onMove(index, index + 1)}
                disabled={index === logos.length - 1}
                className="grid h-8 w-8 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
                aria-label={`Move ${logo.name} down`}
              >
                <ArrowDown className="h-4 w-4" />
              </button>
            </div>
            <div className="flex gap-1">
              <button
                type="button"
                onClick={() => onSwap(logo.id)}
                className={`h-8 rounded-md border px-2 text-xs font-black transition ${
                  swapSourceId && swapSourceId !== logo.id
                    ? "border-primary bg-primary text-primary-foreground"
                    : swapSourceId === logo.id
                      ? "border-primary/30 bg-primary/10 text-primary"
                      : "border-border text-muted-foreground hover:bg-slate-100 hover:text-foreground"
                }`}
              >
                {swapSourceId && swapSourceId !== logo.id
                  ? "Swap here"
                  : swapSourceId === logo.id
                    ? "Selected"
                    : "Swap"}
              </button>
              <button
                type="button"
                onClick={() => onRemove(logo)}
                className="grid h-8 w-8 place-items-center rounded-md border border-border text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                aria-label={`Remove ${logo.name} from popular`}
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function LogoUploadField({
  label,
  imageUrl,
  isUploading,
  onChange,
}: {
  label: string;
  imageUrl: string;
  isUploading: boolean;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
}) {
  const previewUrl = toStorageUrl(imageUrl);

  return (
    <div>
      <span className="mb-1.5 block text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
        {label}
      </span>
      <div className="grid gap-3 rounded-md border border-border bg-slate-50 p-3 sm:grid-cols-[120px_minmax(0,1fr)] sm:items-center">
        <div className="relative h-24 overflow-hidden rounded-md border border-border bg-white">
          {previewUrl ? (
            <Image src={previewUrl} alt={`${label} preview`} fill className="object-contain p-3" />
          ) : (
            <div className="grid h-full place-items-center text-muted-foreground">
              <ImagePlus className="h-6 w-6" />
            </div>
          )}
        </div>
        <label className="flex min-w-0 cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-border bg-white px-4 py-5 text-center transition hover:border-primary/50 hover:bg-primary/5">
          <input type="file" accept="image/*" onChange={onChange} className="sr-only" />
          <span className="inline-flex items-center gap-2 text-sm font-black text-foreground">
            {isUploading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <ImagePlus className="h-4 w-4" />
            )}
            {isUploading ? "Uploading..." : previewUrl ? "Replace image" : "Upload image"}
          </span>
          <span className="mt-1 text-xs font-semibold text-muted-foreground">
            PNG, JPG, WEBP, or SVG
          </span>
        </label>
      </div>
    </div>
  );
}
