"use client"

import { useEffect, useRef, useState } from "react"
import { useRouter } from "next/navigation"
import {
  User, Activity, Eye, Layers, Globe, Image, Star, Video,
  HelpCircle, Save, Send, Loader2, X, Zap,
  HeartHandshake, Package, Link2, ChevronLeft,
} from "lucide-react"

import type { Language } from "@/components/dashboard/shared/LanguageTabs"
import { CategorySelect } from "@/components/dashboard/articles/CategorySelect"
import { ProcedureBasicInfo, type ProcedureBasicInfoData } from "./ProcedureBasicInfo"
import { ProcedureQuickStats, type QuickStatItem } from "./ProcedureQuickStats"
import { ProcedureOverview, type ProcedureOverviewData } from "./ProcedureOverview"
import { ProcedureCountriesComparison, type ProcedureCountriesComparisonData } from "./ProcedureCountriesComparison"
import { ProcedureProcess, type ProcedureProcessData } from "./ProcedureProcess"
import { ProcedureBenefits, type ProcedureBenefitsData } from "./ProcedureBenefits"
import { ProcedureBeforeAfterSection, type ProcedureBeforeAfterSectionData } from "./ProcedureBeforeAfterSection"
import { ProcedureRecovery, type ProcedureRecoveryData } from "./ProcedureRecovery"
import { ProcedurePackage, type ProcedurePackageData } from "./ProcedurePackage"
import { ProcedureReviews, type ProcedureReviewItem } from "./ProcedureReviews"
import { ProcedureFAQ, type ProcedureFAQItem } from "./ProcedureFAQ"
import { ProcedureRelated, type ProcedureRelatedData } from "./ProcedureRelated"
import { ProcedureCTA, type ProcedureCTAData } from "./ProcedureCTA"
import { ProcedureVideoSection, type ProcedureVideoSectionData } from "./ProcedureVideoSection"
import { validateUrlSlug } from "@/lib/slug-validation"
import { revokeStagedImage } from "@/lib/media-manager/stage"
import type { StagedImage } from "@/lib/media-manager/types"
import {
  commitPendingProcedureImages,
  createEmptyProcedurePendingImages,
  clearProcedurePendingImages,
  procedurePendingHasAny,
  procedurePendingKey,
} from "@/lib/media-manager/procedure-pending"
import { mergeProcedureFormMediaFromSavedForm } from "@/lib/media-manager/entity-form-media"
import { applyProcedureCtaDefaults } from "@/lib/procedure-cta-contact-form-defaults"
import { applyProcedureDoctorsSectionDefaults } from "@/lib/procedure-doctors-section-defaults"
import { applyProcedureTranslationsFormDefaults } from "@/lib/procedure-form-locale-defaults"
import { normalizeProcedureBasicInfoJson } from "@/lib/procedure-db"

// ─── Types ────────────────────────────────────────────────────────────────────

type ProcedureSectionKey =
  | "basic"
  | "quickStats"
  | "overview"
  | "countries"
  | "process"
  | "benefits"
  | "beforeAfter"
  | "doctors"
  | "recovery"
  | "package"
  | "reviews"
  | "faq"
  | "related"
  | "cta"
  | "video"

interface LocaleBasicInfoFields {
  startingFromPrice: string
  duration: string
  hospitalStay: string
  recovery: string
}

interface LocaleContent {
  name: string
  description: string
  stayCity: string
  basicInfo: LocaleBasicInfoFields
  overview: ProcedureOverviewData
  countriesComparison: ProcedureCountriesComparisonData
  process: ProcedureProcessData
  benefits: ProcedureBenefitsData
  beforeAfterSection: ProcedureBeforeAfterSectionData
  doctorsSectionEyebrow: string
  doctorsSectionTitle: string
  recovery: ProcedureRecoveryData
  packageSection: ProcedurePackageData
  reviews: ProcedureReviewItem[]
  reviewsEyebrow: string
  reviewsTitle: string
  faqItems: ProcedureFAQItem[]
  faqEyebrow: string
  faqTitle: string
  faqSubtitle: string
  faqButtonText: string
  faqButtonLink: string
  related: ProcedureRelatedData
  cta: ProcedureCTAData
  videoSection: ProcedureVideoSectionData
}

interface ProcedureFormState {
  categoryId: string
  isFeatured: boolean
  basicInfo: ProcedureBasicInfoData
  quickStats: QuickStatItem[]
  translations: {
    en: LocaleContent
    ar: LocaleContent
    tr: LocaleContent
  }
}

// ─── Defaults ─────────────────────────────────────────────────────────────────

const emptyOverview: ProcedureOverviewData = {
  eyebrow: "", title: "", description: "", keyTakeawaysTitle: "", keyTakeaways: [],
  overviewCardStartingPriceLabel: "", overviewCardStartingPriceValue: "", overviewCardImage: "", overviewCardImagePublicId: "",
}

const emptyCountries: ProcedureCountriesComparisonData = {
  eyebrow: "", title: "", subtitle: "", bestValueCountryName: "", bestValueCountryFlag: "", bestValuePrice: "",
  countries: [], mainCardLabel: "", mainCardValue: "", mainCardDescription: "", mainCardButtonText: "", mainCardButtonLink: "", disclaimerText: "",
}

