"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import {
  ArrowDown,
  ArrowUp,
  ChevronDown,
  ExternalLink,
  LogOut,
  Plus,
  Save,
  Trash2,
  Upload,
} from "lucide-react";
import {
  DEFAULT_THEME,
  SERVICE_ICONS,
  type Client,
  type Faq,
  type Milestone,
  type ProcessStep,
  type Project,
  type Service,
  type ServiceIcon,
  type SiteContent,
  type Stat,
  type Testimonial,
  type ThemeColors,
  type SiteTheme,
} from "@/lib/contentTypes";

/* ------------------------- Elemen bentuk umum ------------------------ */

const inputCls =
  "w-full rounded-xl border border-line bg-panel px-3.5 py-2.5 text-sm text-fg outline-none transition-colors placeholder:text-mist/60 focus:border-line-2";

function Field({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block font-accent text-[11px] tracking-wide text-mist uppercase">
        {label}
      </span>
      {children}
    </label>
  );
}

function ImageField({
  label,
  value,
  onChange,
}: {
  label: string;
  value?: string;
  onChange: (path: string) => void;
}) {
  const [busy, setBusy] = useState(false);

  async function upload(file: File) {
    setBusy(true);
    try {
      const form = new FormData();
      form.append("file", file);
      const res = await fetch("/api/admin/upload", { method: "POST", body: form });
      const data = await res.json();
      if (!res.ok) {
        alert(data.error ?? "Upload gagal.");
        return;
      }
      onChange(data.path);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div>
      <span className="mb-1.5 block font-accent text-[11px] tracking-wide text-mist uppercase">
        {label}
      </span>
      <div className="flex items-center gap-3">
        {value ? (
          <Image
            src={value}
            alt=""
            width={72}
            height={48}
            unoptimized
            className="h-12 w-[72px] shrink-0 rounded-lg border border-line object-cover"
          />
        ) : (
          <span className="grid h-12 w-[72px] shrink-0 place-items-center rounded-lg border border-dashed border-line text-[10px] text-mist">
            kosong
          </span>
        )}
        <input
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          placeholder="/projects/contoh.jpg"
          className={inputCls}
        />
        <label className="glow-border inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-full bg-panel px-3.5 py-2 text-xs font-medium text-fg transition-colors hover:bg-panel-strong">
          <Upload size={12} />
          {busy ? "Mengunggah…" : "Upload"}
          <input
            type="file"
            accept="image/png,image/jpeg,image/webp,image/svg+xml"
            className="hidden"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) upload(f);
              e.target.value = "";
            }}
          />
        </label>
      </div>
    </div>
  );
}

