"use client";

import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft,
  Loader2,
  Save,
  Globe,
  Search,
  Code,
  LayoutTemplate,
  Home,
  Info,
  Cpu,
  FolderKanban,
  GraduationCap,
  Users,
  Newspaper,
  Building2,
  Phone,
  Wrench,
  Award,
  MapPin,
  Mail,
  Plus,
  Trash2,
  Clock,
  MessageSquare,
  BarChart2,
  GripVertical,
  Images,
  Video,
  Upload,
} from "lucide-react";
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 { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ImageDropZone } from "@/components/admin/ImageDropZone";
import Image from "next/image";
import { toast } from "sonner";
import { useImageUpload } from "@/hooks/use-image-upload";
import { useAdminLocale } from "@/hooks/use-admin-locale";
import { uploadToCloudinary } from "@/lib/cloudinary";
import {
  getPageSeo,
  updatePageSeo,
  getPageContent,
  updatePageContent,
  type PageSeo,
  type PageContentData,
} from "@/services/pages";
import test from "node:test";

interface OfficeItem {
  city: string;
  role: string;
  company: string;
  address: string;
  phones: string[];
  emails: string[];
}

interface StatItem {
  label: string;
  value: string;
}

const PAGE_CONFIG: Record<
  string,
  { label: string; description: string; path: string; icon: React.ElementType }
> = {
  home: { label: "Home", description: "Main landing page", path: "/", icon: Home },
  about: { label: "About", description: "Company overview and history", path: "/about", icon: Info },
  services: { label: "Services", description: "Services listing page", path: "/services", icon: Wrench },
  projects: { label: "Projects", description: "Projects portfolio page", path: "/projects", icon: FolderKanban },
  technologies: { label: "Technologies", description: "Technologies and equipment", path: "/technologies", icon: Cpu },
  training: { label: "Training", description: "Training programmes overview", path: "/training", icon: GraduationCap },
  clients: { label: "Clients", description: "Client showcase page", path: "/clients", icon: Users },
  news: { label: "News", description: "News and updates", path: "/news", icon: Newspaper },
  contact: { label: "Contact", description: "Contact information page", path: "/contact", icon: Phone },
  inspectors: { label: "Inspectors", description: "Inspectors listing & marketplace page", path: "/inspectors", icon: Users },
};

// ── Default content per page (used when API returns nothing) ──────────────────

const PAGE_DEFAULTS: Record<string, PageContentData> = {
  home: {
    hero_heading: "Integrated Engineering",
    hero_heading_highlight: "& Energy Services",
    hero_subtitle:
      "Delivering advanced engineering, inspection, and energy solutions to the world's most demanding industrial environments.",
    hero_video_url: "/hero-video.mp4",
    hero_video_public_id: "",
    hero_poster_url: "/hero-refinery.jpg",
    hero_poster_public_id: "",
    hero_cta_primary_label: "Explore Services",
    hero_cta_primary_url: "#services",
    hero_cta_secondary_label: "Contact Us",
    hero_cta_secondary_url: "#contact",
    home_about_heading: "Global Leaders in Energy Engineering",
    home_about_body:
      "Petro-Base Group is a premier provider of integrated engineering services. We specialize in maintaining the integrity of critical infrastructure across the oil, gas, and renewable energy sectors. Our multidisciplinary team combines decades of field experience with cutting-edge diagnostic technology.",
    home_about_badge_value: "25+",
    home_about_badge_label: "Years of Excellence",
    home_about_stat_1_title: "Global Operations",
    home_about_stat_1_desc: "Active projects across 4 continents with localized support teams.",
    home_about_stat_2_title: "Certified Quality",
    home_about_stat_2_desc: "ISO 9001, 14001, and OHSAS 18001 accredited safety standards.",
    home_about_image_url: "/about-engineers.jpg",
    home_about_image_public_id: "",
    services_heading: "Core Capabilities",
    services_subtitle: "Providing end-to-end technical solutions for the energy lifecycle.",
    technologies_heading: "Advanced Inspection Tech",
    technologies_subtitle: "We invest in the future of non-destructive testing and robotic maintenance.",
    projects_heading: "Featured Projects",
    projects_subtitle: "Delivering engineering excellence across the globe.",
    training_heading: "Training Center",
    training_subtitle: "OSHA-compliant operator certification and safety training programs.",
    training_image_url: "",
    training_image_public_id: "",
    clients_heading: "Trusted by Industry Leaders",
    clients_subtitle: "Partnering with global energy companies to deliver excellence.",

  },
  about: {
    hero_eyebrow: "About Us",
    hero_heading: "Who We Are",
    hero_subtitle:
      "A multinational integrated Oil & Gas service company delivering excellence across continents",
    hero_image_url: "/about-hero.jpg",
    hero_image_public_id: "",
    about_heading: "About Petro-Base Group",
    about_body_1:
      "Petro-Base Group is a multinational integrated and Oil and Gas service company with Affiliates worldwide, including Petro-Base Group Ltd (Nigeria), Petro-Base Group, LLC (USA), Petro Base Group (PTY) Ltd (South Africa), Petro Base Group CC (Namibia), Petro Base Group, Inc. (Guyana), Petro Base, LTD (Uganda), Petro Base Group, LDA (Mozambique) and other associates companies around the world.",
    about_body_2:
      "Over the years, Petro-Base has successfully executed a diverse range of services including: {services} for various companies worldwide, including Exxon Mobil, Chevron, Shell, SNEPCO, Total, NCOC, and many more, under a sterling safety record.",
    stat_1_value: "Since 1998",
    stat_1_label: "Established",
    stat_2_value: "3+",
    stat_2_label: "Continents",
    about_images: [] as { url: string; alt: string; public_id: string }[],
    years_badge_value: "25+",
    years_badge_label: "Years of Excellence",
    history_heading: "Our History",
    history_subtitle: "Over two decades of growth, innovation, and global expansion in integrated energy services.",
    strengths_heading: "Our Strengths",
    strengths_subtitle: "What sets us apart in the global energy sector",
    affiliates_heading: "Our Affiliates",
    affiliates_subtitle: "Operating entities across the globe",
    mvv_heading: "Mission, Vision & Values",
    core_values_heading: "Core Values",
    global_presence_heading: "Global Presence",
    global_presence_subtitle: "Operating across 4 continents with localized support",
  },
  services: {
    hero_eyebrow: "Petro-Base Group",
    hero_heading: "Our Services",
    hero_subtitle:
      "Comprehensive engineering, inspection, and technical solutions across the entire energy lifecycle.",
    hero_image_url: "/services-hero.jpg",
    hero_image_public_id: "",
    section_heading: "What We Do",
    section_subtitle: "Seven core service verticals spanning the full energy infrastructure lifecycle.",
  },
  projects: {
    hero_eyebrow: "Case Studies",
    hero_heading: "Our Projects",
    hero_subtitle: "Proven project execution across four continents.",
    hero_image_url: "/project-offshore.jpg",
    hero_image_public_id: "",
    section_heading: "Our Projects",
    section_subtitle: "Real-world results from our global operations — offshore platforms, tank farms, gas distribution, and drilling campaigns.",
    stats: [
      { label: "Projects Completed", value: "500+" },
      { label: "Countries Served", value: "15+" },
      { label: "Years of Experience", value: "25+" },
      { label: "Client Satisfaction", value: "99%" },
    ],
  },
  technologies: {
    hero_eyebrow: "Petro-Base Group",
    hero_heading: "Our Technologies",
    hero_subtitle: "Advanced inspection and engineering technology solutions.",
    hero_image_url: "/tech-hero.jpg",
    hero_image_public_id: "",
    section_heading: "Advanced Inspection Technologies",
    section_subtitle: "Purpose-built equipment and proprietary systems for precision asset integrity assessment.",
  },
  training: {
    hero_eyebrow: "Training Centre",
    hero_heading: "Training Programmes",
    hero_subtitle: "Industry-accredited training for oil & gas professionals.",
    hero_image_url: "/training-center.jpg",
    hero_image_public_id: "",
    section_heading: "Training Programs",
    section_subtitle: "Comprehensive operator certification courses designed to international safety standards.",
  },
  clients: {
    hero_eyebrow: "Our Clients",
    hero_heading: "Trusted By Industry Leaders",
    hero_subtitle: "Long-standing partnerships with the world's leading energy companies.",
    hero_image_url: "/client.jpeg",
    hero_image_public_id: "",
    section_heading: "Our Partners",
    section_subtitle: "A selection of the major operators and service companies we proudly serve.",
  },
  news: {
    hero_eyebrow: "Latest News",
    hero_heading: "News & Updates",
    hero_subtitle: "Company news, project updates, and industry insights.",
    hero_image_url: "/project-offshore.jpg",
    hero_image_public_id: "",
    section_heading: "Latest Stories",
    section_subtitle: "Stay up to date with Petro-Base Group's latest projects, milestones, and industry updates.",
  },
  inspectors: {
    hero_eyebrow: "Inspection Resource Marketplace",
    hero_heading: "Our Inspectors",
    hero_subtitle: "Browse our roster of certified inspection professionals available for on-demand deployment.",
    hero_image_url: "",
    hero_image_public_id: "",
    section_heading: "Certified Inspection Professionals",
    section_subtitle: "Each inspector is vetted, certified, and ready to deploy to your site — onshore or offshore.",
  },
  // contact defaults intentionally removed — contact page uses API-only data
};

function emptySeo(slug: string): PageSeo {
  return {
    slug,
    meta_title: "",
    meta_description: "",
    og_title: "",
    og_description: "",
    og_image_url: "",
    og_image_public_id: "",
    canonical_url: "",
    no_index: false,
    schema_json: "",
  };
}

// ── Component ─────────────────────────────────────────────────────────────────