const emptyProcess: ProcedureProcessData = { eyebrow: "", title: "", subtitle: "", steps: [] }
const emptyBenefits: ProcedureBenefitsData = { eyebrow: "", title: "", subtitle: "", benefits: [] }

const emptyBeforeAfter: ProcedureBeforeAfterSectionData = {
  eyebrow: "", title: "", subtitle: "", results: [], buttonText: "", buttonLink: "", disclaimerText: "",
}

const emptyRecovery: ProcedureRecoveryData = { eyebrow: "", title: "", subtitle: "", steps: [], noteText: "" }

const emptyPackage: ProcedurePackageData = {
  eyebrow: "", title: "", subtitle: "", features: [], startingPriceLabel: "", startingPriceValue: "", buttonText: "", buttonLink: "",
}

const emptyRelated: ProcedureRelatedData = { eyebrow: "", title: "", buttonText: "", buttonLink: "" }

const emptyCTA: ProcedureCTAData = {
  eyebrow: "", title: "", subtitle: "", features: [], buttonIconKey: "", buttonTitle: "", buttonSubtitle: "", buttonLink: "",
  formTitle: "", formSubtitle: "", formFullNameLabel: "", formPhoneLabel: "", formEmailLabel: "", formProcedureLabel: "",
  formMessageLabel: "", formButtonIconKey: "", formButtonText: "", formButtonLink: "", formEndLabel: "",
}

const emptyVideoSection: ProcedureVideoSectionData = {
  eyebrow: "",
  title: "",
  subtitle: "",
  videoLink: "",
}

const emptyLocale: LocaleContent = {
  name: "", description: "", stayCity: "", basicInfo: { startingFromPrice: "", duration: "", hospitalStay: "", recovery: "" },
  overview: emptyOverview, countriesComparison: emptyCountries,
  process: emptyProcess, benefits: emptyBenefits, beforeAfterSection: emptyBeforeAfter,
  doctorsSectionEyebrow: "", doctorsSectionTitle: "",
  recovery: emptyRecovery, packageSection: emptyPackage,
  reviews: [], reviewsEyebrow: "", reviewsTitle: "",
  faqItems: [], faqEyebrow: "", faqTitle: "", faqSubtitle: "", faqButtonText: "", faqButtonLink: "",
  related: emptyRelated, cta: emptyCTA,
  videoSection: emptyVideoSection,
}

const emptyBasicInfo: ProcedureBasicInfoData = {
  name: "", slug: "", description: "", rating: "", reviewCount: "",
  mainImage: "", mainImagePublicId: "", beforeAfterImages: [],
  startingFromPrice: "", duration: "", stayCity: "", stayDays: "", hospitalStay: "", recovery: "",
}

function emptyLocaleForLanguage(locale: "en" | "ar" | "tr"): LocaleContent {
  const withDefaults = applyProcedureDoctorsSectionDefaults(
    {
      ...emptyLocale,
      cta: applyProcedureCtaDefaults(emptyCTA, locale),
    },
    locale
  )
  return withDefaults as unknown as LocaleContent
}

const emptyState: ProcedureFormState = {
  categoryId: "", isFeatured: false,
  basicInfo: emptyBasicInfo,
  quickStats: [],
  translations: {
    en: emptyLocaleForLanguage("en"),
    ar: emptyLocaleForLanguage("ar"),
    tr: emptyLocaleForLanguage("tr"),
  },
}

// ─── Section component ────────────────────────────────────────────────────────

interface SectionProps {
  id: string
  icon: React.ReactNode
  title: string
  description: string
  accent: "navy" | "green"
  children: React.ReactNode
}

function Section({ id, icon, title, description, accent, children }: SectionProps) {
  const bg = accent === "navy" ? "rgba(29,45,104,0.02)" : "rgba(43,182,115,0.02)"
  const iconBg = accent === "navy" ? "rgba(29,45,104,0.08)" : "rgba(43,182,115,0.10)"
  const iconColor = accent === "navy" ? "var(--brand-navy)" : "var(--brand-green)"

  return (
    <section className="bg-card rounded-2xl border border-border overflow-hidden" aria-labelledby={id}>
      <div className="flex items-center gap-3 px-6 py-4 border-b border-border" style={{ background: bg }}>
        <div className="w-8 h-8 rounded-xl flex items-center justify-center shrink-0" style={{ background: iconBg }}>
          <span style={{ color: iconColor }} aria-hidden="true">{icon}</span>
        </div>
        <div>
          <h2 id={id} className="text-sm font-bold text-foreground font-sans">{title}</h2>
          <p className="text-xs text-muted-foreground font-sans">{description}</p>
        </div>
      </div>
      <div className="p-6">{children}</div>
    </section>
  )
}

// ─── Main form ────────────────────────────────────────────────────────────────

interface ProcedureFormProps {
  procedureId?: string
  onSuccess?: () => void
  cancelHref?: string
}