function StringList({
  items,
  onChange,
  placeholder,
}: {
  items: string[];
  onChange: (items: string[]) => void;
  placeholder?: string;
}) {
  return (
    <div className="space-y-2">
      {items.map((item, i) => (
        <div key={i} className="flex gap-2">
          <input
            value={item}
            onChange={(e) => {
              const next = [...items];
              next[i] = e.target.value;
              onChange(next);
            }}
            placeholder={placeholder}
            className={inputCls}
          />
          <button
            type="button"
            onClick={() => onChange(items.filter((_, j) => j !== i))}
            className="glow-border grid size-10 shrink-0 place-items-center rounded-xl text-mist transition-colors hover:text-red-400"
            aria-label="Hapus"
          >
            <Trash2 size={14} />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() => onChange([...items, ""])}
        className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
      >
        <Plus size={13} /> Tambah
      </button>
    </div>
  );
}

function ListRow({
  children,
  onRemove,
  onUp,
  onDown,
}: {
  children: React.ReactNode;
  onRemove: () => void;
  onUp?: () => void;
  onDown?: () => void;
}) {
  return (
    <div className="rounded-2xl border border-line bg-ink/60 p-4">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1 space-y-3">{children}</div>
        <div className="flex shrink-0 flex-col gap-1.5">
          {onUp && (
            <button
              type="button"
              onClick={onUp}
              className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-fg"
              aria-label="Naik"
            >
              <ArrowUp size={13} />
            </button>
          )}
          {onDown && (
            <button
              type="button"
              onClick={onDown}
              className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-fg"
              aria-label="Turun"
            >
              <ArrowDown size={13} />
            </button>
          )}
          <button
            type="button"
            onClick={onRemove}
            className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-red-400"
            aria-label="Hapus"
          >
            <Trash2 size={13} />
          </button>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------ Editor ------------------------------- */

const TABS = [
  { id: "proyek", label: "Proyek" },
  { id: "klien", label: "Klien" },
  { id: "layanan", label: "Layanan" },
  { id: "testimoni", label: "Testimoni" },
  { id: "faq", label: "FAQ" },
  { id: "beranda", label: "Beranda" },
  { id: "tema", label: "Tema" },
  { id: "kontak", label: "Kontak" },
] as const;

type TabId = (typeof TABS)[number]["id"];

export default function AdminApp({
  initialContent,
}: {
  initialContent: SiteContent;
}) {
  const router = useRouter();
  const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [content, setContent] = useState<SiteContent>(initialContent);
  const [tab, setTab] = useState<TabId>("proyek");
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState<string | null>(null);
  const [openProject, setOpenProject] = useState<number | null>(null);

  function showToast(message: string) {
    setToast(message);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 3000);
  }

  async function save() {
    setSaving(true);
    try {
      const res = await fetch("/api/admin/content", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(content),
      });
      const data = await res.json();
      if (!res.ok) {
        alert(data.error ?? "Gagal menyimpan.");
        return;
      }
      showToast("Perubahan tersimpan ✓ — buka situs untuk melihat hasilnya.");
      // Muat ulang data server agar (mis.) warna tema dari tab Tema langsung aktif.
      router.refresh();
    } catch {
      alert("Tidak dapat menghubungi server.");
    } finally {
      setSaving(false);
    }
  }

  async function logout() {
    await fetch("/api/admin/logout", { method: "POST" });
    router.refresh();
  }

  /* --------------------------- Helper update -------------------------- */

  const patch = <K extends keyof SiteContent>(key: K, value: SiteContent[K]) =>
    setContent((c) => ({ ...c, [key]: value }));

  function move<T>(arr: T[], i: number, dir: -1 | 1): T[] {
    const j = i + dir;
    if (j < 0 || j >= arr.length) return arr;
    const next = [...arr];
    [next[i], next[j]] = [next[j], next[i]];
    return next;
  }

  /* ------------------------------ Tab ------------------------------ */

  const tabBody = () => {
    switch (tab) {
      case "proyek":
        return <ProjectsTab content={content} patch={patch} openIdx={openProject} setOpenIdx={setOpenProject} move={move} />;
      case "klien":
        return <ClientsTab content={content} patch={patch} move={move} />;
      case "layanan":
        return <ServicesTab content={content} patch={patch} move={move} />;
      case "testimoni":
        return <TestimonialsTab content={content} patch={patch} move={move} />;
      case "faq":
        return <FaqTab content={content} patch={patch} move={move} />;
      case "beranda":
        return <HomeTab content={content} patch={patch} />;
      case "tema":
        return <ThemeTab content={content} patch={patch} />;
      case "kontak":
        return <ContactTab content={content} patch={patch} />;
    }
  };

  return (
    <main className="min-h-screen bg-ink text-fg">
      {/* Header */}
      <header className="sticky top-0 z-20 border-b border-line bg-ink/90 backdrop-blur-xl">
        <div className="mx-auto flex max-w-5xl items-center justify-between gap-4 px-5 py-4">
          <div className="flex items-center gap-3">
            <Image
              src="/logo-velo.png"
              alt="Logo Velo Teknologi"
              width={300}
              height={160}
              className="h-8 w-auto"
            />
            <span className="hidden text-sm font-semibold sm:inline">CMS</span>
          </div>
          <div className="flex items-center gap-2.5">
            <a
              href="/"
              target="_blank"
              className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
            >
              <ExternalLink size={12} />
              Lihat Situs
            </a>
            <button
              onClick={logout}
              className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
            >
              <LogOut size={12} />
              Keluar
            </button>
          </div>
        </div>
      </header>

      <div className="mx-auto max-w-5xl px-5 py-8">
        {/* Tab */}
        <nav className="mb-8 flex flex-wrap gap-2">
          {TABS.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`rounded-full px-4.5 py-2 text-sm font-medium transition-colors ${
                tab === t.id
                  ? "bg-cta text-cta-ink"
                  : "glow-border text-fog hover:text-fg"
              }`}
            >
              {t.label}
            </button>
          ))}
        </nav>

        {tabBody()}

        {/* Bar simpan */}
        <div className="sticky bottom-5 mt-10 flex justify-end">
          <button
            onClick={save}
            disabled={saving}
            className="inline-flex items-center gap-2 rounded-full bg-cta px-6 py-3 text-sm font-semibold text-cta-ink shadow-[0_0_36px_rgba(255,255,255,0.2)] transition-all hover:shadow-[0_0_48px_rgba(255,255,255,0.3)] disabled:opacity-50"
          >
            <Save size={15} />
            {saving ? "Menyimpan…" : "Simpan Perubahan"}
          </button>
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <div className="fixed right-5 bottom-5 z-50 rounded-2xl border border-line bg-surface px-5 py-3.5 text-sm text-fg shadow-2xl">
          {toast}
        </div>
      )}
    </main>
  );
}

