"use client"

import React, { useEffect, useRef, useState } from "react"
import {
  Sparkles,
  SlidersHorizontal,
  BarChart2,
  GitCompareArrows,
  Globe,
  HelpCircle,
  Link2,
  Megaphone,
  Save,
  Pencil,
  Loader2,
  CheckCircle,
  AlertCircle,
} from "lucide-react"

import { ProceduresHeroSection } from "./ProceduresHeroSection"
import { ProceduresFiltersSection } from "./ProceduresFiltersSection"
import { ProceduresStatsSection } from "./ProceduresStatsSection"
import { ProceduresComparisonSection } from "./ProceduresComparisonSection"
import { ProceduresWhyTurkeySection } from "./ProceduresWhyTurkeySection"
import { ProceduresFAQSection } from "./ProceduresFAQSection"
import { ProceduresQuickLinksSection } from "./ProceduresQuickLinksSection"
import { ProceduresFinalCTASection } from "./ProceduresFinalCTASection"
import { LanguageTabs, type Language } from "@/components/dashboard/shared/LanguageTabs"
import {
  createEmptyProceduresPageFormState,
  type ProceduresPageFormStateShape,
} from "@/lib/pages/procedures-page/form-types"
import { PROCEDURES_PAGE_LOCALE_CODES } from "@/lib/pages/procedures-page/locales"
import {
  CmsPagePendingProvider,
  useCmsPagePendingRef,
} from "@/components/dashboard/cms-pages/CmsPagePendingContext"
import {
  clearAllCmsPending,
  commitPendingHeroLocales,
  cmsPendingHasAny,
} from "@/lib/media-manager/cms-page-pending"

// ─── Section wrapper ──────────────────────────────────────────────────────────

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

function Section({ id, icon, title, description, accent, children, footer }: 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>
      {footer ? <div className="px-6 pb-6">{footer}</div> : null}
    </section>
  )
}

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

const LOCALE_CODES: Language[] = [...PROCEDURES_PAGE_LOCALE_CODES]

export function ProceduresPageForm() {
  const [activeLanguage, setActiveLanguage] = useState<Language>("en")
  return (
    <CmsPagePendingProvider activeLanguage={activeLanguage}>
      <ProceduresPageFormBody
        activeLanguage={activeLanguage}
        setActiveLanguage={setActiveLanguage}
      />
    </CmsPagePendingProvider>
  )
}

