"use client";

import { useState, useEffect, useRef } from "react";
import { FormSheet } from "@/components/admin/FormSheet";
import { PageHeader } from "@/components/admin/PageHeader";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "sonner";
import { useDragReorder } from "@/hooks/use-drag-reorder";
import { SectorIconPicker } from "@/components/admin/SectorIconPicker";
import { SECTOR_ICONS } from "@/lib/sectorIconMap";
import {
  Trash2, GripVertical, Loader2, Plus, Save, ChevronRight, MapPin,
  Globe, CheckCircle2,
} from "lucide-react";
import {
  getCoreValues, createCoreValue, updateCoreValue, deleteCoreValue, reorderCoreValues,
  type CoreValue,
} from "@/services/core-values";
import {
  getAffiliates, createAffiliate, updateAffiliate, deleteAffiliate, reorderAffiliates,
  type Affiliate,
} from "@/services/affiliates";
import {
  getStrengths, createStrength, updateStrength, deleteStrength, reorderStrengths,
  type Strength,
} from "@/services/strengths";
import {
  getRegions, createRegion, updateRegion, deleteRegion, reorderRegions,
  type Region,
} from "@/services/regions";
import {
  getContinents, createContinent, updateContinent, deleteContinent, reorderContinents,
  type Continent,
} from "@/services/continents";
import { getPageContent, updatePageContent } from "@/services/pages";
import {
  getMapLocations, createMapLocation, updateMapLocation, deleteMapLocation, reorderMapLocations,
  type MapLocation,
} from "@/services/map-locations";
import {
  getHistoryMilestones, createHistoryMilestone, updateHistoryMilestone,
  deleteHistoryMilestone, reorderHistoryMilestones,
  type HistoryMilestone,
} from "@/services/history";
import { useAdminLocale } from "@/hooks/use-admin-locale";

// ─── Mission & Vision tab ─────────────────────────────────────────────────────