/* ----------------------------- Tab: Proyek --------------------------- */

function ProjectsTab({
  content,
  patch,
  openIdx,
  setOpenIdx,
  move,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
  openIdx: number | null;
  setOpenIdx: (i: number | null) => void;
  move: <T>(arr: T[], i: number, dir: -1 | 1) => T[];
}) {
  const projects = content.projects;

  const update = (i: number, p: Partial<Project>) => {
    const next = [...projects];
    next[i] = { ...next[i], ...p };
    patch("projects", next);
  };

  const add = () => {
    patch("projects", [
      ...projects,
      {
        title: "Proyek Baru",
        client: "",
        type: "Aplikasi Web",
        description: "",
        tone: projects.length % 6,
      },
    ]);
    setOpenIdx(projects.length);
  };

  const remove = (i: number) => {
    if (!confirm(`Hapus proyek "${projects[i].title}"?`)) return;
    patch("projects", projects.filter((_, j) => j !== i));
    setOpenIdx(null);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm text-mist">{projects.length} proyek</p>
        <button
          onClick={add}
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Proyek
        </button>
      </div>

      {projects.map((p, i) => {
        const open = openIdx === i;
        return (
          <div key={i} className="rounded-2xl border border-line bg-ink/60">
            <div className="flex items-center gap-3 p-3">
              {p.image ? (
                <Image
                  src={p.image}
                  alt=""
                  width={64}
                  height={44}
                  unoptimized
                  className="h-11 w-16 shrink-0 rounded-lg border border-line object-cover grayscale"
                />
              ) : (
                <span className="h-11 w-16 shrink-0 rounded-lg border border-dashed border-line" />
              )}
              <button
                onClick={() => setOpenIdx(open ? null : i)}
                className="min-w-0 flex-1 text-left"
              >
                <p className="truncate text-sm font-medium text-fg">
                  {p.title || "(tanpa judul)"}
                </p>
                <p className="truncate text-xs text-mist">
                  {p.client} · {p.type}
                </p>
              </button>
              <div className="flex shrink-0 items-center gap-1.5">
                <button
                  onClick={() => patch("projects", move(projects, i, -1))}
                  disabled={i === 0}
                  className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-fg disabled:opacity-30"
                  aria-label="Naik"
                >
                  <ArrowUp size={13} />
                </button>
                <button
                  onClick={() => patch("projects", move(projects, i, 1))}
                  disabled={i === projects.length - 1}
                  className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-fg disabled:opacity-30"
                  aria-label="Turun"
                >
                  <ArrowDown size={13} />
                </button>
                <button
                  onClick={() => setOpenIdx(open ? null : i)}
                  className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-fg"
                  aria-label="Buka"
                >
                  <ChevronDown
                    size={13}
                    className={`transition-transform ${open ? "rotate-180" : ""}`}
                  />
                </button>
                <button
                  onClick={() => remove(i)}
                  className="glow-border grid size-8 place-items-center rounded-lg text-mist transition-colors hover:text-red-400"
                  aria-label="Hapus"
                >
                  <Trash2 size={13} />
                </button>
              </div>
            </div>

            {open && (
              <div className="space-y-3 border-t border-line p-4">
                <Field label="Judul">
                  <input
                    value={p.title}
                    onChange={(e) => update(i, { title: e.target.value })}
                    className={inputCls}
                  />
                </Field>
                <div className="grid gap-3 sm:grid-cols-2">
                  <Field label="Klien / Instansi">
                    <input
                      value={p.client}
                      onChange={(e) => update(i, { client: e.target.value })}
                      className={inputCls}
                    />
                  </Field>
                  <Field label="Tipe">
                    <input
                      value={p.type}
                      onChange={(e) => update(i, { type: e.target.value })}
                      className={inputCls}
                    />
                  </Field>
                </div>
                <Field label="Deskripsi">
                  <textarea
                    value={p.description}
                    onChange={(e) => update(i, { description: e.target.value })}
                    rows={3}
                    className={inputCls}
                  />
                </Field>
                <ImageField
                  label="Screenshot"
                  value={p.image}
                  onChange={(path) => update(i, { image: path })}
                />
                <Field label="Tone Placeholder (0–5)">
                  <input
                    type="number"
                    min={0}
                    max={5}
                    value={p.tone}
                    onChange={(e) => update(i, { tone: Number(e.target.value) })}
                    className={inputCls}
                  />
                </Field>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

/* ----------------------------- Tab: Klien ---------------------------- */

function ClientsTab({
  content,
  patch,
  move,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
  move: <T>(arr: T[], i: number, dir: -1 | 1) => T[];
}) {
  const clients = content.clients;
  const update = (i: number, c: Partial<Client>) => {
    const next = [...clients];
    next[i] = { ...next[i], ...c };
    patch("clients", next);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm text-mist">{clients.length} klien</p>
        <button
          onClick={() => patch("clients", [...clients, { name: "Klien Baru" }])}
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Klien
        </button>
      </div>

      {clients.map((c, i) => (
        <ListRow
          key={i}
          onRemove={() => patch("clients", clients.filter((_, j) => j !== i))}
          onUp={i > 0 ? () => patch("clients", move(clients, i, -1)) : undefined}
          onDown={
            i < clients.length - 1
              ? () => patch("clients", move(clients, i, 1))
              : undefined
          }
        >
          <Field label="Nama">
            <input
              value={c.name}
              onChange={(e) => update(i, { name: e.target.value })}
              className={inputCls}
            />
          </Field>
          <ImageField
            label="Logo (opsional — tanpa logo tampil sebagai ikon)"
            value={c.logo}
            onChange={(path) => update(i, { logo: path })}
          />
        </ListRow>
      ))}
    </div>
  );
}

/* ---------------------------- Tab: Layanan --------------------------- */

function ServicesTab({
  content,
  patch,
  move,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
  move: <T>(arr: T[], i: number, dir: -1 | 1) => T[];
}) {
  const { services, processSteps } = content;
  const updateService = (i: number, s: Partial<Service>) => {
    const next = [...services];
    next[i] = { ...next[i], ...s };
    patch("services", next);
  };
  const updateStep = (i: number, s: Partial<ProcessStep>) => {
    const next = [...processSteps];
    next[i] = { ...next[i], ...s };
    patch("processSteps", next);
  };

  return (
    <div className="space-y-10">
      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-fg">Layanan Utama</h3>
        {services.map((s, i) => (
          <ListRow
            key={i}
            onRemove={() => patch("services", services.filter((_, j) => j !== i))}
            onUp={i > 0 ? () => patch("services", move(services, i, -1)) : undefined}
            onDown={
              i < services.length - 1
                ? () => patch("services", move(services, i, 1))
                : undefined
            }
          >
            <div className="grid gap-3 sm:grid-cols-[1fr_2fr]">
              <Field label="Ikon">
                <select
                  value={s.icon}
                  onChange={(e) =>
                    updateService(i, { icon: e.target.value as ServiceIcon })
                  }
                  className={inputCls}
                >
                  {SERVICE_ICONS.map((ic) => (
                    <option key={ic} value={ic}>
                      {ic}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Judul">
                <input
                  value={s.title}
                  onChange={(e) => updateService(i, { title: e.target.value })}
                  className={inputCls}
                />
              </Field>
            </div>
            <Field label="Deskripsi">
              <textarea
                value={s.description}
                onChange={(e) => updateService(i, { description: e.target.value })}
                rows={2}
                className={inputCls}
              />
            </Field>
          </ListRow>
        ))}
        <button
          onClick={() =>
            patch("services", [
              ...services,
              { icon: "globe", title: "Layanan Baru", description: "" },
            ])
          }
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Layanan
        </button>
      </section>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-fg">Alur Kerja (Proses)</h3>
        {processSteps.map((s, i) => (
          <ListRow
            key={i}
            onRemove={() =>
              patch("processSteps", processSteps.filter((_, j) => j !== i))
            }
            onUp={
              i > 0 ? () => patch("processSteps", move(processSteps, i, -1)) : undefined
            }
            onDown={
              i < processSteps.length - 1
                ? () => patch("processSteps", move(processSteps, i, 1))
                : undefined
            }
          >
            <Field label={`Langkah ${i + 1} — Judul`}>
              <input
                value={s.title}
                onChange={(e) => updateStep(i, { title: e.target.value })}
                className={inputCls}
              />
            </Field>
            <Field label="Deskripsi">
              <textarea
                value={s.description}
                onChange={(e) => updateStep(i, { description: e.target.value })}
                rows={2}
                className={inputCls}
              />
            </Field>
          </ListRow>
        ))}
        <button
          onClick={() =>
            patch("processSteps", [
              ...processSteps,
              { title: "Langkah Baru", description: "" },
            ])
          }
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Langkah
        </button>
      </section>

      <section className="grid gap-8 md:grid-cols-2">
        <div>
          <h3 className="mb-3 text-sm font-semibold text-fg">
            Sub-layanan (kolom kiri)
          </h3>
          <StringList
            items={content.subServicesLeft}
            onChange={(v) => patch("subServicesLeft", v)}
          />
        </div>
        <div>
          <h3 className="mb-3 text-sm font-semibold text-fg">
            Sub-layanan (kolom kanan)
          </h3>
          <StringList
            items={content.subServicesRight}
            onChange={(v) => patch("subServicesRight", v)}
          />
        </div>
      </section>
    </div>
  );
}

/* --------------------------- Tab: Testimoni -------------------------- */

function TestimonialsTab({
  content,
  patch,
  move,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
  move: <T>(arr: T[], i: number, dir: -1 | 1) => T[];
}) {
  const items = content.testimonials;
  const update = (i: number, t: Partial<Testimonial>) => {
    const next = [...items];
    next[i] = { ...next[i], ...t };
    patch("testimonials", next);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm text-mist">{items.length} testimoni</p>
        <button
          onClick={() =>
            patch("testimonials", [
              ...items,
              {
                name: "Nama",
                role: "Jabatan, Instansi",
                initials: "NA",
                tone: 0,
                quote: "",
                rating: "5.0",
              },
            ])
          }
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Testimoni
        </button>
      </div>

      {items.map((t, i) => (
        <ListRow
          key={i}
          onRemove={() => patch("testimonials", items.filter((_, j) => j !== i))}
          onUp={i > 0 ? () => patch("testimonials", move(items, i, -1)) : undefined}
          onDown={
            i < items.length - 1
              ? () => patch("testimonials", move(items, i, 1))
              : undefined
          }
        >
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Nama">
              <input
                value={t.name}
                onChange={(e) => update(i, { name: e.target.value })}
                className={inputCls}
              />
            </Field>
            <Field label="Jabatan & Instansi">
              <input
                value={t.role}
                onChange={(e) => update(i, { role: e.target.value })}
                className={inputCls}
              />
            </Field>
          </div>
          <div className="grid gap-3 sm:grid-cols-3">
            <Field label="Inisial">
              <input
                value={t.initials}
                maxLength={2}
                onChange={(e) => update(i, { initials: e.target.value })}
                className={inputCls}
              />
            </Field>
            <Field label="Rating">
              <input
                value={t.rating}
                onChange={(e) => update(i, { rating: e.target.value })}
                className={inputCls}
              />
            </Field>
            <Field label="Tone Avatar (0–3)">
              <input
                type="number"
                min={0}
                max={3}
                value={t.tone}
                onChange={(e) => update(i, { tone: Number(e.target.value) })}
                className={inputCls}
              />
            </Field>
          </div>
          <Field label="Kutipan">
            <textarea
              value={t.quote}
              onChange={(e) => update(i, { quote: e.target.value })}
              rows={3}
              className={inputCls}
            />
          </Field>
        </ListRow>
      ))}
    </div>
  );
}

/* ------------------------------ Tab: FAQ ----------------------------- */

function FaqTab({
  content,
  patch,
  move,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
  move: <T>(arr: T[], i: number, dir: -1 | 1) => T[];
}) {
  const items = content.faqs;
  const update = (i: number, f: Partial<Faq>) => {
    const next = [...items];
    next[i] = { ...next[i], ...f };
    patch("faqs", next);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm text-mist">{items.length} pertanyaan</p>
        <button
          onClick={() => patch("faqs", [...items, { q: "Pertanyaan baru?", a: "" }])}
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Pertanyaan
        </button>
      </div>

      {items.map((f, i) => (
        <ListRow
          key={i}
          onRemove={() => patch("faqs", items.filter((_, j) => j !== i))}
          onUp={i > 0 ? () => patch("faqs", move(items, i, -1)) : undefined}
          onDown={
            i < items.length - 1 ? () => patch("faqs", move(items, i, 1)) : undefined
          }
        >
          <Field label="Pertanyaan">
            <input
              value={f.q}
              onChange={(e) => update(i, { q: e.target.value })}
              className={inputCls}
            />
          </Field>
          <Field label="Jawaban">
            <textarea
              value={f.a}
              onChange={(e) => update(i, { a: e.target.value })}
              rows={3}
              className={inputCls}
            />
          </Field>
        </ListRow>
      ))}
    </div>
  );
}

/* ---------------------------- Tab: Beranda --------------------------- */

function HomeTab({
  content,
  patch,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
}) {
  const { stats, milestones } = content;
  const updateStat = (i: number, s: Partial<Stat>) => {
    const next = [...stats];
    next[i] = { ...next[i], ...s };
    patch("stats", next);
  };
  const updateMilestone = (i: number, m: Partial<Milestone>) => {
    const next = [...milestones];
    next[i] = { ...next[i], ...m };
    patch("milestones", next);
  };

  return (
    <div className="space-y-10">
      <Field label="Slogan">
        <input
          value={content.slogan}
          onChange={(e) => patch("slogan", e.target.value)}
          className={inputCls}
        />
      </Field>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-fg">Statistik</h3>
        {stats.map((s, i) => (
          <ListRow
            key={i}
            onRemove={() => patch("stats", stats.filter((_, j) => j !== i))}
          >
            <div className="grid gap-3 sm:grid-cols-[1fr_2fr]">
              <Field label="Nilai">
                <input
                  value={s.value}
                  onChange={(e) => updateStat(i, { value: e.target.value })}
                  className={inputCls}
                />
              </Field>
              <Field label="Label">
                <input
                  value={s.label}
                  onChange={(e) => updateStat(i, { label: e.target.value })}
                  className={inputCls}
                />
              </Field>
            </div>
          </ListRow>
        ))}
        <button
          onClick={() => patch("stats", [...stats, { value: "0+", label: "" }])}
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Statistik
        </button>
      </section>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-fg">
          Tonggak Perjalanan (Tentang Kami)
        </h3>
        {milestones.map((m, i) => (
          <ListRow
            key={i}
            onRemove={() => patch("milestones", milestones.filter((_, j) => j !== i))}
          >
            <Field label="Capaian">
              <input
                value={m.role}
                onChange={(e) => updateMilestone(i, { role: e.target.value })}
                className={inputCls}
              />
            </Field>
            <div className="grid gap-3 sm:grid-cols-2">
              <Field label="Tempat / Instansi">
                <input
                  value={m.place}
                  onChange={(e) => updateMilestone(i, { place: e.target.value })}
                  className={inputCls}
                />
              </Field>
              <Field label="Label Chip">
                <input
                  value={m.period}
                  onChange={(e) => updateMilestone(i, { period: e.target.value })}
                  className={inputCls}
                />
              </Field>
            </div>
          </ListRow>
        ))}
        <button
          onClick={() =>
            patch("milestones", [...milestones, { role: "", place: "", period: "" }])
          }
          className="glow-border inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium text-fog transition-colors hover:text-fg"
        >
          <Plus size={13} /> Tambah Tonggak
        </button>
      </section>

      <section>
        <h3 className="mb-3 text-sm font-semibold text-fg">Tech Stack</h3>
        <StringList items={content.techStack} onChange={(v) => patch("techStack", v)} />
      </section>

      <section>
        <h3 className="mb-3 text-sm font-semibold text-fg">Rekognisi Tim</h3>
        <StringList
          items={content.recognitions}
          onChange={(v) => patch("recognitions", v)}
        />
      </section>

      <section>
        <h3 className="mb-3 text-sm font-semibold text-fg">Liputan Media</h3>
        <StringList
          items={content.mediaCoverage}
          onChange={(v) => patch("mediaCoverage", v)}
        />
      </section>
    </div>
  );
}

/* ------------------------------ Tab: Tema ---------------------------- */

const COLOR_FIELDS: { key: keyof ThemeColors; label: string }[] = [
  { key: "ink", label: "Background Utama" },
  { key: "surface", label: "Kartu / Panel" },
  { key: "fg", label: "Teks Utama" },
  { key: "fog", label: "Teks Sekunder" },
  { key: "mist", label: "Teks Label" },
  { key: "line", label: "Warna Border" },
  { key: "cta", label: "Tombol Utama" },
  { key: "ctaInk", label: "Teks Tombol" },
  { key: "accent", label: "Highlight / Aksen" },
];

const HEX_RE = /^#[0-9a-fA-F]{6}$/;

function ThemeTab({
  content,
  patch,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
}) {
  const theme: SiteTheme = content.theme ?? { dark: {}, light: {} };

  const set = (mode: "dark" | "light", key: keyof ThemeColors, value: string) =>
    patch("theme", { ...theme, [mode]: { ...theme[mode], [key]: value } });

  const reset = (mode: "dark" | "light") =>
    patch("theme", { ...theme, [mode]: { ...DEFAULT_THEME[mode] } });

  return (
    <div className="space-y-12">
      <p className="max-w-2xl text-sm leading-relaxed text-mist">
        Atur warna elemen situs untuk masing-masing mode. Token turunan
        (border transparan, panel halus, kartu hover) dihitung otomatis dari
        warna di sini. Kosongkan kolom untuk memakai bawaan.
      </p>

      {(["dark", "light"] as const).map((mode) => {
        const group = theme[mode] ?? {};
        const val = (key: keyof ThemeColors): string =>
          group[key] ?? DEFAULT_THEME[mode][key] ?? "#000000";
        const valid = (key: keyof ThemeColors) =>
          group[key] === undefined || group[key] === "" || HEX_RE.test(group[key]);

        return (
          <section key={mode} className="space-y-4">
            <div className="flex items-center justify-between gap-4">
              <h3 className="text-sm font-semibold text-fg">
                {mode === "dark" ? "Mode Gelap (bawaan)" : "Mode Terang"}
              </h3>
              <button
                type="button"
                onClick={() => reset(mode)}
                className="glow-border rounded-full px-4 py-1.5 text-xs font-medium text-fog transition-colors hover:text-fg"
              >
                Reset ke default
              </button>
            </div>

            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {COLOR_FIELDS.map(({ key, label }) => (
                <div
                  key={key}
                  className="rounded-2xl border border-line bg-ink/60 p-3.5"
                >
                  <span className="mb-2 block font-accent text-[11px] tracking-wide text-mist uppercase">
                    {label}
                  </span>
                  <div className="flex items-center gap-2.5">
                    <input
                      type="color"
                      value={val(key)}
                      onChange={(e) => set(mode, key, e.target.value)}
                      className="size-10 shrink-0 cursor-pointer rounded-lg border border-line bg-transparent p-1"
                      aria-label={label}
                    />
                    <input
                      type="text"
                      value={group[key] ?? ""}
                      placeholder={DEFAULT_THEME[mode][key]}
                      onChange={(e) => set(mode, key, e.target.value)}
                      className={`${inputCls} font-mono text-xs ${
                        valid(key) ? "" : "border-red-500/60"
                      }`}
                    />
                  </div>
                </div>
              ))}
            </div>

            {/* Pratinjau kombinasi warna mode ini */}
            <div
              className="flex flex-wrap items-center gap-3 rounded-2xl border border-line p-5"
              style={{ background: val("ink") }}
            >
              <span
                className="rounded-xl px-4 py-2 text-sm"
                style={{ background: val("surface"), color: val("fog") }}
              >
                Kartu · <b style={{ color: val("fg") }}>Teks utama</b>
              </span>
              <span
                className="rounded-full px-5 py-2 text-sm font-semibold"
                style={{ background: val("cta"), color: val("ctaInk") }}
              >
                Tombol
              </span>
              <span
                className="rounded-full border px-4 py-2 text-sm font-semibold"
                style={{
                  color: val("accent"),
                  borderColor: val("accent"),
                }}
              >
                Aksen
              </span>
            </div>
          </section>
        );
      })}
    </div>
  );
}

/* ----------------------------- Tab: Kontak --------------------------- */

function ContactTab({
  content,
  patch,
}: {
  content: SiteContent;
  patch: <K extends keyof SiteContent>(key: K, value: SiteContent[K]) => void;
}) {
  const set = (field: keyof SiteContent["contact"], value: string) =>
    patch("contact", { ...content.contact, [field]: value });

  return (
    <div className="max-w-xl space-y-3">
      <Field label="Email">
        <input
          value={content.contact.email}
          onChange={(e) => set("email", e.target.value)}
          className={inputCls}
        />
      </Field>
      <Field label="WhatsApp">
        <input
          value={content.contact.wa}
          onChange={(e) => set("wa", e.target.value)}
          className={inputCls}
        />
      </Field>
      <Field label="Alamat Kantor">
        <input
          value={content.contact.address}
          onChange={(e) => set("address", e.target.value)}
          className={inputCls}
        />
      </Field>
      <Field label="Website">
        <input
          value={content.contact.site}
          onChange={(e) => set("site", e.target.value)}
          className={inputCls}
        />
      </Field>
    </div>
  );
}