function ProceduresPageFormBody({
  activeLanguage,
  setActiveLanguage,
}: {
  activeLanguage: Language
  setActiveLanguage: (lang: Language) => void
}) {
  const [formByLanguage, setFormByLanguage] = useState<Record<Language, ProceduresPageFormStateShape>>({
    en: createEmptyProceduresPageFormState(),
    tr: createEmptyProceduresPageFormState(),
    ar: createEmptyProceduresPageFormState(),
  })
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)
  const [savingSectionKey, setSavingSectionKey] = useState<keyof ProceduresPageFormStateShape | null>(null)
  const [sectionFeedback, setSectionFeedback] = useState<
    Partial<Record<keyof ProceduresPageFormStateShape, { type: "success" | "error"; message: string }>>
  >({})
  const sectionFeedbackTimersRef = useRef<
    Partial<Record<keyof ProceduresPageFormStateShape, ReturnType<typeof setTimeout>>>
  >({})
  const [isLockedForEditing, setIsLockedForEditing] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null)
  const [saveError, setSaveError] = useState<string | null>(null)
  const [englishValidationTouched, setEnglishValidationTouched] = useState(false)

  const isFormLocked = loading || saving || savingSectionKey !== null || isLockedForEditing
  const pendingImages = useCmsPagePendingRef()

  useEffect(() => {
    return () => clearAllCmsPending(pendingImages)
  }, [])

  async function commitPendingImagesIfAny(): Promise<Record<Language, ProceduresPageFormStateShape>> {
    if (!cmsPendingHasAny(pendingImages)) return buildPayload()
    const merged = await commitPendingHeroLocales(formByLanguage, pendingImages)
    setFormByLanguage(merged)
    return merged
  }

  function getEnglishValidationErrors() {
    const en = formByLanguage.en
    const heroCategoryErrors = en.hero.categories.map((item) => ({
      icon: !item.icon.trim(),
      name: !item.name.trim(),
    }))
    const filterItemErrors = en.filters.filters.map((item) => ({
      label: !item.label.trim(),
      options: item.options.length === 0 || item.options.some((opt) => !opt.label.trim()),
      optionItems: item.options.map((opt) => ({ label: !opt.label.trim() })),
    }))
    const mainFilterOptionErrors = en.filters.mainFilterOptions.map((item) => ({ label: !item.label.trim() }))
    const statErrors = en.stats.stats.map((item) => ({ label: !item.label.trim(), value: !item.value.trim() }))
    const whyFeatureErrors = en.whyTurkey.features.map((item) => ({
      cardColor: !item.cardColor.trim(),
      icon: !item.icon.trim(),
      title: !item.title.trim(),
      description: !item.description.trim(),
      label: !item.label.trim(),
      value: !item.value.trim(),
    }))
    const faqItemErrors = en.faq.faqs.map((item) => ({
      question: !item.question.trim(),
      answer: !item.answer.trim(),
    }))
    const quickLinkErrors = en.quickLinks.links.map((item) => ({
      icon: !item.icon.trim(),
      title: !item.title.trim(),
      subtitle: !item.subtitle.trim(),
      link: !item.link.trim(),
    }))
    return {
      hero: {
        title: !en.hero.title.trim(),
        description: !en.hero.description.trim(),
        image: !en.hero.image.trim(),
        categories: en.hero.categories.length === 0 || heroCategoryErrors.some((item) => item.icon || item.name),
        categoryItems: heroCategoryErrors,
      },
      filters: {
        filters: en.filters.filters.length === 0 || filterItemErrors.some((item) => item.label || item.options),
        filterItems: filterItemErrors,
        mainFilterOptionsTitle: !en.filters.mainFilterOptionsTitle.trim(),
        mainFilterOptions:
          en.filters.mainFilterOptions.length === 0 || mainFilterOptionErrors.some((item) => item.label),
        mainFilterOptionItems: mainFilterOptionErrors,
      },
      stats: {
        stats: en.stats.stats.length === 0 || statErrors.some((item) => item.label || item.value),
        statItems: statErrors,
      },
      comparison: {
        eyebrow: !en.comparison.eyebrow.trim(),
        title: !en.comparison.title.trim(),
        subtitle: !en.comparison.subtitle.trim(),
      },
      whyTurkey: {
        eyebrow: !en.whyTurkey.eyebrow.trim(),
        title: !en.whyTurkey.title.trim(),
        features: en.whyTurkey.features.length === 0 || whyFeatureErrors.some((item) => item.cardColor || item.icon || item.title || item.description || item.label || item.value),
        featureItems: whyFeatureErrors,
      },
      faq: {
        eyebrow: !en.faq.eyebrow.trim(),
        title: !en.faq.title.trim(),
        faqs: en.faq.faqs.length === 0 || faqItemErrors.some((item) => item.question || item.answer),
        faqItems: faqItemErrors,
      },
      quickLinks: {
        links: en.quickLinks.links.length === 0 || quickLinkErrors.some((item) => item.icon || item.title || item.subtitle || item.link),
        linkItems: quickLinkErrors,
      },
      finalCta: {
        eyebrow: !en.finalCta.eyebrow.trim(),
        title: !en.finalCta.title.trim(),
        subtitle: !en.finalCta.subtitle.trim(),
        buttonIcon: !en.finalCta.buttonIcon.trim(),
        buttonText: !en.finalCta.buttonText.trim(),
        buttonLink: !en.finalCta.buttonLink.trim(),
      },
    }
  }

  function hasEnglishValidationErrors() {
    const errors = getEnglishValidationErrors()
    return (
      errors.hero.title ||
      errors.hero.description ||
      errors.hero.image ||
      errors.hero.categories ||
      errors.filters.filters ||
      errors.filters.mainFilterOptionsTitle ||
      errors.filters.mainFilterOptions ||
      errors.stats.stats ||
      errors.comparison.eyebrow ||
      errors.comparison.title ||
      errors.comparison.subtitle ||
      errors.whyTurkey.eyebrow ||
      errors.whyTurkey.title ||
      errors.whyTurkey.features ||
      errors.faq.eyebrow ||
      errors.faq.title ||
      errors.faq.faqs ||
      errors.quickLinks.links ||
      errors.finalCta.eyebrow ||
      errors.finalCta.title ||
      errors.finalCta.subtitle ||
      errors.finalCta.buttonIcon ||
      errors.finalCta.buttonText ||
      errors.finalCta.buttonLink
    )
  }

  // ── Load ──────────────────────────────────────────────────────────────────

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch("/api/admin/procedures-page", { credentials: "include" })
        const data: {
          success?: boolean
          error?: string
          locales?: Partial<Record<Language, ProceduresPageFormStateShape>>
        } = await res.json()

        if (cancelled) return
        if (!res.ok || !data.success) {
          setLoadError(data.error ?? "Failed to load Procedures page.")
          return
        }

        setFormByLanguage((prev) => {
          const next = { ...prev }
          for (const code of LOCALE_CODES) {
            const chunk = data.locales?.[code]
            if (chunk?.hero) next[code] = chunk
          }
          return next
        })
      } catch {
        if (!cancelled) setLoadError("Failed to load Procedures page. Please try again.")
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    void load()
    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    return () => {
      for (const timer of Object.values(sectionFeedbackTimersRef.current)) {
        if (timer) clearTimeout(timer)
      }
    }
  }, [])

  // ── Helpers ───────────────────────────────────────────────────────────────

  function showSectionFeedback(
    sectionKey: keyof ProceduresPageFormStateShape,
    type: "success" | "error",
    message: string
  ) {
    const existing = sectionFeedbackTimersRef.current[sectionKey]
    if (existing) clearTimeout(existing)
    setSectionFeedback((prev) => ({ ...prev, [sectionKey]: { type, message } }))
    sectionFeedbackTimersRef.current[sectionKey] = setTimeout(() => {
      setSectionFeedback((prev) => {
        const next = { ...prev }
        delete next[sectionKey]
        return next
      })
      delete sectionFeedbackTimersRef.current[sectionKey]
    }, 3500)
  }

  function updateSection<K extends keyof ProceduresPageFormStateShape>(
    key: K,
    value: ProceduresPageFormStateShape[K]
  ) {
    if (isFormLocked) return
    setFormByLanguage((prev) => ({
      ...prev,
      [activeLanguage]: { ...prev[activeLanguage], [key]: value },
    }))
    setSaveSuccess(null)
    setSaveError(null)
  }

  function buildPayload(): Record<Language, ProceduresPageFormStateShape> {
    return {
      en: { ...formByLanguage.en },
      tr: { ...formByLanguage.tr },
      ar: { ...formByLanguage.ar },
    }
  }

  async function refreshFromServer() {
    const res = await fetch("/api/admin/procedures-page", { credentials: "include" })
    const data: {
      success?: boolean
      error?: string
      locales?: Partial<Record<Language, ProceduresPageFormStateShape>>
    } = await res.json()
    if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to refresh latest data.")
    setFormByLanguage((prev) => {
      const next = { ...prev }
      for (const code of LOCALE_CODES) {
        const chunk = data.locales?.[code]
        if (chunk?.hero) next[code] = chunk
      }
      return next
    })
  }

  // ── Save all ──────────────────────────────────────────────────────────────

  async function handleSave() {
    setEnglishValidationTouched(true)
    if (hasEnglishValidationErrors()) {
      setActiveLanguage("en")
      setSaveSuccess(null)
      setSaveError("Please fill all required English fields.")
      return
    }
    setSaving(true)
    setSaveSuccess(null)
    setSaveError(null)
    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/procedures-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to save")
      await refreshFromServer()
      setSaveSuccess("Procedures page saved successfully.")
      setIsLockedForEditing(true)
    } catch (error) {
      setActiveLanguage("en")
      setSaveError(error instanceof Error ? error.message : "Something went wrong. Please try again.")
    } finally {
      setSaving(false)
    }
  }

  // ── Save section ──────────────────────────────────────────────────────────

  async function handleSaveSection(sectionKey: keyof ProceduresPageFormStateShape) {
    setEnglishValidationTouched(true)
    setSavingSectionKey(sectionKey)
    setSaveSuccess(null)
    setSaveError(null)
    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/procedures-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales, sectionKey }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to save section")
      await refreshFromServer()
      setSaveSuccess(`${String(sectionKey)} section saved successfully.`)
      showSectionFeedback(sectionKey, "success", "Section saved successfully.")
    } catch (error) {
      const msg = error instanceof Error ? error.message : "Something went wrong. Please try again."
      setActiveLanguage("en")
      setSaveError(msg)
      showSectionFeedback(sectionKey, "error", msg)
    } finally {
      setSavingSectionKey(null)
    }
  }

  // ── Section save button renderer ─────────────────────────────────────────

  function renderSectionSaveButton(sectionKey: keyof ProceduresPageFormStateShape) {
    const isSavingThis = savingSectionKey === sectionKey
    const feedback = sectionFeedback[sectionKey]
    return (
      <div className="flex flex-col items-end gap-2">
        <button
          type="button"
          onClick={() => void handleSaveSection(sectionKey)}
          disabled={isFormLocked}
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold font-sans text-white transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: "var(--brand-navy)" }}
        >
          {isSavingThis ? (
            <>
              <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
              Saving section...
            </>
          ) : (
            <>
              <Save className="w-3.5 h-3.5" aria-hidden="true" />
              Save Section
            </>
          )}
        </button>
        {feedback ? (
          <div
            className="text-xs font-sans px-3 py-1.5 rounded-lg border max-w-[420px]"
            style={
              feedback.type === "success"
                ? {
                    background: "rgba(43,182,115,0.08)",
                    borderColor: "rgba(43,182,115,0.30)",
                    color: "var(--brand-green)",
                  }
                : {
                    background: "rgba(239,68,68,0.08)",
                    borderColor: "rgba(239,68,68,0.30)",
                    color: "#dc2626",
                  }
            }
            role="alert"
          >
            {feedback.message}
          </div>
        ) : null}
      </div>
    )
  }

  const form = formByLanguage[activeLanguage]

  return (
    <div className="flex flex-col gap-6">
      {/* Load error */}
      {loadError && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(239,68,68,0.06)",
            borderColor: "rgba(239,68,68,0.30)",
            color: "#dc2626",
          }}
          role="alert"
        >
          <AlertCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {loadError}
        </div>
      )}

      {/* Language Tabs */}
      <div
        className="bg-card rounded-2xl border border-border overflow-hidden"
        role="tabpanel"
        id={`language-panel-${activeLanguage}`}
        aria-labelledby={`language-tab-${activeLanguage}`}
      >
        <div
          className="flex items-center gap-2 px-6 py-3 border-b border-border"
          style={{ background: "rgba(29,45,104,0.02)" }}
        >
          <div
            className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0 text-sm"
            style={{ background: "rgba(29,45,104,0.08)" }}
            aria-hidden="true"
          >
            🌐
          </div>
          <div>
            <p className="text-sm font-bold font-sans" style={{ color: "var(--brand-navy)" }}>
              Page Language
            </p>
            <p className="text-xs text-muted-foreground font-sans leading-none mt-0.5">
              English is required to save. Turkish and Arabic are optional.
            </p>
          </div>
        </div>
        <div className="px-6 py-4">
          <LanguageTabs
            activeLanguage={activeLanguage}
            onChange={(lang) => {
              if (isFormLocked) return
              setActiveLanguage(lang)
            }}
            disabled={isFormLocked}
          />
        </div>
      </div>

      {/* Section 1 — Hero */}
      <Section
        id="section-procedures-hero"
        icon={<Sparkles className="w-4 h-4" />}
        title="Hero Section"
        description="Title, description, image, and categories"
        accent="navy"
        footer={renderSectionSaveButton("hero")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresHeroSection
            value={form.hero}
            onChange={(v) => updateSection("hero", v)}
            isDefaultLanguage={activeLanguage === "en"}
            defaultImageUrl={formByLanguage.en.hero.image || undefined}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().hero : undefined}
          />
        )}
      </Section>

      {/* Section 2 — Filters */}
      <Section
        id="section-procedures-filters"
        icon={<SlidersHorizontal className="w-4 h-4" />}
        title="Filters Section"
        description="Filter groups, their options, and the main filter name options"
        accent="green"
        footer={renderSectionSaveButton("filters")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresFiltersSection
            value={form.filters}
            onChange={(v) => updateSection("filters", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().filters : undefined}
          />
        )}
      </Section>

      {/* Section 3 — Statistics */}
      <Section
        id="section-procedures-stats"
        icon={<BarChart2 className="w-4 h-4" />}
        title="Statistics Section"
        description="Key statistics displayed in the stats bar"
        accent="navy"
        footer={renderSectionSaveButton("stats")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresStatsSection
            value={form.stats}
            onChange={(v) => updateSection("stats", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().stats : undefined}
          />
        )}
      </Section>

      {/* Section 4 — Procedure Comparison */}
      <Section
        id="section-procedures-comparison"
        icon={<GitCompareArrows className="w-4 h-4" />}
        title="Procedure Comparison Section"
        description="Eyebrow, title, and subtitle for the comparison section"
        accent="green"
        footer={renderSectionSaveButton("comparison")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresComparisonSection
            value={form.comparison}
            onChange={(v) => updateSection("comparison", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().comparison : undefined}
          />
        )}
      </Section>

      {/* Section 5 — Why Turkey */}
      <Section
        id="section-procedures-why-turkey"
        icon={<Globe className="w-4 h-4" />}
        title="Why Turkey Section"
        description="Eyebrow, title, and feature cards with color, icon, title, description, and stat"
        accent="navy"
        footer={renderSectionSaveButton("whyTurkey")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresWhyTurkeySection
            value={form.whyTurkey}
            onChange={(v) => updateSection("whyTurkey", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().whyTurkey : undefined}
          />
        )}
      </Section>

      {/* Section 6 — FAQ */}
      <Section
        id="section-procedures-faq"
        icon={<HelpCircle className="w-4 h-4" />}
        title="FAQ Section"
        description="Eyebrow, title, and repeatable FAQ items"
        accent="green"
        footer={renderSectionSaveButton("faq")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresFAQSection
            value={form.faq}
            onChange={(v) => updateSection("faq", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().faq : undefined}
          />
        )}
      </Section>

      {/* Section 7 — Quick Links */}
      <Section
        id="section-procedures-quick-links"
        icon={<Link2 className="w-4 h-4" />}
        title="Quick Links Section"
        description="Repeatable link cards with icon, title, subtitle, and URL"
        accent="navy"
        footer={renderSectionSaveButton("quickLinks")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresQuickLinksSection
            value={form.quickLinks}
            onChange={(v) => updateSection("quickLinks", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().quickLinks : undefined}
          />
        )}
      </Section>

      {/* Section 8 — Final CTA */}
      <Section
        id="section-procedures-final-cta"
        icon={<Megaphone className="w-4 h-4" />}
        title="Final CTA Section"
        description="Eyebrow, title, subtitle, and call-to-action button"
        accent="green"
        footer={renderSectionSaveButton("finalCta")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <ProceduresFinalCTASection
            value={form.finalCta}
            onChange={(v) => updateSection("finalCta", v)}
            disabled={isFormLocked}
            validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().finalCta : undefined}
          />
        )}
      </Section>

      {/* Feedback messages */}
      {saveSuccess && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(43,182,115,0.08)",
            borderColor: "rgba(43,182,115,0.30)",
            color: "var(--brand-green)",
          }}
          role="alert"
        >
          <CheckCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveSuccess}
        </div>
      )}
      {saveError && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{
            background: "rgba(239,68,68,0.06)",
            borderColor: "rgba(239,68,68,0.30)",
            color: "#dc2626",
          }}
          role="alert"
        >
          <AlertCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveError}
        </div>
      )}

      {/* Global save button */}
      <div className="flex items-center justify-end gap-3 pb-2">
        {isLockedForEditing && (
          <button
            type="button"
            onClick={() => {
              setIsLockedForEditing(false)
              setSaveSuccess(null)
              setSaveError(null)
            }}
            disabled={saving || loading}
            className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold font-sans border border-border text-foreground bg-card transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          >
            <Pencil className="w-4 h-4" aria-hidden="true" />
            Edit Page
          </button>
        )}
        <button
          type="button"
          onClick={() => void handleSave()}
          disabled={isFormLocked}
          className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold font-sans text-white transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: "var(--brand-navy)" }}
        >
          {saving ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
              Saving...
            </>
          ) : (
            <>
              <Save className="w-4 h-4" aria-hidden="true" />
              Save Changes
            </>
          )}
        </button>
      </div>
    </div>
  )
}