function MissionVisionTabContent() {
  const [vision, setVision] = useState("");
  const [mission, setMission] = useState("");
  const [loading, setLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const fetchedRef = useRef(false);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getPageContent("about")
      .then((data) => {
        setVision(String(data.about_vision ?? ""));
        setMission(String(data.about_mission ?? ""));
      })
      .finally(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    if (!vision.trim()) { toast.error("Vision text is required."); return; }
    if (!mission.trim()) { toast.error("Mission text is required."); return; }
    setIsSaving(true);
    try {
      await updatePageContent("about", {
        about_vision: vision.trim(),
        about_mission: mission.trim(),
      });
      toast.success("Mission & Vision updated.");
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="max-w-2xl space-y-4">
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-40 w-full" />
      </div>
    );
  }

  return (
    <div className="max-w-2xl space-y-6">
      <p className="text-sm text-muted-foreground">
        Edit the Vision and Mission statements displayed on the About page.
      </p>
      <div className="space-y-2">
        <Label>Our Vision</Label>
        <Textarea
          value={vision}
          onChange={(e) => setVision(e.target.value)}
          rows={4}
          placeholder="We strive to be the first choice..."
        />
      </div>
      <div className="space-y-2">
        <Label>Our Mission</Label>
        <Textarea
          value={mission}
          onChange={(e) => setMission(e.target.value)}
          rows={5}
          placeholder="We enhance our client's facility integrity..."
        />
      </div>
      <Button onClick={handleSave} disabled={isSaving} className="gap-2">
        {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
        Save Changes
      </Button>
    </div>
  );
}

// ─── Core Values tab ──────────────────────────────────────────────────────────

function CoreValuesTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<CoreValue[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<CoreValue | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [iconValue, setIconValue] = useState("Shield");
  const [titleValue, setTitleValue] = useState("");
  const [descValue, setDescValue] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((v, i) => ({ id: v.id, sort_order: i }));
      reorderCoreValues(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getCoreValues().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setIconValue("Shield");
    setTitleValue("");
    setDescValue("");
  };

  const handleSave = async () => {
    if (!titleValue.trim()) { toast.error("Title is required."); return; }
    if (!descValue.trim()) { toast.error("Description is required."); return; }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createCoreValue({ icon: iconValue, title: titleValue.trim(), desc: descValue.trim() });
        setItems((prev) => [...prev, created]);
        toast.success("Core value added.");
        resetSheet();
      } else {
        const updated = await updateCoreValue(editing!.id, {
          icon: iconValue,
          title: { [locale]: titleValue.trim() },
          desc: { [locale]: descValue.trim() },
        });
        setItems((prev) => prev.map((v) => (v.id === updated.id ? updated : v)));
        toast.success("Core value updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: CoreValue) => {
    e.stopPropagation();
    if (deletingId) return;
    setDeletingId(item.id);
    try {
      await deleteCoreValue(item.id);
      setItems((prev) => prev.filter((v) => v.id !== item.id));
      toast.success("Core value removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingId(null);
    }
  };

  const openEdit = (item: CoreValue) => {
    setIconValue(item.icon);
    setTitleValue(item.title);
    setDescValue(item.desc);
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage the core value cards shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Value
        </Button>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {loading
          ? Array.from({ length: 8 }).map((_, i) => <Skeleton key={i} className="h-28 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No core values yet. Add your first one.
              </div>
            )
            : items.map((v, index) => {
                  const IconComp = SECTOR_ICONS[v.icon]?.component;
              return (
                <div
                  key={v.id}
                  draggable
                  onDragStart={() => onDragStart(index)}
                  onDragEnter={() => onDragEnter(index)}
                  onDragOver={(e) => e.preventDefault()}
                  onDragEnd={onDragEnd}
                  className="bg-card border rounded-lg p-5 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                  onClick={() => openEdit(v)}
                >
                  <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1">
                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6 text-destructive hover:text-destructive"
                      disabled={deletingId === v.id}
                      onClick={(e) => handleDelete(e, v)}
                    >
                      {deletingId === v.id
                        ? <Loader2 className="h-3 w-3 animate-spin" />
                        : <Trash2 className="h-3 w-3" />}
                    </Button>
                  </div>
                  <div className="flex items-center gap-2 mb-2 pr-12">
                    {IconComp && <IconComp className="h-5 w-5 text-primary shrink-0" />}
                    <h3 className="font-semibold text-sm leading-tight">{v.title}</h3>
                  </div>
                  <p className="text-xs text-muted-foreground line-clamp-2">{v.desc}</p>
                </div>
              );
            })
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} values · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.title}` : "New Core Value"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Value"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Icon</Label>
          <SectorIconPicker value={iconValue} onChange={setIconValue} />
        </div>
        <div className="space-y-2">
          <Label>Title</Label>
          <Input
            value={titleValue}
            onChange={(e) => setTitleValue(e.target.value)}
            placeholder="e.g. Integrity"
          />
        </div>
        <div className="space-y-2">
          <Label>Description</Label>
          <Input
            value={descValue}
            onChange={(e) => setDescValue(e.target.value)}
            placeholder="e.g. Ethical conduct in every engagement"
          />
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Affiliates tab ───────────────────────────────────────────────────────────

function AffiliatesTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<Affiliate[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Affiliate | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [countryValue, setCountryValue] = useState("");
  const [entityValue, setEntityValue] = useState("");
  const [subEntityValue, setSubEntityValue] = useState("");
  const [subsValue, setSubsValue] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((a, i) => ({ id: a.id, sort_order: i }));
      reorderAffiliates(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getAffiliates().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setCountryValue("");
    setEntityValue("");
    setSubEntityValue("");
    setSubsValue([]);
  };

  const handleSave = async () => {
    if (!countryValue.trim()) { toast.error("Country is required."); return; }
    if (!entityValue.trim()) { toast.error("Entity name is required."); return; }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createAffiliate({
          country: countryValue.trim(),
          entity: entityValue.trim(),
          sub_entity: subEntityValue.trim() || null,
          subs: subsValue.filter(Boolean),
        });
        setItems((prev) => [...prev, created]);
        toast.success("Affiliate added.");
        resetSheet();
      } else {
        const updated = await updateAffiliate(editing!.id, {
          country: countryValue.trim(),
          entity: { [locale]: entityValue.trim() },
          sub_entity: subEntityValue.trim() ? { [locale]: subEntityValue.trim() } : null,
          subs: { [locale]: subsValue.filter(Boolean) },
        });
        setItems((prev) => prev.map((a) => (a.id === updated.id ? updated : a)));
        toast.success("Affiliate updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: Affiliate) => {
    e.stopPropagation();
    if (deletingId) return;
    setDeletingId(item.id);
    try {
      await deleteAffiliate(item.id);
      setItems((prev) => prev.filter((a) => a.id !== item.id));
      toast.success("Affiliate removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingId(null);
    }
  };

  const openEdit = (item: Affiliate) => {
    setCountryValue(item.country);
    setEntityValue(item.entity);
    setSubEntityValue(item.sub_entity ?? "");
    setSubsValue(item.subs ?? []);
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage global affiliate entities shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Affiliate
        </Button>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        {loading
          ? Array.from({ length: 7 }).map((_, i) => <Skeleton key={i} className="h-36 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No affiliates yet. Add your first one.
              </div>
            )
            : items.map((a, index) => (
              <div
                key={a.id}
                draggable
                onDragStart={() => onDragStart(index)}
                onDragEnter={() => onDragEnter(index)}
                onDragOver={(e) => e.preventDefault()}
                onDragEnd={onDragEnd}
                className="bg-card border rounded-lg p-5 border-t-4 border-t-primary cursor-pointer hover:bg-muted/30 transition-colors relative group"
                onClick={() => openEdit(a)}
              >
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-3 right-3 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                  disabled={deletingId === a.id}
                  onClick={(e) => handleDelete(e, a)}
                >
                  {deletingId === a.id
                    ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    : <Trash2 className="h-3.5 w-3.5" />}
                </Button>
                <div className="flex items-center gap-2 mb-2">
                  <MapPin className="h-4 w-4 text-primary shrink-0" />
                  <span className="text-xs font-bold uppercase tracking-wider text-primary">{a.country}</span>
                </div>
                <p className="font-semibold text-sm mb-1">{a.entity}</p>
                {a.sub_entity && (
                  <p className="text-xs text-muted-foreground mb-2">{a.sub_entity}</p>
                )}
                {a.subs && a.subs.length > 0 && (
                  <ul className="space-y-1 mt-2">
                    {a.subs.slice(0, 3).map((s, j) => (
                      <li key={j} className="text-xs text-muted-foreground flex items-start gap-1">
                        <ChevronRight className="h-3 w-3 text-primary mt-0.5 shrink-0" />
                        <span className="line-clamp-1">{s}</span>
                      </li>
                    ))}
                    {a.subs.length > 3 && (
                      <li className="text-xs text-muted-foreground">+{a.subs.length - 3} more</li>
                    )}
                  </ul>
                )}
              </div>
            ))
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} affiliates · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.country}` : "New Affiliate"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Affiliate"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Country</Label>
          <Input
            value={countryValue}
            onChange={(e) => setCountryValue(e.target.value)}
            placeholder="e.g. Nigeria"
          />
        </div>
        <div className="space-y-2">
          <Label>Entity Name</Label>
          <Input
            value={entityValue}
            onChange={(e) => setEntityValue(e.target.value)}
            placeholder="e.g. PETRO-BASE GROUP LTD"
          />
        </div>
        <div className="space-y-2">
          <Label>
            Sub-Entity{" "}
            <span className="text-muted-foreground text-xs font-normal">(optional)</span>
          </Label>
          <Input
            value={subEntityValue}
            onChange={(e) => setSubEntityValue(e.target.value)}
            placeholder="e.g. (a Petro Base API LTD JV Company)"
          />
        </div>
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label>Subsidiaries</Label>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="h-7 text-xs gap-1"
              onClick={() => setSubsValue((prev) => [...prev, ""])}
            >
              <Plus className="h-3 w-3" /> Add
            </Button>
          </div>
          {subsValue.length === 0 && (
            <p className="text-xs text-muted-foreground">
              No subsidiaries yet. Click Add to include them.
            </p>
          )}
          {subsValue.map((sub, i) => (
            <div key={i} className="flex items-center gap-2">
              <Input
                value={sub}
                onChange={(e) =>
                  setSubsValue((prev) => prev.map((s, j) => (j === i ? e.target.value : s)))
                }
                placeholder={`Subsidiary ${i + 1}`}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-9 w-9 shrink-0 text-destructive hover:text-destructive"
                onClick={() => setSubsValue((prev) => prev.filter((_, j) => j !== i))}
              >
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          ))}
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Strengths tab ────────────────────────────────────────────────────────────

function StrengthsTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<Strength[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Strength | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [iconValue, setIconValue] = useState("Zap");
  const [textValue, setTextValue] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((s, i) => ({ id: s.id, sort_order: i }));
      reorderStrengths(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getStrengths().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setIconValue("Zap");
    setTextValue("");
  };

  const handleSave = async () => {
    if (!textValue.trim()) { toast.error("Strength text is required."); return; }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createStrength({ icon: iconValue, text: textValue.trim() });
        setItems((prev) => [...prev, created]);
        toast.success("Strength added.");
        resetSheet();
      } else {
        const updated = await updateStrength(editing!.id, {
          icon: iconValue,
          text: { [locale]: textValue.trim() },
        });
        setItems((prev) => prev.map((s) => (s.id === updated.id ? updated : s)));
        toast.success("Strength updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: Strength) => {
    e.stopPropagation();
    if (deletingId) return;
    setDeletingId(item.id);
    try {
      await deleteStrength(item.id);
      setItems((prev) => prev.filter((s) => s.id !== item.id));
      toast.success("Strength removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingId(null);
    }
  };

  const openEdit = (item: Strength) => {
    setIconValue(item.icon);
    setTextValue(item.text);
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage the strength cards shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Strength
        </Button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
        {loading
          ? Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-16 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No strengths yet. Add your first one.
              </div>
            )
            : items.map((s, index) => {
              const IconComp = SECTOR_ICONS[s.icon]?.component;
              return (
                <div
                  key={s.id}
                  draggable
                  onDragStart={() => onDragStart(index)}
                  onDragEnter={() => onDragEnter(index)}
                  onDragOver={(e) => e.preventDefault()}
                  onDragEnd={onDragEnd}
                  className="bg-card border rounded-lg p-4 flex items-center gap-4 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                  onClick={() => openEdit(s)}
                >
                  <div className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                  </div>
                  {IconComp && <IconComp className="h-5 w-5 text-primary shrink-0" />}
                  <p className="font-semibold text-sm flex-1">{s.text}</p>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive shrink-0"
                    disabled={deletingId === s.id}
                    onClick={(e) => handleDelete(e, s)}
                  >
                    {deletingId === s.id
                      ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                      : <Trash2 className="h-3.5 w-3.5" />}
                  </Button>
                </div>
              );
            })
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} strengths · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? "Edit Strength" : "New Strength"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Strength"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Icon</Label>
          <SectorIconPicker value={iconValue} onChange={setIconValue} />
        </div>
        <div className="space-y-2">
          <Label>Text</Label>
          <Input
            value={textValue}
            onChange={(e) => setTextValue(e.target.value)}
            placeholder="e.g. Modern technology"
          />
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Regions tab ──────────────────────────────────────────────────────────────

function RegionsTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<Region[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Region | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [nameValue, setNameValue] = useState("");
  const [countriesValue, setCountriesValue] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [deletingSlug, setDeletingSlug] = useState<string | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((r, i) => ({ id: r.id, sort_order: i }));
      reorderRegions(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getRegions().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setNameValue("");
    setCountriesValue([]);
  };

  const getRegionIdentity = (item: Region): string => item.slug || `region-${item.id}`;

  const getRegionSlug = (item: Region): string | null => item.slug || null;

  const handleSave = async () => {
    if (!nameValue.trim()) { toast.error("Region name is required."); return; }
    if (countriesValue.filter(Boolean).length === 0) {
      toast.error("Add at least one country.");
      return;
    }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createRegion({ name: nameValue.trim(), countries: countriesValue.filter(Boolean) });
        setItems((prev) => [...prev, created]);
        toast.success("Region added.");
        resetSheet();
      } else {
        const slug = getRegionSlug(editing!);
        if (!slug) {
          toast.error("This region is missing a slug and cannot be updated.");
          return;
        }
        const updated = await updateRegion(slug, {
          name: { [locale]: nameValue.trim() },
          countries: countriesValue.filter(Boolean),
        });
        const editingIdentity = getRegionIdentity(editing!);
        setItems((prev) => prev.map((r) => (getRegionIdentity(r) === editingIdentity ? updated : r)));
        toast.success("Region updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: Region) => {
    e.stopPropagation();
    if (deletingSlug) return;
    const slug = getRegionSlug(item);
    if (!slug) {
      toast.error("This region is missing a slug and cannot be deleted.");
      return;
    }
    const identity = getRegionIdentity(item);
    setDeletingSlug(identity);
    try {
      await deleteRegion(slug);
      setItems((prev) => prev.filter((r) => getRegionIdentity(r) !== identity));
      toast.success("Region removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingSlug(null);
    }
  };

  const getCountryName = (country: unknown): string => {
    if (typeof country === "string") return country;
    if (country && typeof country === "object" && "name" in country) {
      return String((country as { name?: unknown }).name ?? "");
    }
    return "";
  };

  const openEdit = (item: Region) => {
    setNameValue(item.name);
    setCountriesValue((item.countries ?? []).map(getCountryName).filter(Boolean));
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage global presence regions shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Region
        </Button>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
        {loading
          ? Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-40 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No regions yet. Add your first one.
              </div>
            )
            : items.map((r, index) => (
              <div
                key={getRegionIdentity(r)}
                draggable
                onDragStart={() => onDragStart(index)}
                onDragEnter={() => onDragEnter(index)}
                onDragOver={(e) => e.preventDefault()}
                onDragEnd={onDragEnd}
                className="bg-card border rounded-lg p-5 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                onClick={() => openEdit(r)}
              >
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-3 right-3 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                  disabled={deletingSlug === getRegionIdentity(r)}
                  onClick={(e) => handleDelete(e, r)}
                >
                  {deletingSlug === getRegionIdentity(r)
                    ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    : <Trash2 className="h-3.5 w-3.5" />}
                </Button>
                <div className="flex items-center gap-2 mb-4">
                  <Globe className="h-4 w-4 text-primary" />
                  <h4 className="font-bold text-sm">{r.name}</h4>
                </div>
                <ul className="space-y-1.5">
                  {(r.countries ?? []).map((country, j) => (
                    <li key={j} className="flex items-center gap-2 text-xs text-muted-foreground">
                      <CheckCircle2 className="h-3 w-3 text-primary shrink-0" />
                      {getCountryName(country)}
                    </li>
                  ))}
                </ul>
              </div>
            ))
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} regions · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.name}` : "New Region"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Region"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Region Name</Label>
          <Input
            value={nameValue}
            onChange={(e) => setNameValue(e.target.value)}
            placeholder="e.g. Africa"
          />
        </div>
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label>Countries</Label>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="h-7 text-xs gap-1"
              onClick={() => setCountriesValue((prev) => [...prev, ""])}
            >
              <Plus className="h-3 w-3" /> Add
            </Button>
          </div>
          {countriesValue.length === 0 && (
            <p className="text-xs text-muted-foreground">
              No countries yet. Click Add to include them.
            </p>
          )}
          {countriesValue.map((c, i) => (
            <div key={i} className="flex items-center gap-2">
              <Input
                value={c}
                onChange={(e) =>
                  setCountriesValue((prev) => prev.map((x, j) => (j === i ? e.target.value : x)))
                }
                placeholder={`Country ${i + 1}`}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-9 w-9 shrink-0 text-destructive hover:text-destructive"
                onClick={() => setCountriesValue((prev) => prev.filter((_, j) => j !== i))}
              >
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          ))}
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Continents tab ───────────────────────────────────────────────────────────

function ContinentsTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<Continent[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Continent | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [nameValue, setNameValue] = useState("");
  const [countriesValue, setCountriesValue] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [deletingSlug, setDeletingSlug] = useState<string | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((c, i) => ({ id: c.id, sort_order: i }));
      reorderContinents(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getContinents().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setNameValue("");
    setCountriesValue([]);
  };

  const getContinentIdentity = (item: Continent): string => item.slug || `continent-${item.id}`;

  const getContinentSlug = (item: Continent): string | null => item.slug || null;

  const handleSave = async () => {
    if (!nameValue.trim()) { toast.error("Continent name is required."); return; }
    if (countriesValue.filter(Boolean).length === 0) {
      toast.error("Add at least one country.");
      return;
    }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createContinent({ name: nameValue.trim(), countries: countriesValue.filter(Boolean) });
        setItems((prev) => [...prev, created]);
        toast.success("Continent added.");
        resetSheet();
      } else {
        const slug = getContinentSlug(editing!);
        if (!slug) {
          toast.error("This continent is missing a slug and cannot be updated.");
          return;
        }
        const updated = await updateContinent(slug, {
          name: { [locale]: nameValue.trim() },
          countries: countriesValue.filter(Boolean),
        });
        const editingIdentity = getContinentIdentity(editing!);
        setItems((prev) => prev.map((c) => (getContinentIdentity(c) === editingIdentity ? updated : c)));
        toast.success("Continent updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: Continent) => {
    e.stopPropagation();
    if (deletingSlug) return;
    const slug = getContinentSlug(item);
    if (!slug) {
      toast.error("This continent is missing a slug and cannot be deleted.");
      return;
    }
    const identity = getContinentIdentity(item);
    setDeletingSlug(identity);
    try {
      await deleteContinent(slug);
      setItems((prev) => prev.filter((c) => getContinentIdentity(c) !== identity));
      toast.success("Continent removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingSlug(null);
    }
  };

  const getCountryName = (country: unknown): string => {
    if (typeof country === "string") return country;
    if (country && typeof country === "object" && "name" in country) {
      return String((country as { name?: unknown }).name ?? "");
    }
    return "";
  };

  const openEdit = (item: Continent) => {
    setNameValue(item.name);
    setCountriesValue((item.countries ?? []).map(getCountryName).filter(Boolean));
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage continent groups shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Continent
        </Button>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
        {loading
          ? Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-40 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No continents yet. Add your first one.
              </div>
            )
            : items.map((c, index) => (
              <div
                key={getContinentIdentity(c)}
                draggable
                onDragStart={() => onDragStart(index)}
                onDragEnter={() => onDragEnter(index)}
                onDragOver={(e) => e.preventDefault()}
                onDragEnd={onDragEnd}
                className="bg-card border rounded-lg p-5 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                onClick={() => openEdit(c)}
              >
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-3 right-3 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                  disabled={deletingSlug === getContinentIdentity(c)}
                  onClick={(e) => handleDelete(e, c)}
                >
                  {deletingSlug === getContinentIdentity(c)
                    ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    : <Trash2 className="h-3.5 w-3.5" />}
                </Button>
                <div className="flex items-center gap-2 mb-4">
                  <Globe className="h-4 w-4 text-primary" />
                  <h4 className="font-bold text-sm">{c.name}</h4>
                </div>
                <ul className="space-y-1.5">
                  {(c.countries ?? []).map((country, j) => (
                    <li key={j} className="flex items-center gap-2 text-xs text-muted-foreground">
                      <CheckCircle2 className="h-3 w-3 text-primary shrink-0" />
                      {getCountryName(country)}
                    </li>
                  ))}
                </ul>
              </div>
            ))
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} continents · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.name}` : "New Continent"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Continent"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Continent Name</Label>
          <Input
            value={nameValue}
            onChange={(e) => setNameValue(e.target.value)}
            placeholder="e.g. Africa"
          />
        </div>
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label>Countries</Label>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="h-7 text-xs gap-1"
              onClick={() => setCountriesValue((prev) => [...prev, ""])}
            >
              <Plus className="h-3 w-3" /> Add
            </Button>
          </div>
          {countriesValue.length === 0 && (
            <p className="text-xs text-muted-foreground">
              No countries yet. Click Add to include them.
            </p>
          )}
          {countriesValue.map((c, i) => (
            <div key={i} className="flex items-center gap-2">
              <Input
                value={c}
                onChange={(e) =>
                  setCountriesValue((prev) => prev.map((x, j) => (j === i ? e.target.value : x)))
                }
                placeholder={`Country ${i + 1}`}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-9 w-9 shrink-0 text-destructive hover:text-destructive"
                onClick={() => setCountriesValue((prev) => prev.filter((_, j) => j !== i))}
              >
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          ))}
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Map Locations tab ──────────────────────────────────────────────────────────

function MapLocationsTabContent() {
  const [items, setItems] = useState<MapLocation[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<MapLocation | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [nameValue, setNameValue] = useState("");
  const [latValue, setLatValue] = useState("");
  const [lngValue, setLngValue] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((m, i) => ({ id: m.id, sort_order: i }));
      reorderMapLocations(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getMapLocations().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setNameValue("");
    setLatValue("");
    setLngValue("");
  };

  const handleSave = async () => {
    if (!nameValue.trim()) { toast.error("Location name is required."); return; }
    const lat = parseFloat(latValue);
    const lng = parseFloat(lngValue);
    if (isNaN(lat) || lat < -90 || lat > 90) { toast.error("Latitude must be between -90 and 90."); return; }
    if (isNaN(lng) || lng < -180 || lng > 180) { toast.error("Longitude must be between -180 and 180."); return; }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createMapLocation({ name: nameValue.trim(), lat, lng });
        setItems((prev) => [...prev, created]);
        toast.success("Map location added.");
        resetSheet();
      } else {
        const updated = await updateMapLocation(editing!.id, { name: nameValue.trim(), lat, lng });
        setItems((prev) => prev.map((m) => (m.id === updated.id ? updated : m)));
        toast.success("Map location updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: MapLocation) => {
    e.stopPropagation();
    if (deletingId) return;
    setDeletingId(item.id);
    try {
      await deleteMapLocation(item.id);
      setItems((prev) => prev.filter((m) => m.id !== item.id));
      toast.success("Map location removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingId(null);
    }
  };

  const openEdit = (item: MapLocation) => {
    setNameValue(item.name);
    setLatValue(String(item.lat));
    setLngValue(String(item.lng));
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage map pin locations shown on the interactive About page map. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Location
        </Button>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {loading
          ? Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-24 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No map locations yet. Add your first one.
              </div>
            )
            : items.map((m, index) => (
              <div
                key={m.id}
                draggable
                onDragStart={() => onDragStart(index)}
                onDragEnter={() => onDragEnter(index)}
                onDragOver={(e) => e.preventDefault()}
                onDragEnd={onDragEnd}
                className="bg-card border rounded-lg p-5 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                onClick={() => openEdit(m)}
              >
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-3 right-3 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                  disabled={deletingId === m.id}
                  onClick={(e) => handleDelete(e, m)}
                >
                  {deletingId === m.id
                    ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    : <Trash2 className="h-3.5 w-3.5" />}
                </Button>
                <div className="flex items-center gap-2 mb-2 pr-8">
                  <MapPin className="h-4 w-4 text-primary shrink-0" />
                  <span className="font-semibold text-sm">{m.name}</span>
                </div>
                <p className="text-xs text-muted-foreground">Lat: {m.lat}</p>
                <p className="text-xs text-muted-foreground">Lng: {m.lng}</p>
              </div>
            ))
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} locations · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.name}` : "New Map Location"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Location"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Location Name</Label>
          <Input
            value={nameValue}
            onChange={(e) => setNameValue(e.target.value)}
            placeholder="e.g. Lagos, Nigeria"
          />
        </div>
        <div className="space-y-2">
          <Label>Latitude</Label>
          <Input
            type="number"
            min={-90}
            max={90}
            step={0.0001}
            value={latValue}
            onChange={(e) => setLatValue(e.target.value)}
            placeholder="e.g. 6.5244"
          />
        </div>
        <div className="space-y-2">
          <Label>Longitude</Label>
          <Input
            type="number"
            min={-180}
            max={180}
            step={0.0001}
            value={lngValue}
            onChange={(e) => setLngValue(e.target.value)}
            placeholder="e.g. 3.3792"
          />
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────

// ─── History tab ─────────────────────────────────────────────────────────────

function HistoryTabContent() {
  const locale = useAdminLocale();
  const [items, setItems] = useState<HistoryMilestone[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<HistoryMilestone | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [yearValue, setYearValue] = useState("");
  const [titleValue, setTitleValue] = useState("");
  const [descValue, setDescValue] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const fetchedRef = useRef(false);

  const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
    items,
    setItems,
    (reordered) => {
      const positions = reordered.map((m, i) => ({ id: m.id, sort_order: i }));
      reorderHistoryMilestones(positions)
        .then(() => toast.success("Order saved."))
        .catch(() => {});
    },
  );

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getHistoryMilestones().then(setItems).finally(() => setLoading(false));
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setYearValue("");
    setTitleValue("");
    setDescValue("");
  };

  const handleSave = async () => {
    if (!yearValue.trim()) { toast.error("Year is required."); return; }
    if (!titleValue.trim()) { toast.error("Title is required."); return; }
    if (!descValue.trim()) { toast.error("Description is required."); return; }
    setIsSaving(true);
    try {
      if (isAdding) {
        const created = await createHistoryMilestone({
          year: yearValue.trim(),
          title: titleValue.trim(),
          description: descValue.trim(),
        });
        setItems((prev) => [...prev, created]);
        toast.success("Milestone added.");
        resetSheet();
      } else {
        const updated = await updateHistoryMilestone(editing!.id, {
          year: yearValue.trim(),
          title: { [locale]: titleValue.trim() },
          description: { [locale]: descValue.trim() },
        });
        setItems((prev) => prev.map((m) => (m.id === updated.id ? updated : m)));
        toast.success("Milestone updated.");
        resetSheet();
      }
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (e: React.MouseEvent, item: HistoryMilestone) => {
    e.stopPropagation();
    if (deletingId) return;
    setDeletingId(item.id);
    try {
      await deleteHistoryMilestone(item.id);
      setItems((prev) => prev.filter((m) => m.id !== item.id));
      toast.success("Milestone removed.");
    } catch {
      // interceptor shows toast
    } finally {
      setDeletingId(null);
    }
  };

  const openEdit = (item: HistoryMilestone) => {
    setYearValue(String(item.year));
    setTitleValue(String(item.title));
    setDescValue(String(item.description));
    setEditing(item);
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <p className="text-sm text-muted-foreground">
          Manage the Our History timeline shown on the About page. Drag to reorder.
        </p>
        <Button size="sm" className="gap-2" onClick={() => { resetSheet(); setIsAdding(true); }}>
          <Plus className="h-4 w-4" /> Add Milestone
        </Button>
      </div>

      <div className="flex flex-col gap-3">
        {loading
          ? Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-20 rounded-lg" />)
          : items.length === 0
            ? (
              <div className="text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                No milestones yet. Add your first one.
              </div>
            )
            : items.map((m, index) => (
              <div
                key={m.id}
                draggable
                onDragStart={() => onDragStart(index)}
                onDragEnter={() => onDragEnter(index)}
                onDragOver={(e) => e.preventDefault()}
                onDragEnd={onDragEnd}
                className="bg-card border rounded-lg p-4 flex items-start gap-4 cursor-pointer hover:bg-muted/30 transition-colors relative group border-l-4 border-l-primary"
                onClick={() => openEdit(m)}
              >
                <div className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0 mt-0.5">
                  <GripVertical className="h-4 w-4 text-muted-foreground" />
                </div>
                <div className="shrink-0 w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center">
                  <span className="text-xs font-bold text-primary leading-tight text-center">{m.year}</span>
                </div>
                <div className="flex-1 min-w-0">
                  <p className="font-semibold text-sm">{m.title}</p>
                  <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{m.description}</p>
                </div>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive shrink-0"
                  disabled={deletingId === m.id}
                  onClick={(e) => handleDelete(e, m)}
                >
                  {deletingId === m.id
                    ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    : <Trash2 className="h-3.5 w-3.5" />}
                </Button>
              </div>
            ))
        }
      </div>

      {!loading && items.length > 0 && (
        <p className="text-xs text-muted-foreground mt-3">
          {items.length} milestones · Click to edit, drag to reorder
        </p>
      )}

      <FormSheet
        open={!!editing || isAdding}
        onOpenChange={(open) => { if (!open) resetSheet(); }}
        title={editing ? `Edit: ${editing.year} — ${editing.title}` : "New Milestone"}
        onSave={handleSave}
        saveLabel={editing ? "Save Changes" : "Add Milestone"}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Year</Label>
          <Input
            value={yearValue}
            onChange={(e) => setYearValue(e.target.value)}
            placeholder="e.g. 1998"
          />
        </div>
        <div className="space-y-2">
          <Label>Title</Label>
          <Input
            value={titleValue}
            onChange={(e) => setTitleValue(e.target.value)}
            placeholder="e.g. Petro-Base Ltd Founded"
          />
        </div>
        <div className="space-y-2">
          <Label>Description</Label>
          <Textarea
            value={descValue}
            onChange={(e) => setDescValue(e.target.value)}
            rows={5}
            placeholder="Describe what happened this year..."
          />
        </div>
      </FormSheet>
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function AboutAdmin() {
  const [coreValuesActivated, setCoreValuesActivated] = useState(false);
  const [affiliatesActivated, setAffiliatesActivated] = useState(false);
  const [strengthsActivated, setStrengthsActivated] = useState(false);
  const [regionsActivated, setRegionsActivated] = useState(false);
  const [continentsActivated, setContinentsActivated] = useState(false);
  const [mapLocationsActivated, setMapLocationsActivated] = useState(false);
  const [historyActivated, setHistoryActivated] = useState(false);

  const handleTabChange = (value: string) => {
    if (value === "core-values") setCoreValuesActivated(true);
    if (value === "affiliates") setAffiliatesActivated(true);
    if (value === "strengths") setStrengthsActivated(true);
    if (value === "regions") setRegionsActivated(true);
    if (value === "continents") setContinentsActivated(true);
    if (value === "map-locations") setMapLocationsActivated(true);
    if (value === "history") setHistoryActivated(true);
  };

  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto">
      <PageHeader
        title="About Page"
        description="Manage Mission & Vision, Core Values, Affiliates, Strengths, Regions, Continents, Map Locations, and Our History."
      />

      <Tabs defaultValue="mission-vision" onValueChange={handleTabChange}>
        <TabsList>
          <TabsTrigger value="mission-vision">Mission &amp; Vision</TabsTrigger>
          <TabsTrigger value="core-values">Core Values</TabsTrigger>
          <TabsTrigger value="affiliates">Affiliates</TabsTrigger>
          <TabsTrigger value="strengths">Strengths</TabsTrigger>
          <TabsTrigger value="regions">Regions</TabsTrigger>
          <TabsTrigger value="continents">Continents</TabsTrigger>
          <TabsTrigger value="map-locations">Map Locations</TabsTrigger>
          <TabsTrigger value="history">Our History</TabsTrigger>
        </TabsList>

        <TabsContent value="mission-vision" className="mt-6">
          <MissionVisionTabContent />
        </TabsContent>

        <TabsContent value="core-values" className="mt-6">
          {coreValuesActivated && <CoreValuesTabContent />}
        </TabsContent>

        <TabsContent value="affiliates" className="mt-6">
          {affiliatesActivated && <AffiliatesTabContent />}
        </TabsContent>

        <TabsContent value="strengths" className="mt-6">
          {strengthsActivated && <StrengthsTabContent />}
        </TabsContent>

        <TabsContent value="regions" className="mt-6">
          {regionsActivated && <RegionsTabContent />}
        </TabsContent>

        <TabsContent value="continents" className="mt-6">
          {continentsActivated && <ContinentsTabContent />}
        </TabsContent>

        <TabsContent value="map-locations" className="mt-6">
          {mapLocationsActivated && <MapLocationsTabContent />}
        </TabsContent>

        <TabsContent value="history" className="mt-6">
          {historyActivated && <HistoryTabContent />}
        </TabsContent>
      </Tabs>
    </div>
  );
}
