"use client"

import React, { useEffect, useRef, useState } from "react"
import {
  Sparkles,
  BarChart3,
  LayoutGrid,
  ShieldCheck,
  Play,
  GitBranch,
  UserRound,
  Star,
  Building2,
  Award,
  HelpCircle,
  Newspaper,
  Megaphone,
  Save,
  Pencil,
  Loader2,
  CheckCircle,
  AlertCircle,
} from "lucide-react"

import { HeroSection } from "./HeroSection"
import { StatsSection } from "./StatsSection"
import { ServicesSection } from "./ServicesSection"
import { WhyChooseUsSection } from "./WhyChooseUsSection"
import { TestimonialsSection } from "./TestimonialsSection"
import { ProcessSection } from "./ProcessSection"
import { DoctorsSection } from "./DoctorsSection"
import { ReviewsSection } from "./ReviewsSection"
import { HospitalsSection } from "./HospitalsSection"
import { CertificationsSection } from "./CertificationsSection"
import { FAQSection } from "./FAQSection"
import { BlogSection } from "./BlogSection"
import { FinalCTASection } from "./FinalCTASection"
import { LanguageTabs, type Language } from "../shared/LanguageTabs"
import { HOME_PAGE_LOCALE_CODES } from "@/lib/pages/home/locales"
import {
  createEmptyHomePageFormState,
  type HomePageFormStateShape,
} from "@/lib/pages/home/form-types"
import {
  CmsPagePendingProvider,
  useCmsPagePendingRef,
} from "@/components/dashboard/cms-pages/CmsPagePendingContext"
import {
  clearAllCmsPending,
  commitPendingHomePageLocales,
  cmsPendingHasAny,
} from "@/lib/media-manager/cms-page-pending"
import { getPersistedMediaValidationError } from "@/lib/media-manager/validate-persisted-payload"

// ─── State shape ──────────────────────────────────────────────────────────────

type HomePageFormState = HomePageFormStateShape

// ─── 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 ────────────────────────────────────────────────────────────────

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

  return (
    <CmsPagePendingProvider activeLanguage={activeLanguage}>
      <HomePageFormInner
        activeLanguage={activeLanguage}
        setActiveLanguage={setActiveLanguage}
        formByLanguage={formByLanguage}
        setFormByLanguage={setFormByLanguage}
        loading={loading}
        setLoading={setLoading}
        loadError={loadError}
        setLoadError={setLoadError}
        saving={saving}
        setSaving={setSaving}
        savingSectionKey={savingSectionKey}
        setSavingSectionKey={setSavingSectionKey}
        sectionFeedback={sectionFeedback}
        setSectionFeedback={setSectionFeedback}
        sectionFeedbackTimersRef={sectionFeedbackTimersRef}
        isLockedForEditing={isLockedForEditing}
        setIsLockedForEditing={setIsLockedForEditing}
        saveSuccess={saveSuccess}
        setSaveSuccess={setSaveSuccess}
        saveError={saveError}
        setSaveError={setSaveError}
        isFormLocked={isFormLocked}
      />
    </CmsPagePendingProvider>
  )
}

type HomePageFormInnerProps = {
  activeLanguage: Language
  setActiveLanguage: (lang: Language) => void
  formByLanguage: Record<Language, HomePageFormState>
  setFormByLanguage: React.Dispatch<React.SetStateAction<Record<Language, HomePageFormState>>>
  loading: boolean
  setLoading: (v: boolean) => void
  loadError: string | null
  setLoadError: (v: string | null) => void
  saving: boolean
  setSaving: (v: boolean) => void
  savingSectionKey: keyof HomePageFormState | null
  setSavingSectionKey: (v: keyof HomePageFormState | null) => void
  sectionFeedback: Partial<Record<keyof HomePageFormState, { type: "success" | "error"; message: string }>>
  setSectionFeedback: React.Dispatch<
    React.SetStateAction<Partial<Record<keyof HomePageFormState, { type: "success" | "error"; message: string }>>>
  >
  sectionFeedbackTimersRef: React.RefObject<
    Partial<Record<keyof HomePageFormState, ReturnType<typeof setTimeout>>>
  >
  isLockedForEditing: boolean
  setIsLockedForEditing: (v: boolean) => void
  saveSuccess: string | null
  setSaveSuccess: (v: string | null) => void
  saveError: string | null
  setSaveError: (v: string | null) => void
  isFormLocked: boolean
}