export default function PageEditor() {
  const params = useParams();
  const slug = typeof params.slug === "string" ? params.slug : "";
  const config = PAGE_CONFIG[slug];
  const locale = useAdminLocale();

  // Content state
  const [content, setContent] = useState<PageContentData>({});
  const [contentLoading, setContentLoading] = useState(true);
  const [contentSaving, setContentSaving] = useState(false);
  const [heroImgProgress, setHeroImgProgress] = useState<number | null>(null);

  // SEO state
  const [seoForm, setSeoForm] = useState<PageSeo>(emptySeo(slug));
  const [seoLoading, setSeoLoading] = useState(true);
  const [seoSaving, setSeoSaving] = useState(false);
  const [ogImgProgress, setOgImgProgress] = useState<number | null>(null);

  // Image upload hooks — one for hero/poster, one for OG image, one for about slider, one for home about image
  const heroUpload = useImageUpload();
  const ogUpload = useImageUpload();
  const sliderImgUpload = useImageUpload();
  const homeAboutImgUpload = useImageUpload();
  const [homeAboutImgProgress, setHomeAboutImgProgress] = useState<number | null>(null);
  const homeTrainingImgUpload = useImageUpload();
  const [homeTrainingImgProgress, setHomeTrainingImgProgress] = useState<number | null>(null);

  // Home hero video upload
  const heroVideoInputRef = useRef<HTMLInputElement>(null);
  const [heroVideoFile, setHeroVideoFile] = useState<File | null>(null);
  const [heroVideoFileName, setHeroVideoFileName] = useState<string>("");
  const [heroVideoProgress, setHeroVideoProgress] = useState<number | null>(null);
  const [heroVideoDragging, setHeroVideoDragging] = useState(false);

  // About slider image state
  const [newSlideAlt, setNewSlideAlt] = useState("");
  const [pendingSlides, setPendingSlides] = useState<{ file: File; previewUrl: string; alt: string }[]>([]);
  const sliderFileInputRef = useRef<HTMLInputElement>(null);

  // Schema JSON validation state for SEO editor
  const [schemaJsonError, setSchemaJsonError] = useState<string>("");

  // Helpers
  const setC = (key: string, value: unknown) =>
    setContent((prev) => ({ ...prev, [key]: value }));

  // About slider image helpers
  type SlideItem = { url: string; alt: string; public_id: string };
  const getSlides = () =>
    Array.isArray(content.about_images) ? (content.about_images as SlideItem[]) : [];

  const handleStageSlideImage = () => {
    if (!sliderImgUpload.file || !sliderImgUpload.preview) {
      toast.error("Please select an image first.");
      return;
    }
    setPendingSlides((prev) => [
      ...prev,
      { file: sliderImgUpload.file!, previewUrl: sliderImgUpload.preview!, alt: newSlideAlt.trim() },
    ]);
    sliderImgUpload.reset();
    setNewSlideAlt("");
  };
  const setSeo = <K extends keyof PageSeo>(k: K, v: PageSeo[K]) =>
    setSeoForm((prev) => ({ ...prev, [k]: v }));

  // Lazy-loading: fetch content or SEO only when their tab is activated
  const [selectedTab, setSelectedTab] = useState<string>("content");
  const [contentLoaded, setContentLoaded] = useState(false);
  const [seoLoaded, setSeoLoaded] = useState(false);

  const fetchContent = async () => {
    if (!config) return;
    setContentLoading(true);
    try {
      const defaults = PAGE_DEFAULTS[slug] ?? {};
      const contentRes = await getPageContent(slug);
      if (slug === "home") {
        if (contentRes) {
          const api = contentRes as Record<string, any>;
          const mapped = {
            hero_heading: api.hero?.heading ?? api.hero_heading ?? "",
            hero_heading_highlight: api.hero?.heading_highlight ?? api.hero_heading_highlight ?? "",
            hero_subtitle: api.hero?.subtitle ?? api.hero_subtitle ?? "",
            hero_video_url: api.hero?.video_url ?? api.hero_video_url ?? "",
            hero_video_public_id: api.hero?.video_public_id ?? api.hero_video_public_id ?? "",
            hero_poster_url: api.hero?.poster_url ?? api.hero_poster_url ?? "",
            hero_poster_public_id: api.hero?.poster_public_id ?? api.hero_poster_public_id ?? "",
            hero_cta_primary_label: api.hero?.cta_primary?.label ?? api.hero_cta_primary_label ?? "",
            hero_cta_primary_url: api.hero?.cta_primary?.url ?? api.hero_cta_primary_url ?? "",
            hero_cta_secondary_label: api.hero?.cta_secondary?.label ?? api.hero_cta_secondary_label ?? "",
            hero_cta_secondary_url: api.hero?.cta_secondary?.url ?? api.hero_cta_secondary_url ?? "",
            home_about_heading: api.about?.heading ?? api.home_about_heading ?? "",
            home_about_body: api.about?.body ?? api.home_about_body ?? "",
            home_about_badge_value: api.about?.badge?.value ?? api.home_about_badge_value ?? "",
            home_about_badge_label: api.about?.badge?.label ?? api.home_about_badge_label ?? "",
            home_about_stat_1_title: api.about?.stats?.[0]?.title ?? api.home_about_stat_1_title ?? "",
            home_about_stat_1_desc: api.about?.stats?.[0]?.desc ?? api.home_about_stat_1_desc ?? "",
            home_about_stat_2_title: api.about?.stats?.[1]?.title ?? api.home_about_stat_2_title ?? "",
            home_about_stat_2_desc: api.about?.stats?.[1]?.desc ?? api.home_about_stat_2_desc ?? "",
            home_about_image_url: api.about?.image_url ?? api.home_about_image_url ?? "",
            home_about_image_public_id: api.about?.image_public_id ?? api.home_about_image_public_id ?? "",
            services_heading: api.section_headings?.services?.heading ?? api.services_heading ?? "",
            services_subtitle: api.section_headings?.services?.subtitle ?? api.services_subtitle ?? "",
            technologies_heading: api.section_headings?.technologies?.heading ?? api.technologies_heading ?? "",
            technologies_subtitle: api.section_headings?.technologies?.subtitle ?? api.technologies_subtitle ?? "",
            projects_heading: api.section_headings?.projects?.heading ?? api.projects_heading ?? "",
            projects_subtitle: api.section_headings?.projects?.subtitle ?? api.projects_subtitle ?? "",
            training_heading: api.section_headings?.training?.heading ?? api.training_heading ?? "",
            training_subtitle: api.section_headings?.training?.subtitle ?? api.training_subtitle ?? "",
            training_image_url: api.section_headings?.training?.image_url ?? api.training_image_url ?? "",
            training_image_public_id: api.section_headings?.training?.image_public_id ?? api.training_image_public_id ?? "",
            clients_heading: api.section_headings?.clients?.heading ?? api.clients_heading ?? "",
            clients_subtitle: api.section_headings?.clients?.subtitle ?? api.clients_subtitle ?? "",
          } as Record<string, any>;
          setContent({ ...(defaults as any), ...(mapped as any) });
        } else {
          setContent({ ...(defaults as any) });
        }
      } else if (slug === "contact") {
        if (contentRes) {
          const api = contentRes as Record<string, any>;
          const bh = Array.isArray(api.business_hours) ? api.business_hours : [];
          const findHours = (label: string) => {
            const item = bh.find((b: any) => String(b.day ?? "").includes(label));
            return item?.hours ?? "";
          };

          const mapped = {
            hero_eyebrow: api.hero_eyebrow ?? api.hero?.label ?? "",
            hero_heading: api.hero_heading ?? api.hero?.title ?? "",
            hero_subtitle: api.hero_subtitle ?? api.hero?.description ?? "",
            hero_image_url: api.hero_image_url ?? api.hero?.image_url ?? "",
            hero_image_public_id: api.hero_image_public_id ?? api.hero?.image_public_id ?? "",
            hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",

            form_title: api.form_title ?? api.form_section?.title ?? "",
            form_subtitle: api.form_subtitle ?? api.form_section?.subtitle ?? "",

            offices_heading: api.offices_heading ?? api.offices_section?.title ?? "",
            offices_subtitle: api.offices_subtitle ?? api.offices_section?.subtitle ?? "",

            biz_hours_mon_fri: api.biz_hours_mon_fri ?? findHours("Monday") ?? "",
            biz_hours_sat: api.biz_hours_sat ?? findHours("Saturday") ?? "",
            biz_hours_sun: api.biz_hours_sun ?? findHours("Sunday") ?? "",
            biz_hours_emergency: api.biz_hours_emergency ?? findHours("Emergency") ?? "",

            offices: Array.isArray(api.offices) ? api.offices : [],
          } as Record<string, any>;
          setContent(mapped as PageContentData);
        } else {
          setContent({});
        }
      } else if (slug === "about") {
        if (contentRes) {
          const api = contentRes as Record<string, any>;
          const mapped = {
            hero_eyebrow: api.hero?.label ?? api.hero_eyebrow ?? "",
            hero_heading: api.hero?.title ?? api.hero_heading ?? "",
            hero_subtitle: api.hero?.description ?? api.hero_subtitle ?? "",
            hero_image_url: api.hero?.image_url ?? api.hero_image_url ?? "",
            hero_image_public_id: api.hero?.image_public_id ?? api.hero_image_public_id ?? "",
            hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",
            about_heading: api.about?.heading ?? api.about_heading ?? "",
            about_body_1: api.about?.body_1 ?? api.about_body_1 ?? "",
            about_body_2: api.about?.body_2 ?? api.about_body_2 ?? "",
            about_images: Array.isArray(api.about?.images ?? api.about_images) ? (api.about?.images ?? api.about_images) : [],
            stat_1_value: api.stats?.[0]?.value ?? api.stat_1_value ?? "",
            stat_1_label: api.stats?.[0]?.label ?? api.stat_1_label ?? "",
            stat_2_value: api.stats?.[1]?.value ?? api.stat_2_value ?? "",
            stat_2_label: api.stats?.[1]?.label ?? api.stat_2_label ?? "",
            years_badge_value: api.badge?.value ?? api.years_badge_value ?? "",
            years_badge_label: api.badge?.label ?? api.years_badge_label ?? "",
            history_heading: api.section_headings?.history?.heading ?? api.history_heading ?? "",
            history_subtitle: api.section_headings?.history?.subtitle ?? api.history_subtitle ?? "",
            strengths_heading: api.section_headings?.strengths?.heading ?? api.strengths_heading ?? "",
            strengths_subtitle: api.section_headings?.strengths?.subtitle ?? api.strengths_subtitle ?? "",
            affiliates_heading: api.section_headings?.affiliates?.heading ?? api.affiliates_heading ?? "",
            affiliates_subtitle: api.section_headings?.affiliates?.subtitle ?? api.affiliates_subtitle ?? "",
            mvv_heading: api.section_headings?.mvv?.heading ?? api.mvv_heading ?? "",
            core_values_heading: api.section_headings?.core_values?.heading ?? api.core_values_heading ?? "",
            global_presence_heading: api.section_headings?.global_presence?.heading ?? api.global_presence_heading ?? "",
            global_presence_subtitle: api.section_headings?.global_presence?.subtitle ?? api.global_presence_subtitle ?? "",
          } as Record<string, any>;
          setContent({ ...(defaults as any), ...(mapped as any) });
        } else {
          setContent({ ...(defaults as any) });
        }
      } else if (slug === "news" || slug === "technologies" || slug === "services" || slug === "inspectors") {
        if (contentRes) {
          const api = contentRes as Record<string, any>;
          const mapped = {
            hero_eyebrow: api.hero?.label ?? api.hero_eyebrow ?? "",
            hero_heading: api.hero?.title ?? api.hero_heading ?? "",
            hero_subtitle: api.hero?.description ?? api.hero_subtitle ?? "",
            hero_image_url: api.hero?.image_url ?? api.hero_image_url ?? "",
            hero_image_public_id: api.hero?.image_public_id ?? api.hero_image_public_id ?? "",
            hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",
            section_heading: api.section_heading ?? "",
            section_subtitle: api.section_subtitle ?? "",
          } as Record<string, any>;

          setContent({ ...(defaults as any), ...(mapped as any), ...(api ?? {}) });
        } else {
          setContent({ ...(defaults as any) });
        }
      } else if (slug === "training") {
         if (contentRes) {
          const api = contentRes as Record<string, any>;
          const mapped = {
            hero_eyebrow: api.hero?.label ?? api.hero_eyebrow ?? "",
            hero_heading: api.hero?.title ?? api.hero_heading ?? "",
            hero_subtitle: api.hero?.description ?? api.hero_subtitle ?? "",
            hero_image_url: api.hero?.image_url ?? api.hero_image_url ?? "",
            hero_image_public_id: api.hero?.image_public_id ?? api.hero_image_public_id ?? "",
            hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",
            training_section_heading: api.training_section_heading ?? "",
            training_section_subtitle: api.training_section_subtitle ?? "",
          } as Record<string, any>;

          setContent({ ...(defaults as any), ...(mapped as any), ...(api ?? {}) });
        }
      } else if (slug === "clients") {
        if (contentRes) {
          const api = contentRes as Record<string, any>;
          const mapped = {
            hero_eyebrow: api.hero?.label ?? api.hero_eyebrow ?? "",
            hero_heading: api.hero?.title ?? api.hero_heading ?? "",
            hero_subtitle: api.hero?.description ?? api.hero_subtitle ?? "",
            hero_image_url: api.hero?.image_url ?? api.hero_image_url ?? "",
            hero_image_public_id: api.hero?.image_public_id ?? api.hero_image_public_id ?? "",
            hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",
            section_heading: api.section_heading ?? "",
            section_subtitle: api.section_subtitle ?? "",
            testimonial_section_heading: api.testimonial_section_heading ?? "",
            testimonial_section_subtitle: api.testimonial_section_subtitle ?? "",
            industry_section_heading: api.industry_section_heading ?? "",
            industry_section_subtitle: api.industry_section_subtitle ?? "",
          } as Record<string, any>;

          setContent({ ...(defaults as any), ...(mapped as any), ...(api ?? {}) });
        }
      } else if (slug === "projects") {
          if (contentRes) {
            const api = contentRes as Record<string, any>;
            const mapped = {
              hero_eyebrow: api.hero?.label ?? api.hero_eyebrow ?? "",
              hero_heading: api.hero?.title ?? api.hero_heading ?? "",
              hero_subtitle: api.hero?.description ?? api.hero_subtitle ?? "",
              hero_image_url: api.hero?.image_url ?? api.hero_image_url ?? "",
              hero_image_public_id: api.hero?.image_public_id ?? api.hero_image_public_id ?? "",
              hero_image_alt: api.hero?.image_alt ?? api.hero_image_alt ?? "",
              section_heading: api.section_heading ?? "",
              section_subtitle: api.section_subtitle ?? "",
              stats: Array.isArray(api.stats) ? api.stats : (defaults as any).stats ?? [],
            } as Record<string, any>;

            setContent({ ...(defaults as any), ...(mapped as any) });
          } else {
            setContent({ ...(defaults as any) });
          }
        } else {
          setContent({ ...(defaults as any), ...(contentRes ?? {}) });
        }
        setContentLoaded(true);
      } catch {
        setContent({});
      } finally {
        setContentLoading(false);
      }
    };

    const fetchSeo = async () => {
      if (!config) return;
      setSeoLoading(true);
      try {
        const res = await getPageSeo(slug);
        const rawSeo = (res as any)?.data ?? res ?? emptySeo(slug);
        const normalizedSeo: any = {
          ...emptySeo(slug),
          meta_title: rawSeo.meta_title ?? "",
          meta_description: rawSeo.meta_description ?? "",
          og_title: rawSeo.og_title ?? "",
          og_description: rawSeo.og_description ?? "",
          og_image_url: rawSeo.og_image_url ?? "",
          og_image_public_id: rawSeo.og_image_public_id ?? "",
          canonical_url: rawSeo.canonical_url ?? "",
          no_index: rawSeo.no_index ?? false,
          schema_json: rawSeo.schema_json ?? "",
          slug: rawSeo.slug ?? slug,
        };

        if (normalizedSeo.schema_json && typeof normalizedSeo.schema_json === "object") {
          try {
            normalizedSeo.schema_json = JSON.stringify(normalizedSeo.schema_json, null, 2);
          } catch {
            normalizedSeo.schema_json = String(normalizedSeo.schema_json ?? "");
          }
        } else {
          normalizedSeo.schema_json = String(normalizedSeo.schema_json ?? "");
        }

        setSeoForm(normalizedSeo as PageSeo);
        setSeoLoaded(true);
      } catch {
        setSeoForm(emptySeo(slug));
      } finally {
        setSeoLoading(false);
      }
    };

    // Trigger fetch when a tab becomes active
    useEffect(() => {
      if (!config) return;
      if (selectedTab === "content" && !contentLoaded) fetchContent();
      if (selectedTab === "seo" && !seoLoaded) fetchSeo();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedTab, slug, config]);

    // Per-slug hero upload-signature endpoints
    const HERO_UPLOAD_SIGNATURE_URL: Record<string, string> = {
      contact: "/api/pages/contact/content/hero/upload-signature",
      news: "/api/pages/news/content/hero/upload-signature",
      clients: "/api/pages/clients/content/hero/upload-signature",
      training: "/api/pages/training/content/hero/upload-signature",
      technologies: "/api/pages/technologies/content/hero/upload-signature",
      projects: "/api/pages/projects/content/hero/upload-signature",
      services: "/api/pages/services/content/hero/upload-signature",
      about: "/api/pages/about/content/hero/upload-signature",
      inspector: "/api/pages/inspector/content/hero/upload-signature",
      inspectors: "/api/pages/inspectors/content/hero/upload-signature",
      home: "/api/pages/home/content/hero/poster/upload-signature"
    };
    const heroUploadSignatureUrl =
      HERO_UPLOAD_SIGNATURE_URL[slug] ?? "/api/pages/upload-signature";

    // Per-slug OG image upload-signature endpoints for SEO
    const OG_UPLOAD_SIGNATURE_URL: Record<string, string> = {
      contact: "/api/pages/contact/seo/og-image/upload-signature",
      news: "/api/pages/news/seo/og-image/upload-signature",
      clients: "/api/pages/clients/seo/og-image/upload-signature",
      training: "/api/pages/training/seo/og-image/upload-signature",
      technologies: "/api/pages/technologies/seo/og-image/upload-signature",
      projects: "/api/pages/projects/seo/og-image/upload-signature",
      services: "/api/pages/services/seo/og-image/upload-signature",
      about: "/api/pages/about/seo/og-image/upload-signature",
      inspector: "/api/pages/inspector/seo/og-image/upload-signature",
      inspectors: "/api/pages/inspectors/seo/og-image/upload-signature",
      home: "/api/pages/home/seo/og-image/upload-signature",
    };
    const ogUploadSignatureUrl = OG_UPLOAD_SIGNATURE_URL[slug] ?? "/api/pages/upload-signature";

    // Save content
    const handleSaveContent = async () => {
      setContentSaving(true);
      try {
        const imgUrlKey = slug === "home" ? "hero_poster_url" : "hero_image_url";
        const imgPubIdKey = slug === "home" ? "hero_poster_public_id" : "hero_image_public_id";
        const updated = { ...content };

        if (heroUpload.file) {
          setHeroImgProgress(0);
          const res = await uploadToCloudinary(
            heroUpload.file,
            "image",
            setHeroImgProgress,
            heroUploadSignatureUrl,
          );
          updated[imgUrlKey] = res.secure_url;
          updated[imgPubIdKey] = res.public_id;
          setHeroImgProgress(null);
          heroUpload.reset();
        }

        // Upload home hero video
        if (slug === "home" && heroVideoFile) {
          setHeroVideoProgress(0);
          const res = await uploadToCloudinary(
            heroVideoFile,
            "video",
            setHeroVideoProgress,
            "/api/pages/home/content/hero/video/upload-signature",
          );
          updated.hero_video_url = res.secure_url;
          (updated as any).hero_video_public_id = res.public_id;
          setContent((prev) => ({ ...prev, hero_video_url: res.secure_url, hero_video_public_id: res.public_id }));
          setHeroVideoProgress(null);
          setHeroVideoFile(null);
          setHeroVideoFileName("");
        }

        // Upload home about-section image
        if (slug === "home" && homeAboutImgUpload.file) {
          setHomeAboutImgProgress(0);
          const res = await uploadToCloudinary(
            homeAboutImgUpload.file,
            "image",
            setHomeAboutImgProgress,
            "/api/pages/home/content/about/image/upload-signature",
          );
          updated.home_about_image_url = res.secure_url;
          updated.home_about_image_public_id = res.public_id;
          setHomeAboutImgProgress(null);
          homeAboutImgUpload.reset();
        }

        // Upload home training-section image
        if (slug === "home" && homeTrainingImgUpload.file) {
          setHomeTrainingImgProgress(0);
          const res = await uploadToCloudinary(
            homeTrainingImgUpload.file,
            "image",
            setHomeTrainingImgProgress,
            "/api/pages/home/content/training/image/upload-signature",
          );
          (updated as any).training_image_url = res.secure_url;
          (updated as any).training_image_public_id = res.public_id;
          setHomeTrainingImgProgress(null);
          homeTrainingImgUpload.reset();
        }

        // Upload any staged about slider images
        if (slug === "about" && pendingSlides.length > 0) {
          const uploaded = await Promise.all(
            pendingSlides.map(async (s) => {
              const res = await uploadToCloudinary(
                s.file,
                "image",
                undefined,
                "/api/pages/about/content/hero/upload-signature",
              );
              return { url: res.secure_url, alt: s.alt, public_id: res.public_id };
            }),
          );
          const existing = Array.isArray(updated.about_images)
            ? (updated.about_images as SlideItem[])
            : [];
          updated.about_images = [...existing, ...uploaded];
          setPendingSlides([]);
        }

        // Transform payload per page
        let payload = updated;
        if (slug === "home") {
          payload = {
            hero: {
              heading: (updated as any).hero_heading ?? "",
              heading_highlight: (updated as any).hero_heading_highlight ?? "",
              subtitle: (updated as any).hero_subtitle ?? "",
              cta_primary: {
                label: (updated as any).hero_cta_primary_label ?? "",
                url: (updated as any).hero_cta_primary_url ?? "",
              },
              cta_secondary: {
                label: (updated as any).hero_cta_secondary_label ?? "",
                url: (updated as any).hero_cta_secondary_url ?? "",
              },
              video_url: (updated as any).hero_video_url ?? "",
              video_public_id: (updated as any).hero_video_public_id ?? "",
              poster_url: (updated as any).hero_poster_url ?? "",
              poster_public_id: (updated as any).hero_poster_public_id ?? "",
            },
            about: {
              heading: (updated as any).home_about_heading ?? "",
              body: (updated as any).home_about_body ?? "",
              badge: {
                value: (updated as any).home_about_badge_value ?? "",
                label: (updated as any).home_about_badge_label ?? "",
              },
              stats: [
                { title: (updated as any).home_about_stat_1_title ?? "", desc: (updated as any).home_about_stat_1_desc ?? "" },
                { title: (updated as any).home_about_stat_2_title ?? "", desc: (updated as any).home_about_stat_2_desc ?? "" },
              ],
              image_url: (updated as any).home_about_image_url ?? "",
              image_public_id: (updated as any).home_about_image_public_id ?? "",
            },
            section_headings: {
              services: { heading: (updated as any).services_heading ?? "", subtitle: (updated as any).services_subtitle ?? "" },
              technologies: { heading: (updated as any).technologies_heading ?? "", subtitle: (updated as any).technologies_subtitle ?? "" },
              projects: { heading: (updated as any).projects_heading ?? "", subtitle: (updated as any).projects_subtitle ?? "" },
              training: { heading: (updated as any).training_heading ?? "", subtitle: (updated as any).training_subtitle ?? "", image_url: (updated as any).training_image_url ?? "", image_public_id: (updated as any).training_image_public_id ?? "" },
              clients: { heading: (updated as any).clients_heading ?? "", subtitle: (updated as any).clients_subtitle ?? "" },
            },
          };
        } else if (slug === "about") {
          payload = {
            hero: {
              label: updated.hero_eyebrow ?? "",
              title: updated.hero_heading ?? "",
              description: updated.hero_subtitle ?? "",
              image_url: updated.hero_image_url ?? "",
              image_public_id: updated.hero_image_public_id ?? "",
              image_alt: (updated as any).hero_image_alt ?? "",
            },
            about: {
              heading: (updated as any).about_heading ?? "",
              body_1: (updated as any).about_body_1 ?? "",
              body_2: (updated as any).about_body_2 ?? "",
              images: Array.isArray(updated.about_images) ? updated.about_images : [],
            },
            stats: [
              { value: (updated as any).stat_1_value ?? "", label: (updated as any).stat_1_label ?? "" },
              { value: (updated as any).stat_2_value ?? "", label: (updated as any).stat_2_label ?? "" },
            ],
            badge: {
              value: (updated as any).years_badge_value ?? "",
              label: (updated as any).years_badge_label ?? "",
            },
            section_headings: {
              history: { heading: (updated as any).history_heading ?? "", subtitle: (updated as any).history_subtitle ?? "" },
              strengths: { heading: (updated as any).strengths_heading ?? "", subtitle: (updated as any).strengths_subtitle ?? "" },
              affiliates: { heading: (updated as any).affiliates_heading ?? "", subtitle: (updated as any).affiliates_subtitle ?? "" },
              mvv: { heading: (updated as any).mvv_heading ?? "" },
              core_values: { heading: (updated as any).core_values_heading ?? "" },
              global_presence: { heading: (updated as any).global_presence_heading ?? "", subtitle: (updated as any).global_presence_subtitle ?? "" },
            },
          };
        } else if (slug === "contact") {
          payload = {
            hero: {
              label: updated.hero_eyebrow ?? "",
              title: updated.hero_heading ?? "",
              description: updated.hero_subtitle ?? "",
              image_url: updated.hero_image_url ?? "",
              image_public_id: updated.hero_image_public_id ?? "",
              image_alt: (updated as any).hero_image_alt ?? "",
            },
            form_section: {
              title: updated.form_title ?? "",
              subtitle: updated.form_subtitle ?? "",
            },
            business_hours: [
              { day: "Monday – Friday", hours: updated.biz_hours_mon_fri ?? "" },
              { day: "Saturday", hours: updated.biz_hours_sat ?? "" },
              { day: "Sunday", hours: updated.biz_hours_sun ?? "" },
              { day: "Emergency Support", hours: updated.biz_hours_emergency ?? "" },
            ],
            offices_section: {
              title: updated.offices_heading ?? "",
              subtitle: updated.offices_subtitle ?? "",
            },
            offices: updated.offices ?? [],
          };
        } else if (slug === "news" || slug === "services" || slug === "technologies" || slug === "inspectors") {
          payload = {
            hero: {
              label: updated.hero_eyebrow ?? "",
              title: updated.hero_heading ?? "",
              description: updated.hero_subtitle ?? "",
              image_url: updated.hero_image_url ?? "",
              image_public_id: updated.hero_image_public_id ?? "",
              image_alt: (updated as any).hero_image_alt ?? "",
            },
            section_heading: (updated as any).section_heading ?? "",
            section_subtitle: (updated as any).section_subtitle ?? "",
          };
        } else if (slug === "clients") {
          payload = {
            hero: {
              label: updated.hero_eyebrow ?? "",
              title: updated.hero_heading ?? "",
              description: updated.hero_subtitle ?? "",
              image_url: updated.hero_image_url ?? "",
              image_public_id: updated.hero_image_public_id ?? "",
              image_alt: (updated as any).hero_image_alt ?? "",
            },
            section_heading: (updated as any).section_heading ?? "",
            section_subtitle: (updated as any).section_subtitle ?? "",
            testimonial_section_heading: (updated as any).testimonial_section_heading ?? "",
            testimonial_section_subtitle: (updated as any).testimonial_section_subtitle ?? "",
            industry_section_heading: (updated as any).industry_section_heading ?? "",
            industry_section_subtitle: (updated as any).industry_section_subtitle ?? "",
          };
        } else if (slug === "training") {
          payload = {
            // [locale]: {
              hero: {
                label: updated.hero_eyebrow ?? "",
                title: updated.hero_heading ?? "",
                description: updated.hero_subtitle ?? "",
                image_url: updated.hero_image_url ?? "",
                image_public_id: updated.hero_image_public_id ?? "",
                image_alt: (updated as any).hero_image_alt ?? "",
              },
              section_heading: (updated as any).section_heading ?? "",
              section_subtitle: (updated as any).section_subtitle ?? "",
              training_section_heading: (updated as any).training_section_heading ?? "",
              training_section_subtitle: (updated as any).training_section_subtitle ?? "",
            // },
          };
        } else if (slug === "projects") {
          payload = {
            hero: {
              label: updated.hero_eyebrow ?? "",
              title: updated.hero_heading ?? "",
              description: updated.hero_subtitle ?? "",
              image_url: updated.hero_image_url ?? "",
              image_public_id: updated.hero_image_public_id ?? "",
              image_alt: (updated as any).hero_image_alt ?? "",
            },
            section_heading: (updated as any).section_heading ?? "",
            section_subtitle: (updated as any).section_subtitle ?? "",
            stats: (updated as any).stats ?? [],
          };
        }
        await updatePageContent(slug, payload);
        setContent(updated);
        toast.success("Page content saved.");
      } catch {
        // errors handled by the API interceptor
      } finally {
        setContentSaving(false);
      }
    };

    // Save SEO
    const handleSaveSeo = async () => {
      setSeoSaving(true);
      try {
        let ogUrl = seoForm.og_image_url;
        let ogPubId = seoForm.og_image_public_id;
        if (ogUpload.file) {
          setOgImgProgress(0);
          const res = await uploadToCloudinary(
            ogUpload.file,
            "image",
            setOgImgProgress,
            ogUploadSignatureUrl,
          );
          ogUrl = res.secure_url;
          ogPubId = res.public_id;
          setOgImgProgress(null);
          ogUpload.reset();
        }

        // Prepare payload: attempt to parse schema_json string into object if valid JSON
        const payload: any = { ...seoForm, og_image_url: ogUrl, og_image_public_id: ogPubId };
        if (typeof payload.schema_json === "string") {
          const txt = payload.schema_json.trim();
          if (txt) {
            try {
              payload.schema_json = JSON.parse(txt);
            } catch {
              // leave as string if parse fails
              payload.schema_json = txt;
            }
          } else {
            payload.schema_json = "";
          }
        }

        await updatePageSeo(slug, payload);
        // Keep textarea-friendly string representation in form state
        setSeoForm((prev) => ({ ...prev, og_image_url: ogUrl, og_image_public_id: ogPubId }));
        toast.success("SEO settings saved.");
      } catch {
        // errors handled by the API interceptor
      } finally {
        setSeoSaving(false);
      }
    };

    // Unknown slugs
    if (!config) {
      return (
        <div className="flex flex-col items-center justify-center py-24 gap-4">
          <p className="text-muted-foreground">Page &quot;{slug}&quot; not found.</p>
          <Link href="/admin/pages">
            <Button variant="outline" size="sm">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Pages
            </Button>
          </Link>
        </div>
      );
    }

    const PageIcon = config.icon;
    const isLoading = selectedTab === "seo" ? seoLoading : contentLoading;

    // ── Reusable hero image upload section (standard pages) ───────────────────
    const heroImgUrlKey = slug === "home" ? "hero_poster_url" : "hero_image_url";

    // For contact, prefer API hero object fields; guard hero as object
    const heroObj = typeof content.hero === "object" && content.hero !== null ? (content.hero as Record<string, any>) : {};
    const contactHeroImageUrl = (content as Record<string, any>).hero_image_url || heroObj.image_url || "";
    const contactHeroImagePublicId = (content as Record<string, any>).hero_image_public_id || heroObj.image_public_id || "";

    const standardHeroSection = (
      <section className="space-y-4">
        <div className="flex items-center gap-2">
          <LayoutTemplate className="h-4 w-4 text-muted-foreground" />
          <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
            Hero Section
          </h2>
        </div>
        <Separator />
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-1.5">
            <Label>Eyebrow / Label</Label>
            <Input
              value={String(content.hero_eyebrow ?? heroObj.label ?? "")}
              onChange={(e) => setC("hero_eyebrow", e.target.value)}
              placeholder="e.g. About Us"
            />
          </div>
          <div className="space-y-1.5">
            <Label>Page Heading</Label>
            <Input
              value={String(content.hero_heading ?? heroObj.title ?? "")}
              onChange={(e) => setC("hero_heading", e.target.value)}
              placeholder="e.g. Who We Are"
            />
          </div>
        </div>
        <div className="space-y-1.5">
          <Label>Subtitle</Label>
          <Textarea
            value={String(content.hero_subtitle ?? heroObj.description ?? "")}
            onChange={(e) => setC("hero_subtitle", e.target.value)}
            rows={2}
            className="resize-none"
            placeholder="Supporting subtitle text…"
          />
        </div>
        <div className="space-y-1.5">
          <Label>
            Background Image{" "}
            <span className="text-muted-foreground font-normal">(1920×1080px recommended)</span>
          </Label>
          <input
            ref={heroUpload.inputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => {
              if (e.target.files?.[0]) heroUpload.handleFile(e.target.files[0]);
            }}
          />
          <ImageDropZone
            preview={heroUpload.preview}
            fallback={slug === "contact" ? (contactHeroImageUrl || undefined) : (String(content[heroImgUrlKey] ?? "") || undefined)}
            isDragging={heroUpload.isDragging}
            onDragOver={(e) => {
              e.preventDefault();
              heroUpload.setIsDragging(true);
            }}
            onDragLeave={() => heroUpload.setIsDragging(false)}
            onDrop={heroUpload.onDrop}
            onClick={() => heroUpload.inputRef.current?.click()}
          />
          {heroImgProgress !== null && (
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <Loader2 className="h-3 w-3 animate-spin" />
              Uploading… {heroImgProgress}%
            </div>
          )}
          <div className="space-y-1.5">
            <Label>Image Alt Text</Label>
            <Input
              value={String((content as Record<string, any>).hero_image_alt ?? heroObj.image_alt ?? "")}
              onChange={(e) => setC("hero_image_alt", e.target.value)}
              placeholder="Describe the image for accessibility"
            />
          </div>
        </div>
      </section>
    );

    // ── Per-page content fields ───────────────────────────────────────────────
    function renderContentFields() {
      switch (slug) {
        // ── Home ──────────────────────────────────────────────────────────────
        case "home":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <LayoutTemplate className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Hero Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Heading — Line 1</Label>
                  <Input
                    value={String(content.hero_heading ?? "")}
                    onChange={(e) => setC("hero_heading", e.target.value)}
                    placeholder="Integrated Engineering"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>
                    Heading — Line 2{" "}
                    <span className="text-muted-foreground font-normal">(accent colour)</span>
                  </Label>
                  <Input
                    value={String(content.hero_heading_highlight ?? "")}
                    onChange={(e) => setC("hero_heading_highlight", e.target.value)}
                    placeholder="& Energy Services"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Subtitle</Label>
                  <Textarea
                    value={String(content.hero_subtitle ?? "")}
                    onChange={(e) => setC("hero_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Primary CTA — Label</Label>
                    <Input
                      value={String(content.hero_cta_primary_label ?? "")}
                      onChange={(e) => setC("hero_cta_primary_label", e.target.value)}
                      placeholder="Explore Services"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Primary CTA — URL</Label>
                    <Input
                      value={String(content.hero_cta_primary_url ?? "")}
                      onChange={(e) => setC("hero_cta_primary_url", e.target.value)}
                      placeholder="#services"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Secondary CTA — Label</Label>
                    <Input
                      value={String(content.hero_cta_secondary_label ?? "")}
                      onChange={(e) => setC("hero_cta_secondary_label", e.target.value)}
                      placeholder="Contact Us"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Secondary CTA — URL</Label>
                    <Input
                      value={String(content.hero_cta_secondary_url ?? "")}
                      onChange={(e) => setC("hero_cta_secondary_url", e.target.value)}
                      placeholder="#contact"
                    />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label>
                    Background Video{" "}
                    <span className="text-muted-foreground font-normal">(MP4, WEBM or OGG)</span>
                  </Label>
                  <input
                    ref={heroVideoInputRef}
                    type="file"
                    accept="video/mp4,video/webm,video/ogg"
                    className="hidden"
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (f) { setHeroVideoFile(f); setHeroVideoFileName(f.name); }
                    }}
                  />
                  <div
                    className={`border-2 border-dashed rounded-lg p-8 text-center text-sm cursor-pointer transition-colors ${heroVideoDragging
                        ? "border-primary bg-primary/5"
                        : "border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/50"
                      } text-muted-foreground`}
                    onClick={() => heroVideoInputRef.current?.click()}
                    onDragOver={(e) => { e.preventDefault(); setHeroVideoDragging(true); }}
                    onDragLeave={() => setHeroVideoDragging(false)}
                    onDrop={(e) => {
                      e.preventDefault();
                      setHeroVideoDragging(false);
                      const f = e.dataTransfer.files[0];
                      if (f) { setHeroVideoFile(f); setHeroVideoFileName(f.name); }
                    }}
                  >
                    {heroVideoFile ? (
                      <div className="flex flex-col items-center gap-2">
                        <Video className="h-8 w-8 mx-auto text-primary/60" />
                        <span className="text-sm font-medium text-foreground truncate max-w-xs">{heroVideoFileName}</span>
                        <span className="text-xs text-muted-foreground">Click or drop to replace</span>
                      </div>
                    ) : content.hero_video_url ? (
                      <div className="flex flex-col items-center gap-2">
                        <Video className="h-8 w-8 mx-auto text-muted-foreground/50" />
                        <span className="text-xs text-muted-foreground truncate max-w-xs">Current: {String(content.hero_video_url)}</span>
                        <span className="text-xs text-muted-foreground/60">Click or drop to replace</span>
                      </div>
                    ) : (
                      <div className="flex flex-col items-center gap-2">
                        <Upload className="h-8 w-8 mx-auto text-muted-foreground/50" />
                        <span>Click to upload or drag &amp; drop</span>
                        <span className="text-xs text-muted-foreground/60">MP4, WEBM, OGG</span>
                      </div>
                    )}
                  </div>
                  {heroVideoFile && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="text-destructive hover:text-destructive px-2"
                      onClick={() => { setHeroVideoFile(null); setHeroVideoFileName(""); }}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                      <span className="ml-1.5 text-xs">Remove</span>
                    </Button>
                  )}
                  {heroVideoProgress !== null && (
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Loader2 className="h-3 w-3 animate-spin" />
                      Uploading video… {heroVideoProgress}%
                    </div>
                  )}
                </div>
                <div className="space-y-1.5">
                  <Label>
                    Video Poster / Thumbnail{" "}
                    <span className="text-muted-foreground font-normal">(shown while video loads)</span>
                  </Label>
                  <input
                    ref={heroUpload.inputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/webp"
                    className="hidden"
                    onChange={(e) => {
                      if (e.target.files?.[0]) heroUpload.handleFile(e.target.files[0]);
                    }}
                  />
                  <ImageDropZone
                    preview={heroUpload.preview}
                    fallback={String(content.hero_poster_url ?? "") || undefined}
                    isDragging={heroUpload.isDragging}
                    onDragOver={(e) => {
                      e.preventDefault();
                      heroUpload.setIsDragging(true);
                    }}
                    onDragLeave={() => heroUpload.setIsDragging(false)}
                    onDrop={heroUpload.onDrop}
                    onClick={() => heroUpload.inputRef.current?.click()}
                  />
                  {heroImgProgress !== null && (
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Loader2 className="h-3 w-3 animate-spin" />
                      Uploading… {heroImgProgress}%
                    </div>
                  )}
                </div>
              </section>

              {/* ── About Snippet ────────────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Info className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    About Snippet
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Heading</Label>
                  <Input
                    value={String(content.home_about_heading ?? "")}
                    onChange={(e) => setC("home_about_heading", e.target.value)}
                    placeholder="Global Leaders in Energy Engineering"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Body Text</Label>
                  <Textarea
                    value={String(content.home_about_body ?? "")}
                    onChange={(e) => setC("home_about_body", e.target.value)}
                    rows={4}
                    className="resize-y"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Badge — Value</Label>
                    <Input
                      value={String(content.home_about_badge_value ?? "")}
                      onChange={(e) => setC("home_about_badge_value", e.target.value)}
                      placeholder="25+"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Badge — Label</Label>
                    <Input
                      value={String(content.home_about_badge_label ?? "")}
                      onChange={(e) => setC("home_about_badge_label", e.target.value)}
                      placeholder="Years of Excellence"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 1 — Title</Label>
                    <Input
                      value={String(content.home_about_stat_1_title ?? "")}
                      onChange={(e) => setC("home_about_stat_1_title", e.target.value)}
                      placeholder="Global Operations"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 1 — Description</Label>
                    <Input
                      value={String(content.home_about_stat_1_desc ?? "")}
                      onChange={(e) => setC("home_about_stat_1_desc", e.target.value)}
                      placeholder="Active projects across 4 continents…"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 2 — Title</Label>
                    <Input
                      value={String(content.home_about_stat_2_title ?? "")}
                      onChange={(e) => setC("home_about_stat_2_title", e.target.value)}
                      placeholder="Certified Quality"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 2 — Description</Label>
                    <Input
                      value={String(content.home_about_stat_2_desc ?? "")}
                      onChange={(e) => setC("home_about_stat_2_desc", e.target.value)}
                      placeholder="ISO 9001, 14001, and OHSAS 18001 accredited safety standards."
                    />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label>
                    Section Image{" "}
                    <span className="text-muted-foreground font-normal">(500×500px recommended)</span>
                  </Label>
                  <input
                    ref={homeAboutImgUpload.inputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/webp"
                    className="hidden"
                    onChange={(e) => { if (e.target.files?.[0]) homeAboutImgUpload.handleFile(e.target.files[0]); }}
                  />
                  <ImageDropZone
                    preview={homeAboutImgUpload.preview}
                    fallback={String(content.home_about_image_url ?? "") || undefined}
                    isDragging={homeAboutImgUpload.isDragging}
                    onDragOver={(e) => { e.preventDefault(); homeAboutImgUpload.setIsDragging(true); }}
                    onDragLeave={() => homeAboutImgUpload.setIsDragging(false)}
                    onDrop={homeAboutImgUpload.onDrop}
                    onClick={() => homeAboutImgUpload.inputRef.current?.click()}
                  />
                  {homeAboutImgProgress !== null && (
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Loader2 className="h-3 w-3 animate-spin" />
                      Uploading… {homeAboutImgProgress}%
                    </div>
                  )}
                </div>
              </section>

              {/* ── Section Headings ─────────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <LayoutTemplate className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Section Headings
                  </h2>
                </div>
                <Separator />
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Services — Heading</Label>
                    <Input value={String(content.services_heading ?? "")} onChange={(e) => setC("services_heading", e.target.value)} placeholder="Core Capabilities" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Services — Subtitle</Label>
                    <Input value={String(content.services_subtitle ?? "")} onChange={(e) => setC("services_subtitle", e.target.value)} placeholder="Providing end-to-end technical solutions…" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Technologies — Heading</Label>
                    <Input value={String(content.technologies_heading ?? "")} onChange={(e) => setC("technologies_heading", e.target.value)} placeholder="Advanced Inspection Tech" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Technologies — Subtitle</Label>
                    <Input value={String(content.technologies_subtitle ?? "")} onChange={(e) => setC("technologies_subtitle", e.target.value)} placeholder="We invest in the future of NDT…" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Projects — Heading</Label>
                    <Input value={String(content.projects_heading ?? "")} onChange={(e) => setC("projects_heading", e.target.value)} placeholder="Featured Projects" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Projects — Subtitle</Label>
                    <Input value={String(content.projects_subtitle ?? "")} onChange={(e) => setC("projects_subtitle", e.target.value)} placeholder="Delivering engineering excellence across the globe." />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Training — Heading</Label>
                    <Input value={String(content.training_heading ?? "")} onChange={(e) => setC("training_heading", e.target.value)} placeholder="Training Center" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Training — Subtitle</Label>
                    <Input value={String(content.training_subtitle ?? "")} onChange={(e) => setC("training_subtitle", e.target.value)} placeholder="OSHA-compliant operator certification…" />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label>
                    Training — Background Image{" "}
                    <span className="text-muted-foreground font-normal">(1920×1080px recommended)</span>
                  </Label>
                  <input
                    ref={homeTrainingImgUpload.inputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/webp"
                    className="hidden"
                    onChange={(e) => { if (e.target.files?.[0]) homeTrainingImgUpload.handleFile(e.target.files[0]); }}
                  />
                  <ImageDropZone
                    preview={homeTrainingImgUpload.preview}
                    fallback={String((content as any).training_image_url ?? "") || undefined}
                    isDragging={homeTrainingImgUpload.isDragging}
                    onDragOver={(e) => { e.preventDefault(); homeTrainingImgUpload.setIsDragging(true); }}
                    onDragLeave={() => homeTrainingImgUpload.setIsDragging(false)}
                    onDrop={homeTrainingImgUpload.onDrop}
                    onClick={() => homeTrainingImgUpload.inputRef.current?.click()}
                  />
                  {homeTrainingImgProgress !== null && (
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Loader2 className="h-3 w-3 animate-spin" />
                      Uploading… {homeTrainingImgProgress}%
                    </div>
                  )}
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Clients — Heading</Label>
                    <Input value={String(content.clients_heading ?? "")} onChange={(e) => setC("clients_heading", e.target.value)} placeholder="Trusted by Industry Leaders" />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Clients — Subtitle</Label>
                    <Input value={String(content.clients_subtitle ?? "")} onChange={(e) => setC("clients_subtitle", e.target.value)} placeholder="Partnering with global energy companies…" />
                  </div>
                </div>
              </section>

            </div>
          );

        // ── About ─────────────────────────────────────────────────────────────
        case "about":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}

              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Info className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    About Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.about_heading ?? "")}
                    onChange={(e) => setC("about_heading", e.target.value)}
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Body — Paragraph 1</Label>
                  <Textarea
                    value={String(content.about_body_1 ?? "")}
                    onChange={(e) => setC("about_body_1", e.target.value)}
                    rows={4}
                    className="resize-y"
                  />
                  <p className="text-xs text-muted-foreground">Tip: type <code className="bg-muted px-1 rounded">{"{"}services{"}"}</code> anywhere to embed the live service list as links.</p>
                </div>
                <div className="space-y-1.5">
                  <Label>Body — Paragraph 2</Label>
                  <Textarea
                    value={String(content.about_body_2 ?? "")}
                    onChange={(e) => setC("about_body_2", e.target.value)}
                    rows={4}
                    className="resize-y"
                  />
                  <p className="text-xs text-muted-foreground">Tip: type <code className="bg-muted px-1 rounded">{"{"}services{"}"}</code> anywhere to embed the live service list as links.</p>
                </div>
              </section>

              {/* ── About Section Images ─────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Images className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    About Section Images
                  </h2>
                </div>
                <Separator />
                <p className="text-xs text-muted-foreground">
                  These images appear in the photo slider next to the About text. Upload, reorder (drag), or delete slides. Changes save with the main Save Content button.
                </p>

                {/* Saved slides */}
                {getSlides().length > 0 && (
                  <div className="space-y-2">
                    {getSlides().map((slide, idx) => (
                      <div key={idx} className="flex items-center gap-3 bg-muted/30 border rounded-lg p-3">
                        <div className="relative h-14 w-20 rounded overflow-hidden shrink-0 bg-muted">
                          <Image src={slide.url} alt={slide.alt || "Slide"} fill className="object-cover" sizes="80px" />
                        </div>
                        <div className="flex-1 min-w-0 space-y-1">
                          <Label className="text-xs">Alt Text</Label>
                          <Input
                            value={slide.alt}
                            onChange={(e) => {
                              const next = getSlides().map((s, i) =>
                                i === idx ? { ...s, alt: e.target.value } : s,
                              );
                              setC("about_images", next);
                            }}
                            className="h-7 text-xs"
                            placeholder="Describe the image"
                          />
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
                          onClick={() => setC("about_images", getSlides().filter((_, i) => i !== idx))}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}

                {/* Staged (pending) slides — will upload when Save is clicked */}
                {pendingSlides.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-medium text-amber-600 dark:text-amber-400">Pending — will be uploaded on Save</p>
                    {pendingSlides.map((slide, idx) => (
                      <div key={idx} className="flex items-center gap-3 border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-950/30 rounded-lg p-3">
                        <div className="relative h-14 w-20 rounded overflow-hidden shrink-0 bg-muted">
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img src={slide.previewUrl} alt={slide.alt || "Pending slide"} className="h-full w-full object-cover" />
                        </div>
                        <div className="flex-1 min-w-0 space-y-1">
                          <Label className="text-xs">Alt Text</Label>
                          <Input
                            value={slide.alt}
                            onChange={(e) =>
                              setPendingSlides((prev) =>
                                prev.map((s, i) => (i === idx ? { ...s, alt: e.target.value } : s)),
                              )
                            }
                            className="h-7 text-xs"
                            placeholder="Describe the image"
                          />
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
                          onClick={() => setPendingSlides((prev) => prev.filter((_, i) => i !== idx))}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}

                {getSlides().length === 0 && pendingSlides.length === 0 && (
                  <p className="text-xs text-muted-foreground">No images yet. Add some below.</p>
                )}

                {/* Add new slide */}
                <div className="border border-dashed rounded-lg p-4 space-y-3">
                  <p className="text-xs font-medium text-muted-foreground">Add Image</p>
                  <input
                    ref={sliderFileInputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/webp"
                    className="hidden"
                    onChange={(e) => { if (e.target.files?.[0]) sliderImgUpload.handleFile(e.target.files[0]); }}
                  />
                  <ImageDropZone
                    preview={sliderImgUpload.preview}
                    isDragging={sliderImgUpload.isDragging}
                    onDragOver={(e) => { e.preventDefault(); sliderImgUpload.setIsDragging(true); }}
                    onDragLeave={() => sliderImgUpload.setIsDragging(false)}
                    onDrop={sliderImgUpload.onDrop}
                    onClick={() => sliderFileInputRef.current?.click()}
                  />
                  <div className="space-y-1.5">
                    <Label className="text-xs">Alt Text</Label>
                    <Input
                      value={newSlideAlt}
                      onChange={(e) => setNewSlideAlt(e.target.value)}
                      placeholder="e.g. Petro-Base team at offshore facility"
                      className="h-8 text-sm"
                    />
                  </div>
                  <Button
                    type="button"
                    size="sm"
                    className="gap-2"
                    disabled={!sliderImgUpload.file}
                    onClick={handleStageSlideImage}
                  >
                    <Plus className="h-3.5 w-3.5" />
                    Stage Image
                  </Button>
                </div>
              </section>

              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Award className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Stats &amp; Badge
                  </h2>
                </div>
                <Separator />
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Stat 1 — Value</Label>
                    <Input
                      value={String(content.stat_1_value ?? "")}
                      onChange={(e) => setC("stat_1_value", e.target.value)}
                      placeholder="Since 1998"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 1 — Label</Label>
                    <Input
                      value={String(content.stat_1_label ?? "")}
                      onChange={(e) => setC("stat_1_label", e.target.value)}
                      placeholder="Established"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 2 — Value</Label>
                    <Input
                      value={String(content.stat_2_value ?? "")}
                      onChange={(e) => setC("stat_2_value", e.target.value)}
                      placeholder="3+"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Stat 2 — Label</Label>
                    <Input
                      value={String(content.stat_2_label ?? "")}
                      onChange={(e) => setC("stat_2_label", e.target.value)}
                      placeholder="Continents"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Badge — Value</Label>
                    <Input
                      value={String(content.years_badge_value ?? "")}
                      onChange={(e) => setC("years_badge_value", e.target.value)}
                      placeholder="25+"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Badge — Label</Label>
                    <Input
                      value={String(content.years_badge_label ?? "")}
                      onChange={(e) => setC("years_badge_label", e.target.value)}
                      placeholder="Years of Excellence"
                    />
                  </div>
                </div>
              </section>

              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Info className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Section Headings
                  </h2>
                </div>
                <Separator />
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Our History — Heading</Label>
                    <Input
                      value={String(content.history_heading ?? "")}
                      onChange={(e) => setC("history_heading", e.target.value)}
                      placeholder="Our History"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Our History — Subtitle</Label>
                    <Input
                      value={String(content.history_subtitle ?? "")}
                      onChange={(e) => setC("history_subtitle", e.target.value)}
                      placeholder="Over two decades of growth…"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Our Strengths — Heading</Label>
                    <Input
                      value={String(content.strengths_heading ?? "")}
                      onChange={(e) => setC("strengths_heading", e.target.value)}
                      placeholder="Our Strengths"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Our Strengths — Subtitle</Label>
                    <Input
                      value={String(content.strengths_subtitle ?? "")}
                      onChange={(e) => setC("strengths_subtitle", e.target.value)}
                      placeholder="What sets us apart…"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Our Affiliates — Heading</Label>
                    <Input
                      value={String(content.affiliates_heading ?? "")}
                      onChange={(e) => setC("affiliates_heading", e.target.value)}
                      placeholder="Our Affiliates"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Our Affiliates — Subtitle</Label>
                    <Input
                      value={String(content.affiliates_subtitle ?? "")}
                      onChange={(e) => setC("affiliates_subtitle", e.target.value)}
                      placeholder="Operating entities across the globe"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Mission, Vision &amp; Values — Heading</Label>
                    <Input
                      value={String(content.mvv_heading ?? "")}
                      onChange={(e) => setC("mvv_heading", e.target.value)}
                      placeholder="Mission, Vision & Values"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Core Values — Heading</Label>
                    <Input
                      value={String(content.core_values_heading ?? "")}
                      onChange={(e) => setC("core_values_heading", e.target.value)}
                      placeholder="Core Values"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Global Presence — Heading</Label>
                    <Input
                      value={String(content.global_presence_heading ?? "")}
                      onChange={(e) => setC("global_presence_heading", e.target.value)}
                      placeholder="Global Presence"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Global Presence — Subtitle</Label>
                    <Input
                      value={String(content.global_presence_subtitle ?? "")}
                      onChange={(e) => setC("global_presence_subtitle", e.target.value)}
                      placeholder="Operating across 4 continents…"
                    />
                  </div>
                </div>
              </section>
            </div>
          );

        // ── Services ──────────────────────────────────────────────────────────
        case "services":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Wrench className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Services Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                  />
                </div>
              </section>
            </div>
          );

        // ── Contact ───────────────────────────────────────────────────────────
        case "contact": {
          const offices = ((content.offices ?? []) as OfficeItem[]);
          const setOffices = (next: OfficeItem[]) => setC("offices", next);

          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}

              {/* ── Form Section ──────────────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <MessageSquare className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Contact Form Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Form Heading</Label>
                  <Input
                    value={String(content.form_title ?? "")}
                    onChange={(e) => setC("form_title", e.target.value)}
                    placeholder="Send Us a Message"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Form Subtitle</Label>
                  <Textarea
                    value={String(content.form_subtitle ?? "")}
                    onChange={(e) => setC("form_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Fill out the form below and our team will respond within 24 business hours."
                  />
                </div>
              </section>

              {/* ── Business Hours ────────────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Business Hours
                  </h2>
                </div>
                <Separator />
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label>Monday – Friday</Label>
                    <Input
                      value={String(content.biz_hours_mon_fri ?? "")}
                      onChange={(e) => setC("biz_hours_mon_fri", e.target.value)}
                      placeholder="8:00 AM – 6:00 PM"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Saturday</Label>
                    <Input
                      value={String(content.biz_hours_sat ?? "")}
                      onChange={(e) => setC("biz_hours_sat", e.target.value)}
                      placeholder="9:00 AM – 2:00 PM"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Sunday</Label>
                    <Input
                      value={String(content.biz_hours_sun ?? "")}
                      onChange={(e) => setC("biz_hours_sun", e.target.value)}
                      placeholder="Closed"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>Emergency Support</Label>
                    <Input
                      value={String(content.biz_hours_emergency ?? "")}
                      onChange={(e) => setC("biz_hours_emergency", e.target.value)}
                      placeholder="24/7 Available"
                    />
                  </div>
                </div>
              </section>

              {/* ── Offices Section Header ────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <MapPin className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Offices Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.offices_heading ?? "")}
                    onChange={(e) => setC("offices_heading", e.target.value)}
                    placeholder="Our Offices"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.offices_subtitle ?? "")}
                    onChange={(e) => setC("offices_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Strategically located across Nigeria's key energy corridors."
                  />
                </div>
              </section>

              {/* ── Office Locations ──────────────────────────────────────── */}
              <section className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                      Office Locations
                    </h2>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="gap-1.5 h-7 text-xs"
                    onClick={() =>
                      setOffices([
                        ...offices,
                        { city: "", role: "", company: "", address: "", phones: [""], emails: [""] },
                      ])
                    }
                  >
                    <Plus className="h-3.5 w-3.5" /> Add Office
                  </Button>
                </div>
                <Separator />

                <div className="space-y-6">
                  {offices.map((office, oi) => {
                    const updateOffice = (key: keyof OfficeItem, val: string | string[]) => {
                      const next = offices.map((o, idx) =>
                        idx === oi ? { ...o, [key]: val } : o,
                      );
                      setOffices(next);
                    };

                    const phones = office.phones ?? [""];
                    const emails = office.emails ?? [""];

                    return (
                      <div key={oi} className="rounded-lg border border-border p-5 space-y-4">
                        {/* Card header */}
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-semibold text-foreground">
                            Office {oi + 1}
                            {office.city ? ` — ${office.city}` : ""}
                          </span>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7 text-muted-foreground hover:text-destructive"
                            onClick={() => setOffices(offices.filter((_, j) => j !== oi))}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>

                        {/* City / Role */}
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-1.5">
                            <Label>City / Country</Label>
                            <Input
                              value={office.city}
                              onChange={(e) => updateOffice("city", e.target.value)}
                              placeholder="Nigeria"
                            />
                          </div>
                          <div className="space-y-1.5">
                            <Label>Role</Label>
                            <Input
                              value={office.role}
                              onChange={(e) => updateOffice("role", e.target.value)}
                              placeholder="Headquarters"
                            />
                          </div>
                        </div>

                        {/* Company */}
                        <div className="space-y-1.5">
                          <Label>Company Name</Label>
                          <Input
                            value={office.company}
                            onChange={(e) => updateOffice("company", e.target.value)}
                            placeholder="Petro-Base Group, Ltd"
                          />
                        </div>

                        {/* Address */}
                        <div className="space-y-1.5">
                          <Label>Address</Label>
                          <Textarea
                            value={office.address}
                            onChange={(e) => updateOffice("address", e.target.value)}
                            rows={2}
                            className="resize-none"
                            placeholder="Street address…"
                          />
                        </div>

                        {/* Phone numbers */}
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <Label className="flex items-center gap-1.5">
                              <Phone className="h-3.5 w-3.5 text-muted-foreground" /> Phone Numbers
                            </Label>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-6 text-xs gap-1 px-2"
                              onClick={() => updateOffice("phones", [...phones, ""])}
                            >
                              <Plus className="h-3 w-3" /> Add
                            </Button>
                          </div>
                          {phones.map((ph, pi) => (
                            <div key={pi} className="flex gap-2">
                              <Input
                                value={ph}
                                onChange={(e) => {
                                  const next = phones.map((p, j) =>
                                    j === pi ? e.target.value : p,
                                  );
                                  updateOffice("phones", next);
                                }}
                                placeholder="+234 000 000 0000"
                              />
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-10 w-10 shrink-0 text-muted-foreground hover:text-destructive"
                                disabled={phones.length === 1}
                                onClick={() =>
                                  updateOffice(
                                    "phones",
                                    phones.filter((_, j) => j !== pi),
                                  )
                                }
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          ))}
                        </div>

                        {/* Email addresses */}
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <Label className="flex items-center gap-1.5">
                              <Mail className="h-3.5 w-3.5 text-muted-foreground" /> Email Addresses
                            </Label>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-6 text-xs gap-1 px-2"
                              onClick={() => updateOffice("emails", [...emails, ""])}
                            >
                              <Plus className="h-3 w-3" /> Add
                            </Button>
                          </div>
                          {emails.map((em, ei) => (
                            <div key={ei} className="flex gap-2">
                              <Input
                                type="email"
                                value={em}
                                onChange={(e) => {
                                  const next = emails.map((v, j) =>
                                    j === ei ? e.target.value : v,
                                  );
                                  updateOffice("emails", next);
                                }}
                                placeholder="info@petrobasegroup.com"
                              />
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-10 w-10 shrink-0 text-muted-foreground hover:text-destructive"
                                disabled={emails.length === 1}
                                onClick={() =>
                                  updateOffice(
                                    "emails",
                                    emails.filter((_, j) => j !== ei),
                                  )
                                }
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })}

                  {offices.length === 0 && (
                    <p className="text-sm text-muted-foreground text-center py-6 border border-dashed border-border rounded-lg">
                      No offices added yet. Click &quot;Add Office&quot; to get started.
                    </p>
                  )}
                </div>
              </section>
            </div>
          );
        }

        // ── News ──────────────────────────────────────────────────────────────
        case "news":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Newspaper className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    News Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Latest Stories"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Stay up to date with Petro-Base Group's latest projects…"
                  />
                </div>
              </section>
            </div>
          );

        // ── Clients ───────────────────────────────────────────────────────────
        case "clients":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Building2 className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Clients Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Our Partners"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="A selection of the major operators and service companies we proudly serve."
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Testimonial Section Heading</Label>
                  <Input
                    value={String(content.testimonial_section_heading ?? "")}
                    onChange={(e) => setC("testimonial_section_heading", e.target.value)}
                    placeholder="Our Partners"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Testimonial Section Subtitle</Label>
                  <Textarea
                    value={String(content.testimonial_section_subtitle ?? "")}
                    onChange={(e) => setC("testimonial_section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="A selection of the major operators and service companies we proudly serve."
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Industry Section Heading</Label>
                  <Input
                    value={String(content.industry_section_heading ?? "")}
                    onChange={(e) => setC("industry_section_heading", e.target.value)}
                    placeholder="Our Partners"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Industry Section Subtitle</Label>
                  <Textarea
                    value={String(content.industry_section_subtitle ?? "")}
                    onChange={(e) => setC("industry_section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="A selection of the major operators and service companies we proudly serve."
                  />
                </div>
              </section>
            </div>
          );

        // ── Training ──────────────────────────────────────────────────────────
        case "training":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <GraduationCap className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Training Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Training Programs"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Comprehensive operator certification courses designed to international safety standards."
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Training Section Heading</Label>
                  <Input
                    value={String(content.training_section_heading ?? "")}
                    onChange={(e) => setC("training_section_heading", e.target.value)}
                    placeholder="Training Programs"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Training Section Subtitle</Label>
                  <Textarea
                    value={String(content.training_section_subtitle ?? "")}
                    onChange={(e) => setC("training_section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Comprehensive operator certification courses designed to international safety standards."
                  />
                </div>
              </section>
            </div>
          );

        // ── Technologies ──────────────────────────────────────────────────────
        case "technologies":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Cpu className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Technologies Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Advanced Inspection Technologies"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Purpose-built equipment and proprietary systems for precision asset integrity assessment."
                  />
                </div>
              </section>
            </div>
          );

        // ── Inspectors ────────────────────────────────────────────────────────
        case "inspectors":
          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <Users className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Inspectors Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Certified Inspection Professionals"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Each inspector is vetted, certified, and ready to deploy…"
                  />
                </div>
              </section>
            </div>
          );

        // ── Projects ──────────────────────────────────────────────────────────
        case "projects": {
          const projectStats = (((content as any).stats ?? []) as StatItem[]);
          const setProjectStats = (next: StatItem[]) => setC("stats", next);

          return (
            <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">
              {standardHeroSection}
              <section className="space-y-4">
                <div className="flex items-center gap-2">
                  <FolderKanban className="h-4 w-4 text-muted-foreground" />
                  <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Projects Section
                  </h2>
                </div>
                <Separator />
                <div className="space-y-1.5">
                  <Label>Section Heading</Label>
                  <Input
                    value={String(content.section_heading ?? "")}
                    onChange={(e) => setC("section_heading", e.target.value)}
                    placeholder="Our Projects"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Section Subtitle</Label>
                  <Textarea
                    value={String(content.section_subtitle ?? "")}
                    onChange={(e) => setC("section_subtitle", e.target.value)}
                    rows={2}
                    className="resize-none"
                    placeholder="Real-world results from our global operations…"
                  />
                </div>
              </section>
              <section className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <BarChart2 className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                      Stats Bar
                    </h2>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="gap-1.5 h-7 text-xs"
                    onClick={() => setProjectStats([...projectStats, { label: "", value: "" }])}
                  >
                    <Plus className="h-3.5 w-3.5" /> Add Stat
                  </Button>
                </div>
                <Separator />
                <div className="space-y-3">
                  {projectStats.map((stat, si) => (
                    <div key={si} className="flex items-end gap-3">
                      <div className="flex-1 space-y-1.5">
                        <Label>Value</Label>
                        <Input
                          value={stat.value}
                          onChange={(e) =>
                            setProjectStats(
                              projectStats.map((s, j) =>
                                j === si ? { ...s, value: e.target.value } : s,
                              ),
                            )
                          }
                          placeholder="500+"
                        />
                      </div>
                      <div className="flex-1 space-y-1.5">
                        <Label>Label</Label>
                        <Input
                          value={stat.label}
                          onChange={(e) =>
                            setProjectStats(
                              projectStats.map((s, j) =>
                                j === si ? { ...s, label: e.target.value } : s,
                              ),
                            )
                          }
                          placeholder="Projects Completed"
                        />
                      </div>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-10 w-10 shrink-0 text-muted-foreground hover:text-destructive"
                        disabled={projectStats.length <= 1}
                        onClick={() =>
                          setProjectStats(projectStats.filter((_, j) => j !== si))
                        }
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  ))}
                  {projectStats.length === 0 && (
                    <p className="text-sm text-muted-foreground text-center py-6 border border-dashed border-border rounded-lg">
                      No stats yet. Click &quot;Add Stat&quot; to get started.
                    </p>
                  )}
                </div>
              </section>
            </div>
          );
        }

        // ── All other pages: just the hero ────────────────────────────────────
        default:
          return <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-10">{standardHeroSection}</div>;
      }
    }

    // ── Render ────────────────────────────────────────────────────────────────
    return (
      <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex items-center gap-3">
          <Link href="/admin/pages">
            <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted">
            <PageIcon className="h-4 w-4 text-muted-foreground" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold tracking-tight">{config.label}</h1>
              <Badge variant="secondary" className="text-xs font-mono hidden sm:inline-flex">
                {config.path}
              </Badge>
            </div>
            <p className="text-sm text-muted-foreground mt-0.5">{config.description}</p>
          </div>
        </div>

        {isLoading ? (
          <div className="space-y-4">
            <Skeleton className="h-10 w-full" />
            {[...Array(6)].map((_, i) => (
              <div key={i} className="space-y-2">
                <Skeleton className="h-4 w-28" />
                <Skeleton className="h-10 w-full" />
              </div>
            ))}
          </div>
        ) : (
          <Tabs value={selectedTab} onValueChange={(v) => setSelectedTab(v)} defaultValue="content">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="content" className="gap-2">
                <LayoutTemplate className="h-3.5 w-3.5" />
                Content
              </TabsTrigger>
              <TabsTrigger value="seo" className="gap-2">
                <Search className="h-3.5 w-3.5" />
                SEO
              </TabsTrigger>
            </TabsList>

            {/* ── Content Tab ─────────────────────────────────────────────── */}
            <TabsContent value="content" className="pt-6">
              <div className="space-y-10">
                {renderContentFields()}
                <div className="flex justify-end pt-4 border-t border-border">
                  <Button
                    onClick={handleSaveContent}
                    disabled={contentSaving}
                    size="sm"
                    className="gap-2"
                  >
                    {contentSaving ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Save className="h-4 w-4" />
                    )}
                    Save Content
                  </Button>
                </div>
              </div>
            </TabsContent>

            {/* ── SEO Tab ─────────────────────────────────────────────────── */}
            <TabsContent value="seo" className="pt-6">
              <div className="space-y-10">
                {/* Meta Tags */}
                <section className="space-y-4">
                  <div className="flex items-center gap-2">
                    <Search className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                      Meta Tags
                    </h2>
                  </div>
                  <Separator />
                  <div className="space-y-1.5">
                    <Label htmlFor="meta_title">Meta Title</Label>
                    <Input
                      id="meta_title"
                      value={seoForm.meta_title ?? ""}
                      onChange={(e) => setSeo("meta_title", e.target.value)}
                      maxLength={70}
                      placeholder="e.g. Petro-Base Group | Engineering & Energy Services"
                    />
                    <p className="text-xs text-muted-foreground">
                      {(seoForm.meta_title ?? "").length}/70 — recommended 50–60
                    </p>
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="meta_desc">Meta Description</Label>
                    <Textarea
                      id="meta_desc"
                      value={seoForm.meta_description ?? ""}
                      onChange={(e) => setSeo("meta_description", e.target.value)}
                      maxLength={160}
                      rows={3}
                      className="resize-none"
                      placeholder="Brief summary shown in search results…"
                    />
                    <p className="text-xs text-muted-foreground">
                      {(seoForm.meta_description ?? "").length}/160 — recommended 120–160
                    </p>
                  </div>
                </section>

                {/* Open Graph */}
                <section className="space-y-4">
                  <div className="flex items-center gap-2">
                    <Globe className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                      Open Graph / Social
                    </h2>
                  </div>
                  <Separator />
                  <div className="space-y-1.5">
                    <Label>OG Title</Label>
                    <Input
                      value={seoForm.og_title ?? ""}
                      onChange={(e) => setSeo("og_title", e.target.value)}
                      placeholder="Title shown on social media"
                    />
                    <p className="text-xs text-muted-foreground">Leave blank to inherit Meta Title</p>
                  </div>
                  <div className="space-y-1.5">
                    <Label>OG Description</Label>
                    <Textarea
                      value={seoForm.og_description ?? ""}
                      onChange={(e) => setSeo("og_description", e.target.value)}
                      rows={3}
                      className="resize-none"
                      placeholder="Description shown on social media"
                    />
                    <p className="text-xs text-muted-foreground">Leave blank to inherit Meta Description</p>
                  </div>
                  <div className="space-y-1.5">
                    <Label>
                      OG Image{" "}
                      <span className="text-muted-foreground font-normal">(1200×630px recommended)</span>
                    </Label>
                    <input
                      ref={ogUpload.inputRef}
                      type="file"
                      accept="image/jpeg,image/png,image/webp"
                      className="hidden"
                      onChange={(e) => {
                        if (e.target.files?.[0]) ogUpload.handleFile(e.target.files[0]);
                      }}
                    />
                    <ImageDropZone
                      preview={ogUpload.preview}
                      fallback={seoForm.og_image_url || undefined}
                      isDragging={ogUpload.isDragging}
                      onDragOver={(e) => {
                        e.preventDefault();
                        ogUpload.setIsDragging(true);
                      }}
                      onDragLeave={() => ogUpload.setIsDragging(false)}
                      onDrop={ogUpload.onDrop}
                      onClick={() => ogUpload.inputRef.current?.click()}
                    />
                    {ogImgProgress !== null && (
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Loader2 className="h-3 w-3 animate-spin" />
                        Uploading… {ogImgProgress}%
                      </div>
                    )}
                  </div>
                </section>

                {/* Advanced */}
                <section className="space-y-4">
                  <div className="flex items-center gap-2">
                    <Code className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                      Advanced
                    </h2>
                  </div>
                  <Separator />
                  <div className="space-y-1.5">
                    <Label>Canonical URL</Label>
                    <Input
                      value={seoForm.canonical_url ?? ""}
                      onChange={(e) => setSeo("canonical_url", e.target.value)}
                      placeholder="https://petrobasegroup.com/about"
                    />
                    <p className="text-xs text-muted-foreground">Leave blank to use the default page URL</p>
                  </div>
                  <div className="flex items-center justify-between rounded-lg border border-border px-4 py-3">
                    <div>
                      <p className="text-sm font-medium">No Index</p>
                      <p className="text-xs text-muted-foreground">
                        Tell search engines not to index this page
                      </p>
                    </div>
                    <Switch
                      checked={seoForm.no_index}
                      onCheckedChange={(v) => setSeo("no_index", v)}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label>JSON-LD Structured Data</Label>
                    <Textarea
                      value={seoForm.schema_json ?? ""}
                      onChange={(e) => {
                        const v = e.target.value;
                        setSeo("schema_json", v);
                        const txt = v.trim();
                        if (!txt) {
                          setSchemaJsonError("");
                          return;
                        }
                        try {
                          JSON.parse(txt);
                          setSchemaJsonError("");
                        } catch (err: any) {
                          setSchemaJsonError(err?.message ?? String(err));
                        }
                      }}
                      className="resize-y font-mono text-xs"
                      rows={8}
                      placeholder={`{\n  "@context": "https://schema.org",\n  "@type": "Organization",\n  "name": "Petro-Base Group"\n}`}
                    />
                    {schemaJsonError ? (
                      <p className="text-xs text-destructive">JSON parse error: {schemaJsonError}</p>
                    ) : (
                      <p className="text-xs text-muted-foreground">
                        Raw JSON-LD injected into the{" "}
                        <code className="bg-muted px-1 rounded text-xs">&lt;head&gt;</code>
                      </p>
                    )}
                  </div>
                </section>

                <div className="flex justify-end pt-4 border-t border-border">
                  <Button
                    onClick={handleSaveSeo}
                    disabled={seoSaving || Boolean(schemaJsonError)}
                    size="sm"
                    className="gap-2"
                  >
                    {seoSaving ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Save className="h-4 w-4" />
                    )}
                    Save SEO
                  </Button>
                </div>
              </div>
            </TabsContent>
          </Tabs>
        )}
      </div>
    );
  }
