/**
 * Contact page data layer.
 *
 * Same pattern as homepage & green-energy: bundled defaults with
 * Strapi merge-over-defaults when enabled.
 */

import { fetchSingle, getMediaUrl } from "@/lib/strapi/client"
import { isStrapiEnabled } from "@/lib/strapi/config"
import { titleCase } from "@/lib/api/casing"
import { normalizeCmsLink } from "@/lib/api/links"
import type {
  ContactData,
  ContactInfoItemData,
  DepartmentCardData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults                                                   */
/* ------------------------------------------------------------------ */

export const contactDefaults: ContactData = {
  hero: {
    heading: "Contact Us",
    description: "We'd love to hear from you. Contact us for inquiries, partnerships, or any assistance.",
    mobileImage: "/assets/contact/hero-bg-mobile.png",
    desktopImage: "/assets/contact/desktop-contact-banner.jpeg",
  },
  getInTouch: {
    watermarkText: "Get In Touch",
    description: "Have questions about our services or want to explore partnership opportunities? Our team is here to assist.",
    items: [
      {
        icon: "/assets/contact/icon-location.svg",
        label: "Head Office",
        value: "MGM Group of Companies. Chennai, Tamil Nadu. India",
        href: "",
      },
      {
        icon: "/assets/contact/icon-phone.svg",
        label: "Phone",
        value: "+91 (888) 888-8888",
        href: "tel:+918888888888",
      },
      {
        icon: "/assets/contact/icon-email.svg",
        label: "Email",
        value: "info@mgmgroup.com",
        href: "mailto:info@mgmgroup.com",
      },
    ],
  },
  contactForm: {
    heading: "Send Us a Message",
    mobileDescription: "Get the latest updates delivered directly to your inbox every month",
    bgVector: "/assets/contact/form-bg-vector.svg",
    overlayVector: "/assets/contact/vector.png",
    fullNamePlaceholder: "Full Name",
    emailPlaceholder: "Email ID",
    subjectPlaceholder: "Subject",
    messagePlaceholder: "Your message...",
    ctaLabel: "Send Message",
    ctaHref: "",
  },
  departments: {
    cards: [
      {
        title: "Partnership Inquiries",
        description: "Explore collaboration opportunities with MGM Group.",
        email: "partnerships@mgmgroup.com",
      },
      {
        title: "Media Relations",
        description: "Press inquiries and media requests only.",
        email: "media@mgmgroup.com",
      },
      {
        title: "Customer Support",
        description: "Questions about our products and services.",
        email: "support@mgmgroup.com",
      },
    ],
  },
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                           */
/* ------------------------------------------------------------------ */

type AnyRec = Record<string, unknown>

function str(val: unknown, fallback = ""): string {
  if (typeof val === "string") return val.trim() !== "" ? val : fallback
  if (typeof val === "number") return String(val)
  return fallback
}

function media(val: unknown): string {
  return getMediaUrl(val as StrapiMedia | null | undefined)
}

function withFallback<T>(value: T[] | undefined | null, fallback: T[]): T[] {
  return value && value.length > 0 ? value : fallback
}

/* ------------------------------------------------------------------ */
/*  Public API                                                        */
/* ------------------------------------------------------------------ */

export async function getContactData(): Promise<ContactData> {
  const d = contactDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("contact")

  if (!entry) return d

  const hero = (entry.hero as AnyRec | undefined) ?? {}
  const getInTouch = (entry.getInTouch as AnyRec | undefined) ?? {}
  const contactForm = (entry.contactForm as AnyRec | undefined) ?? {}
  const departments = (entry.departments as AnyRec | undefined) ?? {}
  const itemRows = (getInTouch.items as AnyRec[] | undefined) ?? []
  const cardRows = (departments.cards as AnyRec[] | undefined) ?? []

  return {
    hero: {
      heading: str(hero.heading, d.hero.heading),
      description: str(hero.description, d.hero.description),
      mobileImage: media(hero.mobileImage_4x3) || d.hero.mobileImage,
      desktopImage: media(hero.desktopImage_3x1) || d.hero.desktopImage,
    },
    getInTouch: {
      watermarkText: titleCase(str(getInTouch.watermarkText, d.getInTouch.watermarkText)),
      description: str(getInTouch.description, d.getInTouch.description),
      items: withFallback(
        itemRows.map((row, i) => {
          const fb = d.getInTouch.items[i] ?? d.getInTouch.items[0]
          return {
            icon: media(row.icon_1x1) || fb?.icon || "",
            label: str(row.label, fb?.label || ""),
            value: str(row.value, fb?.value || ""),
            href: str(row.href, fb?.href || ""),
          }
        }),
        d.getInTouch.items,
      ),
    },
    contactForm: {
      heading: str(contactForm.heading, d.contactForm.heading),
      mobileDescription: str(contactForm.mobileDescription, d.contactForm.mobileDescription),
      bgVector: media(contactForm.bgVector_1x1) || d.contactForm.bgVector,
      overlayVector: media(contactForm.overlayVector_1x1) || d.contactForm.overlayVector,
      fullNamePlaceholder: str(contactForm.fullNamePlaceholder, d.contactForm.fullNamePlaceholder),
      emailPlaceholder: str(contactForm.emailPlaceholder, d.contactForm.emailPlaceholder),
      subjectPlaceholder: str(contactForm.subjectPlaceholder, d.contactForm.subjectPlaceholder),
      messagePlaceholder: str(contactForm.messagePlaceholder, d.contactForm.messagePlaceholder),
      ctaLabel: str(contactForm.ctaButtonText, d.contactForm.ctaLabel),
      ctaHref: normalizeCmsLink(contactForm.ctaButtonLink, d.contactForm.ctaHref),
    },
    departments: {
      cards: withFallback(
        cardRows.map((row, i) => {
          const fb = d.departments.cards[i] ?? d.departments.cards[0]
          return {
            title: str(row.title, fb?.title || ""),
            description: str(row.description, fb?.description || ""),
            email: str(row.email, fb?.email || ""),
          }
        }),
        d.departments.cards,
      ),
    },
  }
}