function HomePageFormInner({
  activeLanguage,
  setActiveLanguage,
  formByLanguage,
  setFormByLanguage,
  loading,
  setLoading,
  loadError,
  setLoadError,
  saving,
  setSaving,
  savingSectionKey,
  setSavingSectionKey,
  sectionFeedback,
  setSectionFeedback,
  sectionFeedbackTimersRef,
  isLockedForEditing,
  setIsLockedForEditing,
  saveSuccess,
  setSaveSuccess,
  saveError,
  setSaveError,
  isFormLocked,
}: HomePageFormInnerProps) {
  const pendingImages = useCmsPagePendingRef()

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

  async function commitPendingImagesIfAny(): Promise<Record<Language, HomePageFormState>> {
    if (!cmsPendingHasAny(pendingImages)) return formByLanguage
    const merged = await commitPendingHomePageLocales(formByLanguage, pendingImages)
    setFormByLanguage(merged)
    const mediaError = getPersistedMediaValidationError({ locales: merged })
    if (mediaError) throw new Error(mediaError)
    return merged
  }

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

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch("/api/admin/home-page", { credentials: "include" })
        const data: {
          success?: boolean
          error?: string
          locales?: Partial<Record<Language, HomePageFormState>>
        } = await res.json()
        if (cancelled) return
        if (!res.ok || !data.success) {
          setLoadError(data.error ?? "Failed to load home page.")
          return
        }
        setFormByLanguage((prev) => {
          const next = { ...prev }
          for (const code of HOME_PAGE_LOCALE_CODES) {
            const chunk = data.locales?.[code]
            if (chunk?.hero) next[code] = chunk
          }
          return next
        })
      } catch {
        if (!cancelled) setLoadError("Failed to load home 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)
      }
    }
  }, [])

  function showSectionFeedback(
    sectionKey: keyof HomePageFormState,
    type: "success" | "error",
    message: string
  ) {
    const existingTimer = sectionFeedbackTimersRef.current[sectionKey]
    if (existingTimer) clearTimeout(existingTimer)
    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)
  }

  async function handleSave() {
    setSaving(true)
    setSaveSuccess(null)
    setSaveError(null)

    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/home-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")

      // Confirm full-page persistence by reloading fresh values from DB.
      const refreshRes = await fetch("/api/admin/home-page", { credentials: "include" })
      const refreshData: {
        success?: boolean
        error?: string
        locales?: Partial<Record<Language, HomePageFormState>>
      } = await refreshRes.json()
      if (!refreshRes.ok || !refreshData.success) {
        throw new Error(refreshData.error ?? "Page saved, but failed to refresh latest data.")
      }
      setFormByLanguage((prev) => {
        const next = { ...prev }
        for (const code of HOME_PAGE_LOCALE_CODES) {
          const chunk = refreshData.locales?.[code]
          if (chunk?.hero) next[code] = chunk
        }
        return next
      })

      setSaveSuccess("Home Page saved successfully.")
      setIsLockedForEditing(true)
    } catch (error) {
      setActiveLanguage("en")
      setSaveError(error instanceof Error ? error.message : "Something went wrong. Please try again.")
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveSection(sectionKey: keyof HomePageFormState) {
    setSavingSectionKey(sectionKey)
    setSaveSuccess(null)
    setSaveError(null)

    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/home-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")

      // Confirm persistence by reloading fresh values from DB immediately.
      const refreshRes = await fetch("/api/admin/home-page", { credentials: "include" })
      const refreshData: {
        success?: boolean
        error?: string
        locales?: Partial<Record<Language, HomePageFormState>>
      } = await refreshRes.json()
      if (!refreshRes.ok || !refreshData.success) {
        throw new Error(refreshData.error ?? "Section saved, but failed to refresh latest data.")
      }
      setFormByLanguage((prev) => {
        const next = { ...prev }
        for (const code of HOME_PAGE_LOCALE_CODES) {
          const chunk = refreshData.locales?.[code]
          if (chunk?.hero) next[code] = chunk
        }
        return next
      })
      setSaveSuccess(`${String(sectionKey)} section saved successfully.`)
      showSectionFeedback(sectionKey, "success", "Section saved successfully.")
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Something went wrong. Please try again."
      setActiveLanguage("en")
      setSaveError(errorMessage)
      showSectionFeedback(sectionKey, "error", errorMessage)
    } finally {
      setSavingSectionKey(null)
    }
  }

  function renderSectionSaveButton(sectionKey: keyof HomePageFormState) {
    const isSavingThisSection = 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)" }}
        >
          {isSavingThisSection ? (
            <>
              <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">
      {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={(language) => {
              if (isFormLocked) return
              setActiveLanguage(language)
            }}
            disabled={isFormLocked}
          />
        </div>
      </div>

      {/* 1 — Hero */}
      <Section id="hp-hero" icon={<Sparkles className="w-4 h-4" />} title="Hero Section" description="Main headline, description, and primary call-to-action button" accent="navy" footer={renderSectionSaveButton("hero")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><HeroSection value={form.hero} onChange={(v) => updateSection("hero", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 2 — Stats */}
      <Section id="hp-stats" icon={<BarChart3 className="w-4 h-4" />} title="Stats Section" description="Key numbers and metrics displayed below the hero" accent="green" footer={renderSectionSaveButton("stats")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><StatsSection value={form.stats} onChange={(v) => updateSection("stats", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 3 — Services */}
      <Section id="hp-services" icon={<LayoutGrid className="w-4 h-4" />} title="Services Section" description="Service categories, service detail cards, and CTA button" accent="navy" footer={renderSectionSaveButton("services")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><ServicesSection value={form.services} onChange={(v) => updateSection("services", v)} showValidation={activeLanguage === "en"} defaultSharedData={formByLanguage.en.services} isDefaultLanguage={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 4 — Why Choose Us */}
      <Section id="hp-why" icon={<ShieldCheck className="w-4 h-4" />} title="Why Choose Us Section" description="Title and feature cards with icons and descriptions" accent="green" footer={renderSectionSaveButton("whyChooseUs")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><WhyChooseUsSection value={form.whyChooseUs} onChange={(v) => updateSection("whyChooseUs", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 5 — Testimonials */}
      <Section id="hp-testimonials" icon={<Play className="w-4 h-4" />} title="Testimonials Section" description="Video testimonials with patient name, treatment, and image" accent="navy" footer={renderSectionSaveButton("testimonials")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><TestimonialsSection value={form.testimonials} onChange={(v) => updateSection("testimonials", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 6 — Process */}
      <Section id="hp-process" icon={<GitBranch className="w-4 h-4" />} title="Process Section (Steps)" description="Step-by-step treatment process with images and overlay details" accent="green" footer={renderSectionSaveButton("process")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><ProcessSection value={form.process} onChange={(v) => updateSection("process", v)} showValidation={activeLanguage === "en"} defaultSharedData={formByLanguage.en.process} isDefaultLanguage={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 7 — Doctors */}
      <Section id="hp-doctors" icon={<UserRound className="w-4 h-4" />} title="Doctors Section" description="Section title, subtitle, and link to the full doctors listing" accent="navy" footer={renderSectionSaveButton("doctors")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><DoctorsSection value={form.doctors} onChange={(v) => updateSection("doctors", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 8 — Reviews */}
      <Section id="hp-reviews" icon={<Star className="w-4 h-4" />} title="Reviews Section" description="Written patient reviews with name, location, and optional avatar" accent="green" footer={renderSectionSaveButton("reviews")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><ReviewsSection value={form.reviews} onChange={(v) => updateSection("reviews", v)} showValidation={activeLanguage === "en"} defaultSharedData={formByLanguage.en.reviews} isDefaultLanguage={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 9 — Hospitals */}
      <Section id="hp-hospitals" icon={<Building2 className="w-4 h-4" />} title="Hospitals Section" description="Partner hospital cards with location, features, and CTA" accent="navy" footer={renderSectionSaveButton("hospitals")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><HospitalsSection value={form.hospitals} onChange={(v) => updateSection("hospitals", v)} showValidation={activeLanguage === "en"} defaultSharedData={formByLanguage.en.hospitals} isDefaultLanguage={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 10 — Certifications */}
      <Section id="hp-certifications" icon={<Award className="w-4 h-4" />} title="Certifications Section" description="Accreditations and certifications with issuer, year, and status" accent="green" footer={renderSectionSaveButton("certifications")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><CertificationsSection value={form.certifications} onChange={(v) => updateSection("certifications", v)} showValidation={activeLanguage === "en"} defaultSharedData={formByLanguage.en.certifications} isDefaultLanguage={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 11 — FAQ */}
      <Section id="hp-faq" icon={<HelpCircle className="w-4 h-4" />} title="FAQ Section" description="Frequently asked questions organized by category" accent="navy" footer={renderSectionSaveButton("faq")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><FAQSection value={form.faq} onChange={(v) => updateSection("faq", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 12 — Blog */}
      <Section id="hp-blog" icon={<Newspaper className="w-4 h-4" />} title="Blog Section" description="Eyebrow, title, and subtitle for the blog preview on the homepage" accent="green" footer={renderSectionSaveButton("blog")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><BlogSection value={form.blog} onChange={(v) => updateSection("blog", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </Section>

      {/* 13 — Final CTA */}
      <Section id="hp-final-cta" icon={<Megaphone className="w-4 h-4" />} title="Final CTA Section" description="Closing call-to-action with eyebrow, title, description, buttons, and trust badges" accent="navy" footer={renderSectionSaveButton("finalCTA")}>
        {loading ? <p className="text-sm text-muted-foreground font-sans">Loading...</p> : <fieldset disabled={isFormLocked} className="min-w-0"><FinalCTASection value={form.finalCTA} onChange={(v) => updateSection("finalCTA", v)} showValidation={activeLanguage === "en"} /></fieldset>}
      </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>
      )}

      {/* 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>
  )
}