export function ProcedureForm({ procedureId, onSuccess, cancelHref = "/dashboard/procedures" }: ProcedureFormProps) {
  const router = useRouter()
  const [form, setForm] = useState<ProcedureFormState>(emptyState)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loadingProcedure, setLoadingProcedure] = useState(!!procedureId)
  const [createdProcedureId, setCreatedProcedureId] = useState<string | null>(null)
  const [pendingAction, setPendingAction] = useState<"draft" | "published" | null>(null)
  const [savingSectionKey, setSavingSectionKey] = useState<ProcedureSectionKey | null>(null)
  const [sectionFeedback, setSectionFeedback] = useState<
    Partial<Record<ProcedureSectionKey, { type: "success" | "error"; message: string }>>
  >({})
  const sectionFeedbackTimersRef = useRef<Partial<Record<ProcedureSectionKey, ReturnType<typeof setTimeout>>>>({})
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [submitSuccess, setSubmitSuccess] = useState<string | null>(null)
  const [slugAvailable, setSlugAvailable] = useState<boolean | null>(null)
  const [checkingSlug, setCheckingSlug] = useState(false)
  const [slugError, setSlugError] = useState<string | null>(null)
  const [activeLocale, setActiveLocale] = useState<Language>("en")
  const pendingImagesRef = useRef(createEmptyProcedurePendingImages())
  /** Slug from server — updated after each successful save. */
  const loadedProcedureSlugRef = useRef("")

  const sharedFieldsLocked = activeLocale !== "en"

  function getProcedureSlug() {
    return form.basicInfo.slug.trim()
  }

  function handleStageMainPhoto(staged: StagedImage) {
    if (pendingImagesRef.current.mainPhoto) revokeStagedImage(pendingImagesRef.current.mainPhoto)
    pendingImagesRef.current.mainPhoto = staged
  }

  function handleClearStagedMainPhoto() {
    if (pendingImagesRef.current.mainPhoto) revokeStagedImage(pendingImagesRef.current.mainPhoto)
    pendingImagesRef.current.mainPhoto = null
  }

  function handleStageBasicBefore(index: number, staged: StagedImage) {
    const existing = pendingImagesRef.current.basicBefore.get(index)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.basicBefore.set(index, staged)
  }

  function handleClearStagedBasicBefore(index: number) {
    const existing = pendingImagesRef.current.basicBefore.get(index)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.basicBefore.delete(index)
  }

  function handleStageBasicAfter(index: number, staged: StagedImage) {
    const existing = pendingImagesRef.current.basicAfter.get(index)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.basicAfter.set(index, staged)
  }

  function handleClearStagedBasicAfter(index: number) {
    const existing = pendingImagesRef.current.basicAfter.get(index)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.basicAfter.delete(index)
  }

  function handleStageOverviewCard(staged: StagedImage) {
    const key = procedurePendingKey(activeLocale, 0)
    const existing = pendingImagesRef.current.overviewCard.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.overviewCard.set(key, staged)
  }

  function handleClearStagedOverviewCard() {
    const key = procedurePendingKey(activeLocale, 0)
    const existing = pendingImagesRef.current.overviewCard.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.overviewCard.delete(key)
  }

  function handleStageResultBefore(index: number, staged: StagedImage) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.sectionBefore.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.sectionBefore.set(key, staged)
  }

  function handleClearStagedResultBefore(index: number) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.sectionBefore.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.sectionBefore.delete(key)
  }

  function handleStageResultAfter(index: number, staged: StagedImage) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.sectionAfter.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.sectionAfter.set(key, staged)
  }

  function handleClearStagedResultAfter(index: number) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.sectionAfter.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.sectionAfter.delete(key)
  }

  function handleStageReviewAvatar(index: number, staged: StagedImage) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.reviewAvatars.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.reviewAvatars.set(key, staged)
  }

  function handleClearStagedReviewAvatar(index: number) {
    const key = procedurePendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.reviewAvatars.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.reviewAvatars.delete(key)
  }

  useEffect(() => {
    return () => clearProcedurePendingImages(pendingImagesRef.current)
  }, [])

  async function checkSlugAvailability(slug: string) {
    const normalized = slug.trim()
    const localValidation = validateUrlSlug(normalized)
    if (!localValidation.valid) {
      setSlugAvailable(false)
      setSlugError(localValidation.error)
      return false
    }

    try {
      setCheckingSlug(true)
      setSlugError(null)
      const effectiveProcedureId = procedureId ?? createdProcedureId
      const url =
        `/api/procedures/check-slug?slug=${encodeURIComponent(normalized)}` +
        (effectiveProcedureId ? `&excludeId=${encodeURIComponent(effectiveProcedureId)}` : "")
      const res = await fetch(url)
      const json = await res.json().catch(() => ({}))
      const available = !!json?.available
      setSlugAvailable(available)
      if (!available) {
        setSlugError(typeof json?.error === "string" ? json.error : "Slug already in use")
      }
      return available
    } catch {
      setSlugAvailable(false)
      setSlugError("Failed to check slug availability")
      return false
    } finally {
      setCheckingSlug(false)
    }
  }

  useEffect(() => {
    if (!procedureId) {
      setLoadingProcedure(false)
      return
    }

    let cancelled = false
    async function loadProcedure() {
      setLoadingProcedure(true)
      setLoadError(null)
      try {
        const res = await fetch(`/api/admin/procedures/${procedureId}`, { cache: "no-store" })
        const json = await res.json().catch(() => ({}))
        if (!res.ok || json?.success === false) {
          throw new Error(typeof json?.error === "string" ? json.error : "Failed to load procedure")
        }
        const loadedForm = json?.procedure?.form
        if (!cancelled && loadedForm && typeof loadedForm === "object") {
          const raw = { ...(loadedForm as Record<string, unknown>) }
          delete raw.tags
          const rawBasic =
            raw.basicInfo && typeof raw.basicInfo === "object"
              ? normalizeProcedureBasicInfoJson(raw.basicInfo)
              : emptyBasicInfo
          raw.basicInfo = { ...emptyBasicInfo, ...rawBasic }
          if (raw.translations && typeof raw.translations === "object") {
            raw.translations = applyProcedureTranslationsFormDefaults(
              raw.translations as Record<string, unknown>
            )
          }
          setForm(raw as unknown as ProcedureFormState)
          const rawRec = raw as Record<string, unknown>
          const bi = rawRec.basicInfo && typeof rawRec.basicInfo === "object" ? (rawRec.basicInfo as Record<string, unknown>) : {}
          loadedProcedureSlugRef.current = typeof bi.slug === "string" ? bi.slug.trim() : ""
        }
      } catch (error) {
        if (!cancelled) {
          setLoadError(error instanceof Error ? error.message : "Failed to load procedure")
          setForm(emptyState)
        }
      } finally {
        if (!cancelled) setLoadingProcedure(false)
      }
    }

    void loadProcedure()
    return () => {
      cancelled = true
    }
  }, [procedureId])

  function setLocale(key: keyof LocaleContent, val: LocaleContent[keyof LocaleContent]) {
    setForm((prev) => ({
      ...prev,
      translations: {
        ...prev.translations,
        [activeLocale]: { ...prev.translations[activeLocale], [key]: val },
      },
    }))
  }

  const activeLocaleData = form.translations[activeLocale]
  const englishBasicInfo = form.basicInfo
  const localeBasicInfo =
    activeLocale === "en"
      ? englishBasicInfo
      : {
          startingFromPrice: activeLocaleData.basicInfo.startingFromPrice || englishBasicInfo.startingFromPrice,
          duration: activeLocaleData.basicInfo.duration || englishBasicInfo.duration,
          hospitalStay: activeLocaleData.basicInfo.hospitalStay || englishBasicInfo.hospitalStay,
          recovery: activeLocaleData.basicInfo.recovery || englishBasicInfo.recovery,
        }

  function setSectionFeedbackEntry(key: ProcedureSectionKey, entry: { type: "success" | "error"; message: string }) {
    setSectionFeedback((prev) => ({ ...prev, [key]: entry }))
    if (sectionFeedbackTimersRef.current[key]) clearTimeout(sectionFeedbackTimersRef.current[key])
    sectionFeedbackTimersRef.current[key] = setTimeout(() => {
      setSectionFeedback((prev) => { const next = { ...prev }; delete next[key]; return next })
    }, 3000)
  }

  function renderSectionSaveButton(key: ProcedureSectionKey) {
    const feedback = sectionFeedback[key]
    const isSaving = savingSectionKey === key

    return (
      <div className="flex items-center justify-between mt-5 pt-4 border-t border-border">
        {feedback ? (
          <span
            className="text-xs font-sans font-semibold"
            style={{ color: feedback.type === "success" ? "var(--brand-green)" : "#ef4444" }}
            role="status"
          >
            {feedback.message}
          </span>
        ) : (
          <span />
        )}
        <button
          type="button"
          disabled={isSaving || pendingAction !== null}
          onClick={() => void handleSaveSection(key)}
          className="flex cursor-pointer items-center gap-2 px-4 py-2 rounded-xl text-white text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed"
          style={{ background: "var(--brand-navy)", boxShadow: "0 2px 6px rgba(29,45,104,0.20)" }}
        >
          {isSaving ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
          ) : (
            <Save className="w-3.5 h-3.5" aria-hidden="true" />
          )}
          {isSaving ? "Saving…" : "Save Section"}
        </button>
      </div>
    )
  }

  async function handleSaveSection(sectionKey: ProcedureSectionKey) {
    setSavingSectionKey(sectionKey)
    try {
      await runSubmit("draft", {
        callOnSuccess: false,
        suppressGlobalFeedback: true,
      })
      setSectionFeedbackEntry(sectionKey, { type: "success", message: "Section saved successfully." })
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Failed to save section."
      setSectionFeedbackEntry(sectionKey, { type: "error", message: msg })
    } finally {
      setSavingSectionKey(null)
    }
  }

  async function runSubmit(
    status: "draft" | "published",
    options?: { callOnSuccess?: boolean; suppressGlobalFeedback?: boolean }
  ) {
    const callOnSuccess = options?.callOnSuccess !== false
    const suppressGlobalFeedback = options?.suppressGlobalFeedback ?? false
    const effectiveProcedureId = procedureId ?? createdProcedureId

    if (!suppressGlobalFeedback) {
      setSubmitError(null)
      setSubmitSuccess(null)
    }
    setPendingAction(status)
    try {
      const requestedSlug = form.basicInfo.slug?.trim() ?? ""
      const localValidation = validateUrlSlug(requestedSlug)
      if (!localValidation.valid) {
        const msg = localValidation.error ?? "Invalid slug."
        if (!suppressGlobalFeedback) setSubmitError(msg)
        if (suppressGlobalFeedback) throw new Error(msg)
        setPendingAction(null)
        return
      }

      let available = slugAvailable
      if (available === null) {
        available = await checkSlugAvailability(requestedSlug)
      }
      if (!available) {
        const msg = slugError ?? "Slug already in use."
        if (!suppressGlobalFeedback) setSubmitError(msg)
        if (suppressGlobalFeedback) throw new Error(msg)
        setPendingAction(null)
        return
      }

      let formForSave = form

      if (procedurePendingHasAny(pendingImagesRef.current)) {
        const procedureSlug = getProcedureSlug()
        if (!procedureSlug) {
          const msg = "Procedure slug is required before saving images."
          if (!suppressGlobalFeedback) setSubmitError(msg)
          if (suppressGlobalFeedback) throw new Error(msg)
          setPendingAction(null)
          return
        }

        const committed = await commitPendingProcedureImages(
          {
            basicInfo: form.basicInfo,
            translations: {
              en: {
                overview: form.translations.en.overview,
                beforeAfterSection: form.translations.en.beforeAfterSection,
                reviews: form.translations.en.reviews,
              },
              ar: {
                overview: form.translations.ar.overview,
                beforeAfterSection: form.translations.ar.beforeAfterSection,
                reviews: form.translations.ar.reviews,
              },
              tr: {
                overview: form.translations.tr.overview,
                beforeAfterSection: form.translations.tr.beforeAfterSection,
                reviews: form.translations.tr.reviews,
              },
            },
          },
          {
            procedureSlug,
            procedureId: effectiveProcedureId ?? undefined,
            pending: pendingImagesRef.current,
          }
        )

        formForSave = {
          ...form,
          basicInfo: committed.basicInfo,
          translations: {
            en: {
              ...form.translations.en,
              overview: committed.translations.en.overview,
              beforeAfterSection: committed.translations.en.beforeAfterSection,
              reviews: committed.translations.en.reviews,
            },
            ar: {
              ...form.translations.ar,
              overview: committed.translations.ar.overview,
              beforeAfterSection: committed.translations.ar.beforeAfterSection,
              reviews: committed.translations.ar.reviews,
            },
            tr: {
              ...form.translations.tr,
              overview: committed.translations.tr.overview,
              beforeAfterSection: committed.translations.tr.beforeAfterSection,
              reviews: committed.translations.tr.reviews,
            },
          },
        }
        setForm(formForSave)
      }

      formForSave = {
        ...formForSave,
        translations: applyProcedureTranslationsFormDefaults(
          formForSave.translations as unknown as Record<string, unknown>
        ) as ProcedureFormState["translations"],
      }

      const payload = { ...formForSave, status }
      const url = effectiveProcedureId ? `/api/admin/procedures/${effectiveProcedureId}` : "/api/admin/procedures"
      const method = effectiveProcedureId ? "PUT" : "POST"
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.success === false) {
        throw new Error(typeof json?.error === "string" ? json.error : "Failed to save.")
      }

      const newId =
        typeof json?.procedure?.id === "string"
          ? json.procedure.id
          : typeof json?.id === "string"
            ? json.id
            : null
      if (!procedureId && !createdProcedureId && typeof newId === "string") {
        setCreatedProcedureId(newId)
      }

      const savedForm = json?.procedure?.form
      if (savedForm && typeof savedForm === "object") {
        setForm((prev) => mergeProcedureFormMediaFromSavedForm(prev, savedForm))
      } else {
        setForm(formForSave)
      }

      loadedProcedureSlugRef.current = requestedSlug

      if (!suppressGlobalFeedback) {
        setSubmitSuccess(status === "published" ? "Procedure published successfully." : "Saved as draft.")
      }
      if (callOnSuccess && onSuccess) {
        onSuccess()
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Failed to save."
      if (!suppressGlobalFeedback) setSubmitError(msg)
      if (suppressGlobalFeedback) throw new Error(msg)
    } finally {
      setPendingAction(null)
    }
  }

  if (procedureId && loadingProcedure) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 rounded-2xl border border-border bg-card py-24" role="status" aria-live="polite">
        <Loader2 className="w-10 h-10 animate-spin text-[var(--brand-navy)]" aria-hidden="true" />
        <p className="text-sm text-muted-foreground font-sans">Loading procedure…</p>
      </div>
    )
  }

  if (procedureId && loadError) {
    return (
      <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-4 text-sm text-red-800 font-sans" role="alert">
        {loadError}
      </div>
    )
  }

  return (
    <form
      className="flex flex-col gap-6 pb-12"
      onSubmit={(e) => { e.preventDefault(); void runSubmit("published") }}
      noValidate
    >
      {/* Section 1 — Basic Information */}
      <Section id="section-basic" icon={<User className="w-4 h-4" />} title="Basic Information" description="Core details shared across all languages" accent="navy">
        {/* Language tabs — same pattern as ArticleForm / DoctorForm Basic Information */}
        <div className="flex items-center gap-2 rounded-xl border border-border bg-muted/30 p-1 mb-5">
          {([
            { locale: "en", label: "English" },
            { locale: "ar", label: "Arabic" },
            { locale: "tr", label: "Turkish" },
          ] as const).map((tab) => (
            <button
              key={tab.locale}
              type="button"
              onClick={() => setActiveLocale(tab.locale)}
              className="px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-colors cursor-pointer"
              style={
                activeLocale === tab.locale
                  ? { background: "var(--brand-green)", color: "#fff" }
                  : { color: "var(--muted-foreground)" }
              }
            >
              {tab.label}
            </button>
          ))}
          {sharedFieldsLocked && (
            <p className="text-xs text-amber-600 font-sans">
              Shared fields can only be edited from the English tab.
            </p>
          )}
        </div>

        {/* Category */}
        <div className="mb-5">
          <CategorySelect
            value={form.categoryId}
            onChange={(id) => setForm((prev) => ({ ...prev, categoryId: id }))}
            disabled={sharedFieldsLocked}
            nativeRequired={false}
          />
        </div>



        <ProcedureBasicInfo
          value={{
            ...form.basicInfo,
            beforeAfterImages: form.basicInfo.beforeAfterImages ?? [],
            startingFromPrice: localeBasicInfo.startingFromPrice,
            duration: localeBasicInfo.duration,
            hospitalStay: localeBasicInfo.hospitalStay,
            recovery: localeBasicInfo.recovery,
            name: activeLocaleData.name,
            description: activeLocaleData.description,
            stayCity: activeLocaleData.stayCity ?? (activeLocale === "en" ? form.basicInfo.stayCity : ""),
            slug: form.basicInfo.slug,
          }}
          onChange={(v) => {
            setForm((prev) => {
              const nextBasicInfo = { ...prev.basicInfo }
              if (activeLocale === "en") {
                nextBasicInfo.startingFromPrice = v.startingFromPrice
                nextBasicInfo.duration = v.duration
                nextBasicInfo.hospitalStay = v.hospitalStay
                nextBasicInfo.recovery = v.recovery
                nextBasicInfo.stayCity = v.stayCity
              }

              return {
                ...prev,
                basicInfo: {
                  ...nextBasicInfo,
                  slug: v.slug,
                  mainImage: v.mainImage,
                  mainImagePublicId: v.mainImagePublicId,
                  beforeAfterImages: v.beforeAfterImages,
                  rating: v.rating,
                  reviewCount: v.reviewCount,
                  stayDays: v.stayDays,
                },
                translations: {
                  ...prev.translations,
                  [activeLocale]: {
                    ...prev.translations[activeLocale],
                    name: v.name,
                    description: v.description,
                    stayCity: v.stayCity,
                    basicInfo: {
                      startingFromPrice: v.startingFromPrice,
                      duration: v.duration,
                      hospitalStay: v.hospitalStay,
                      recovery: v.recovery,
                    },
                  },
                },
              }
            })
            setSlugAvailable(null)
            const localValidation = validateUrlSlug(v.slug)
            setSlugError(localValidation.valid ? null : localValidation.error)
          }}
          onSlugBlur={(value) => {
            void checkSlugAvailability(value)
          }}
          checkingSlug={checkingSlug}
          slugError={slugError}
          slugAvailable={slugAvailable}
          sharedFieldsLocked={sharedFieldsLocked}
          getProcedureSlug={getProcedureSlug}
          onStageMainPhoto={handleStageMainPhoto}
          onClearStagedMainPhoto={handleClearStagedMainPhoto}
          onStageBasicBefore={handleStageBasicBefore}
          onClearStagedBasicBefore={handleClearStagedBasicBefore}
          onStageBasicAfter={handleStageBasicAfter}
          onClearStagedBasicAfter={handleClearStagedBasicAfter}
        />

        {/* Featured procedure (matches Featured Article exactly) */}
        <div className="mb-5 flex items-center justify-between gap-4 px-4 py-3 rounded-xl border border-border bg-card">
          <div className="flex items-center gap-2.5">
            <Star className="w-4 h-4" style={{ color: "var(--brand-navy)" }} aria-hidden="true" />
            <div>
              <p className="text-sm font-semibold text-foreground font-sans">Featured Procedure</p>
              <p className="text-xs text-muted-foreground font-sans">Pin this procedure to appear in featured sections</p>
            </div>
          </div>
          <button
            type="button"
            role="switch"
            aria-checked={form.isFeatured}
            onClick={() => setForm((prev) => ({ ...prev, isFeatured: !prev.isFeatured }))}
            disabled={sharedFieldsLocked}
            className="relative cursor-pointer w-11 h-6 rounded-full transition-colors duration-200 shrink-0 focus:outline-none focus:ring-2 focus:ring-[#2BB673]/40 disabled:opacity-60"
            style={{
              background: form.isFeatured ? "var(--brand-green)" : "var(--border)",
            }}
          >
            <span
              className="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-sm transition-transform duration-200"
              style={{ transform: form.isFeatured ? "translateX(20px)" : "translateX(0px)" }}
            />
            <span className="sr-only">{form.isFeatured ? "Featured" : "Not featured"}</span>
          </button>
        </div>

        {renderSectionSaveButton("basic")}
      </Section>

      {/* Section 2 — Quick Stats */}
      <Section id="section-quick-stats" icon={<Activity className="w-4 h-4" />} title="Quick Stats Section" description="Key statistics displayed prominently on the procedure page" accent="green">
        <ProcedureQuickStats
          value={form.quickStats}
          onChange={(v) => setForm((prev) => ({ ...prev, quickStats: v }))}
        />
        {renderSectionSaveButton("quickStats")}
      </Section>

      {/* Section 3 — Overview */}
      <Section id="section-overview" icon={<Eye className="w-4 h-4" />} title="Overview Section" description="Detailed description, key takeaways, and overview card" accent="navy">
        <ProcedureOverview
          value={activeLocaleData.overview}
          onChange={(v) => setLocale("overview", v)}
          sharedFieldsLocked={sharedFieldsLocked}
          getProcedureSlug={getProcedureSlug}
          onStageOverviewCard={handleStageOverviewCard}
          onClearStagedOverviewCard={handleClearStagedOverviewCard}
        />
        {renderSectionSaveButton("overview")}
      </Section>

      {/* Section 4 — Countries Comparison */}
      <Section id="section-countries" icon={<Globe className="w-4 h-4" />} title="Countries Comparison Section" description="Compare procedure prices across different countries" accent="green">
        <ProcedureCountriesComparison
          value={activeLocaleData.countriesComparison}
          onChange={(v) => setLocale("countriesComparison", v)}
        />
        {renderSectionSaveButton("countries")}
      </Section>

      {/* Section 5 — Process */}
      <Section id="section-process" icon={<Layers className="w-4 h-4" />} title="Process Section" description="Step-by-step procedure process" accent="navy">
        <ProcedureProcess
          value={activeLocaleData.process}
          onChange={(v) => setLocale("process", v)}
        />
        {renderSectionSaveButton("process")}
      </Section>

      {/* Section 6 — Benefits */}
      <Section id="section-benefits" icon={<Zap className="w-4 h-4" />} title="Benefits Section" description="Key benefits and advantages of this procedure" accent="green">
        <ProcedureBenefits
          value={activeLocaleData.benefits}
          onChange={(v) => setLocale("benefits", v)}
        />
        {renderSectionSaveButton("benefits")}
      </Section>
               {/* Section 15 — Video */}
      <Section id="section-video" icon={<Video className="w-4 h-4" />} title="Video Section" description="Eyebrow, title, subtitle and video link" accent="navy">
        <ProcedureVideoSection
          value={activeLocaleData.videoSection}
          onChange={(v) => setLocale("videoSection", v)}
        />
        {renderSectionSaveButton("video")}
      </Section>
      {/* Section 7 — Before & After */}
      <Section id="section-before-after" icon={<Image className="w-4 h-4" />} title="Before & After Section" description="Patient result gallery with filter categories" accent="navy">
        <ProcedureBeforeAfterSection
          value={activeLocaleData.beforeAfterSection}
          onChange={(v) => setLocale("beforeAfterSection", v)}
          sharedFieldsLocked={sharedFieldsLocked}
          getProcedureSlug={getProcedureSlug}
          onStageResultBefore={handleStageResultBefore}
          onClearStagedResultBefore={handleClearStagedResultBefore}
          onStageResultAfter={handleStageResultAfter}
          onClearStagedResultAfter={handleClearStagedResultAfter}
        />
        {renderSectionSaveButton("beforeAfter")}
      </Section>

      {/* Section 8 — Doctors */}
      <Section id="section-doctors" icon={<User className="w-4 h-4" />} title="Doctors Section" description="Section heading for the related doctors display" accent="green">
        <div className="flex flex-col gap-3 rounded-xl border border-border bg-muted/30 p-4">
          <div className="flex items-center gap-2 pb-2 border-b border-border">
            <span className="w-1 h-4 rounded-full shrink-0" style={{ background: "var(--brand-green)" }} aria-hidden="true" />
            <p className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground font-sans">Section Headings</p>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-semibold text-foreground font-sans">Eyebrow</label>
              <input
                type="text"
                value={activeLocaleData.doctorsSectionEyebrow}
                onChange={(e) => setLocale("doctorsSectionEyebrow", e.target.value)}
                placeholder="e.g. Our Specialists"
                className="w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673]"
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-semibold text-foreground font-sans">Title</label>
              <input
                type="text"
                value={activeLocaleData.doctorsSectionTitle}
                onChange={(e) => setLocale("doctorsSectionTitle", e.target.value)}
                placeholder="e.g. Meet Our Expert Doctors"
                className="w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673]"
              />
            </div>
          </div>
        </div>
        {renderSectionSaveButton("doctors")}
      </Section>

      {/* Section 9 — Recovery */}
      <Section id="section-recovery" icon={<HeartHandshake className="w-4 h-4" />} title="Recovery Steps" description="Recovery timeline with color-coded steps and discomfort levels" accent="navy">
        <ProcedureRecovery
          value={activeLocaleData.recovery}
          onChange={(v) => setLocale("recovery", v)}
        />
        {renderSectionSaveButton("recovery")}
      </Section>

      {/* Section 10 — Package */}
      <Section id="section-package" icon={<Package className="w-4 h-4" />} title="All-Inclusive Package Section" description="Package features, pricing, and CTA" accent="green">
        <ProcedurePackage
          value={activeLocaleData.packageSection}
          onChange={(v) => setLocale("packageSection", v)}
        />
        {renderSectionSaveButton("package")}
      </Section>

      {/* Section 11 — Reviews */}
      <Section id="section-reviews" icon={<Star className="w-4 h-4" />} title="Reviews Section" description="Patient testimonials and ratings" accent="navy">
        <ProcedureReviews
          value={activeLocaleData.reviews}
          onChange={(v) => setLocale("reviews", v)}
          eyebrow={activeLocaleData.reviewsEyebrow}
          onEyebrowChange={(val) => setLocale("reviewsEyebrow", val)}
          sectionTitle={activeLocaleData.reviewsTitle}
          onSectionTitleChange={(val) => setLocale("reviewsTitle", val)}
          sharedValuesLocked={sharedFieldsLocked}
          getProcedureSlug={getProcedureSlug}
          onStageReviewAvatar={handleStageReviewAvatar}
          onClearStagedReviewAvatar={handleClearStagedReviewAvatar}
        />
        {renderSectionSaveButton("reviews")}
      </Section>

      {/* Section 12 — FAQ */}
      <Section id="section-faq" icon={<HelpCircle className="w-4 h-4" />} title="FAQ Section" description="Frequently asked questions about this procedure" accent="green">
        <ProcedureFAQ
          items={activeLocaleData.faqItems}
          onChange={(v) => setLocale("faqItems", v)}
          eyebrow={activeLocaleData.faqEyebrow}
          onEyebrowChange={(val) => setLocale("faqEyebrow", val)}
          sectionTitle={activeLocaleData.faqTitle}
          onSectionTitleChange={(val) => setLocale("faqTitle", val)}
          subtitle={activeLocaleData.faqSubtitle}
          onSubtitleChange={(val) => setLocale("faqSubtitle", val)}
          buttonText={activeLocaleData.faqButtonText}
          onButtonTextChange={(val) => setLocale("faqButtonText", val)}
          buttonLink={activeLocaleData.faqButtonLink}
          onButtonLinkChange={(val) => setLocale("faqButtonLink", val)}
        />
        {renderSectionSaveButton("faq")}
      </Section>

      {/* Section 13 — Related Procedures */}
      <Section id="section-related" icon={<Link2 className="w-4 h-4" />} title="Related Procedures Section" description="Link to other related procedures" accent="navy">
        <ProcedureRelated
          value={activeLocaleData.related}
          onChange={(v) => setLocale("related", v)}
        />
        {renderSectionSaveButton("related")}
      </Section>

      {/* Section 14 — CTA */}
      <Section id="section-cta" icon={<HeartHandshake className="w-4 h-4" />} title="CTA Section" description="Call-to-action with contact form for lead generation" accent="green">
        <ProcedureCTA
          value={activeLocaleData.cta}
          onChange={(v) => setLocale("cta", v)}
        />
        {renderSectionSaveButton("cta")}
      </Section>

     

      {/* Submit actions */}
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 flex-wrap">
        <div className="flex-1 min-w-0">
          {submitError && (
            <div
              className="inline-flex items-start gap-2 px-4 py-2.5 rounded-xl text-sm font-sans"
              style={{ background: "rgba(239,68,68,0.08)", color: "#ef4444", border: "1px solid rgba(239,68,68,0.20)" }}
              role="alert"
            >
              {submitError}
            </div>
          )}
          {submitSuccess && (
            <div
              className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-sans"
              style={{ background: "rgba(43,182,115,0.08)", color: "var(--brand-green)", border: "1px solid rgba(43,182,115,0.20)" }}
              role="status"
            >
              {submitSuccess}
            </div>
          )}
        </div>

        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 shrink-0">
          <button
            type="button"
            onClick={() => router.push(cancelHref)}
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-sm font-semibold font-sans border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <ChevronLeft className="w-4 h-4" aria-hidden="true" />
            Cancel
          </button>

          <button
            type="button"
            onClick={() => void runSubmit("draft")}
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed"
            style={{ background: "var(--brand-navy)", boxShadow: "0 2px 8px rgba(29,45,104,0.25)" }}
          >
            {pendingAction === "draft" ? (
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
            ) : (
              <Save className="w-4 h-4" aria-hidden="true" />
            )}
            {pendingAction === "draft" ? "Saving…" : "Save as Draft"}
          </button>

          <button
            type="submit"
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed"
            style={{ background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.3)" }}
          >
            {pendingAction === "published" ? (
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
            ) : (
              <Send className="w-4 h-4" aria-hidden="true" />
            )}
            {pendingAction === "published" ? "Publishing…" : "Publish Procedure"}
          </button>
        </div>
      </div>
    </form>
  )
}
