/**
 * About Us page data layer.
 *
 * Same pattern as other pages: bundled defaults with
 * Strapi merge-over-defaults when enabled.
 *
 * Timeline defaults are sourced from the existing data file;
 * philanthropic & testimonials defaults reuse homepage defaults.
 */

import { fetchSingle, getMediaUrl } from "@/lib/strapi/client"
import { isStrapiEnabled } from "@/lib/strapi/config"
import { titleCase } from "@/lib/api/casing"
import { timelineYears } from "@/data/timelineSlides"
import { homepageDefaults } from "@/lib/api/defaults"
import type {
  AboutCharitableTrustData,
  AboutCompanyData,
  AboutData,
  AboutFounderData,
  AboutFounderSlideData,
  AboutGalleryData,
  AboutGalleryImageData,
  AboutGoldenRuleData,
  AboutGoldenRulesData,
  AboutPastVentureData,
  AboutPastVenturesData,
  AboutPhilanthropicActivityData,
  AboutPhilanthropicData,
  AboutTestimonialData,
  AboutTestimonialsData,
  AboutTimelineData,
  AboutTimelineYearData,
  AboutVisionaryBeginningsData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults                                                   */
/* ------------------------------------------------------------------ */

export const aboutDefaults: AboutData = {
  founder: {
    slides: [
      {
        badge: "About the founder",
        badgeIcon: "/assets/leaders/sparkle-icon.svg",
        bio: [
          "Chevalier Dr. Manuel Gnana Muthu (MGM) was born on 2nd April 1935 in Tirunelveli, TamilNadu, as the second son of Mr.Manuel and Mrs.Rajalakshmi. He began his career at the Chennai Port in 1957 and later founded the MGM Group of Companies, which started with logistics and hospitality and grew into areas like Coal and Mineral Mining, Food Chains, International Trading, Housing, Distilleries, IMFS, and the famous MGM Dizzee World theme park in Chennai.",
          "Known for his business skills and commitment to social causes, Dr. Muthu has worked to support the underprivileged and shared his journey in his autobiography, \"Rags to Riches: Chevalier Seva Ratna Dr. M. G. Muthu\" (1999). He was also honored with the Chevalier Virudhu Award.",
        ],
        watermark: "About The Founder",
        image: "/assets/home/our leader/MG Muthu Founder Profile.webp",
        quote: "\"Truth, Hard work, Simplicity, Honesty and Faith\" - These are the five golden tenets which the Founder - Chairman of the Group followed strictly. The Five Golden Mantras are the five Towers of the Group's victory.",
        quoteAttribution: "- An excerpt from his autobiography",
      },
      {
        badge: "About Vice Chairman",
        badgeIcon: "/assets/leaders/sparkle-icon.svg",
        bio: [
          "Mr. MGM Maran, also known as Nesamani Maran Muthu, is the Vice Chairman of the MGM Group of Companies, a leading conglomerate based in Chennai. Known for his strategic insight and progressive leadership, he has played a key role in expanding the Group's presence across multiple industries. With a strong foundation in values such as integrity, innovation, and social responsibility, he continues to strengthen the organization's legacy. Mr. Maran is recognized for his people-centric approach and commitment to sustainable growth. His leadership continues to guide the MGM Group toward long-term success on both national and global platforms.",
        ],
        watermark: "Vision For The Future",
        image: "/assets/mgm-maran-new.png",
        quote: "\"The foundation we build today will determine the heights we reach tomorrow. Let every brick be laid with honesty and every pillar stand on truth.\"",
        quoteAttribution: "- Mr. MGM Maran",
      },
      {
        badge: "About Group Managing Director",
        badgeIcon: "/assets/leaders/sparkle-icon.svg",
        bio: [
          "Mr. MGM Anand Muthu is a prominent Indian business leader and the Managing Director of the MGM Group of Companies, headquartered in Chennai. With over two decades of experience, he has been instrumental in expanding the group's presence across South India while upholding its strong legacy. As the son of visionary founder Dr. M.G. Muthu, he continues to build on values of integrity, discipline, and innovation. Under his leadership, the group has diversified into hospitality, entertainment, logistics, and manufacturing. Anand Muthu is known for his strategic vision, operational expertise, and commitment to sustainable growth and long-term business excellence.",
        ],
        watermark: "Legacy Of Excellence",
        image: "/assets/home/our leader/MGM Anand Profile.webp",
        quote: "\"A work of real merit finds success at last, as we have found. Nothing succeeds like success…\"",
        quoteAttribution: "- Mr. MGM Anand Muthu",
      },
    ],
  },
  visionaryBeginnings: {
    heading: "From visionary beginnings to industry leadership",
    description:
      "Built on a legacy of integrity and enterprise, MGM Group has grown into a diversified conglomerate, shaping industries across logistics, hospitality, entertainment, manufacturing, and global trade.",
    bannerImage: "/assets/about/One version.jpg",
    mobileBannerImage: "https://mgmindia.s3.ap-south-1.amazonaws.com/uploads/One_vision_345aeb9765.webp",
  },
  aboutCompany: {
    badge: "About COMPANY",
    badgeIcon: "/assets/about/sparkle-icon.svg",
    description:
      "MGM Group is a diversified enterprise built on decades of trust, integrity, and operational excellence. Since its inception in 1963, the Group has expanded across logistics, hospitality, entertainment, manufacturing, and global trade, creating lasting value for businesses, communities, and stakeholders.",
    image: "https://mgmindia.s3.ap-south-1.amazonaws.com/uploads/large_MGM_Centre_Entrance_jpg_1_e47b881e5c.jpeg",
  },
  goldenRules: {
    badge: "Our Golden Rule",
    badgeIcon: "/assets/about/golden-badge-icon.svg",
    description:
      "The values that guide our decisions, shape our journey, and continue to drive our success.",
    cards: [
      { num: "01", title: "Hard Work", description: "Commitment and perseverance in everything we do", icon: "/assets/about/icon-hardwork.svg" },
      { num: "02", title: "Character", description: "Strong values and a foundation of integrity", icon: "/assets/about/icon-character.svg" },
      { num: "03", title: "Integrity", description: "Honesty and ethical conduct in all interactions", icon: "/assets/about/icon-integrity.svg" },
      { num: "04", title: "Truth", description: "Transparency and sincerity in our actions", icon: "/assets/about/icon-truth.svg" },
      { num: "05", title: "Hope", description: "A positive outlook and belief in a better future", icon: "/assets/about/icon-hope.svg" },
    ],
  },
  timeline: {
    badge: "Timeline",
    badgeIcon: "/assets/about/timeline-badge-icon.svg",
    backgroundImage: "/assets/about/timeline-bg.png",
    years: timelineYears.map((y) => ({
      year: y.year,
      slides: y.slides.map((s) => ({ image: s.image, body: s.body })),
    })),
  },
  gallery: {
    badge: "Gallery",
    badgeIcon: "/assets/leaders/sparkle-icon.svg",
    description:
      "Our gallery reflects the evolution of our craft, the people behind it, and the passion that continues to shape our story.",
    images: [
      { src: "/assets/about/gallery/(174).jpg", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/(7).jpg", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/cash purse was presented to Mother Teresa when she visited Chennai.jpeg", aspect: "aspect-[3/2]" },
      { src: "/assets/about/gallery/DSC_0588.JPG", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/DSC_0623.JPG", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/MGM Muthu in  traditional Chevalier Robes .jpeg", aspect: "aspect-[3/4]" },
      { src: "/assets/about/gallery/MGM Muthu Receiving the National Integration Award from the Former President R. Venkataraman.jpeg", aspect: "aspect-[3/2]" },
      { src: "/assets/about/gallery/MGM Muthu sir With Suoerstar Sarathkumar.jpeg", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/MGM Muthu sir with Superstar Rajinikanth .jpeg", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/MGM Muthu with Former Indian Cricket Captain Kapil Dev, who visited the MGM Dizzee World.jpg", aspect: "aspect-[4/3]" },
      { src: "/assets/about/gallery/MGM Muthu with outstanding actor Kamalhassan at my office..jpeg", aspect: "aspect-square" },
      { src: "/assets/about/gallery/Roller coater opening .JPG", aspect: "aspect-[3/4]" },
      { src: "/assets/about/gallery/Thiru R. Venkataraman at the Computer Car in MGM Dizzee World (1).jpeg", aspect: "aspect-[4/3]" },
    ],
  },
  pastVentures: {
    badge: "Past Ventures",
    badgeIcon: "/assets/leaders/sparkle-icon.svg",
    description: "Pioneering initiatives that shaped our diversified portfolio",
    ventures: [
      {
        name: "Marrybrown",
        description: "Marrybrown, a popular Malaysian QSR known for fried chicken and fusion meals, entered India in 1999 and has expanded to over 50 outlets across Tamil Nadu in 15 years.",
        image: "/assets/portfolio/Marrybrown .png",
        logo: "/assets/244717.svg",
      },
      {
        name: "MGM Anand Transport",
        description: "MGM Anand Transport began in 1982 and grew into a private company by 2011, expanding into multi-modal logistics across India's major ports.",
        image: "/assets/portfolio/Anand Transport.JPG",
        logo: "/assets/portfolio/anand-transport-new-logo.png",
      },
      {
        name: "MGM Housing & Real Estates",
        description: "MGM Housing & Real Estates Pvt. Ltd., established in 1988, marked the MGM Group's entry into real estate, focusing on land development and residential projects, expanding across key locations.",
        image: "https://mgmindia.s3.ap-south-1.amazonaws.com/uploads/MGM_Housing_and_Realestate_91b7f359ca.png",
        logo: "https://mgmindia.s3.ap-south-1.amazonaws.com/uploads/MGM_Housing_and_Real_Estates_01_0b1d715473.png",
      },
      {
        name: "MGM Tyre Centre",
        description: "MGM Tyre Centre started in 1989 in T. Nagar, offering quality tyres and services, and became a trusted name before closing in 2012.",
        image: "/assets/portfolio/MGM Tyre Centre.png",
        logo: "/assets/past ventures/MGM Tyre Center-01.png",
      },
      {
        name: "MGM International Imports and Exports",
        description: "Leading global trade operations that connect markets worldwide, driven by quality, trust, and strong international partnerships.",
        image: "/assets/portfolio/MGM International Imports & Exports Port.jpg",
        logo: "/assets/past ventures/mgm-imports-exports-logo-new.jpeg",
      },
      {
        name: "MGM Selvee World",
        description: "A landmark entertainment venture that delights families and reflects MGM Group's dedication to creating memorable experiences.",
        image: "/assets/portfolio/MGM Selvee World.png",
        logo: "/assets/portfolio/selvee-logo-new.jpeg",
      },
      {
        name: "FUN World",
        description: "Birthday celebrations, coin-operated machines. Mayaajal, Esphani Centre, Luz Corner, Abirami Hall.",
        image: "/assets/portfolio/Fun world.jpg",
        logo: "/assets/past ventures/Mgm Fun world Logo-01.png",
      },
    ],
  },
  charitableTrust: {
    badge: "Group Sponsorship",
    badgeIcon: "/assets/about/golden-badge-icon.svg",
    description:
      "Giving back to society through meaningful initiatives Chevalier Dr. MG Muthu was a generous philanthropist who established the MGM Charitable Trust to serve society.",
    watermarkText: "MGM Charitable Trust",
    aidIntroText: "Through this trust, the group has been providing aid to:",
    aidBulletIcon: "/assets/about/badge-star-dark.svg",
    aidItems: [
      "Old age home support in Kovalam since 1995",
      "Educational aid to poor students since inception",
      "Feeding programs for orphanages",
      "Various charitable activities",
      "Food & clothes distribution on Founder's Day",
      "Scholarships, books & student support",
      "Tuticorin flood relief (2023) & medical aid (2024)",
    ],
    slides: [
      "/assets/about/responsibilty/MGM 15L Donation LittleSistersAgedHome Chennai 2015.JPG",
      "/assets/about/responsibilty/MGM_Charity_Greet_2023.jpg.JPG",
      "/assets/about/responsibilty/MGM_Cheque_Donation.JPG",
      "/assets/about/responsibilty/MGM_Charity_TV_Donation_1999.JPG",
      "/assets/about/responsibilty/MGM_Clothes_Distribution.jpg",
      "/assets/about/responsibilty/MGM_EducationSupport.JPG",
      "/assets/about/responsibilty/MGM_StJohnBritto_AgedHome_2005.JPG",
      "/assets/about/responsibilty/MGM_Student_Support.JPG",
      "/assets/about/responsibilty/MGM_FoundersDay_Food.jpg",
    ],
  },
  philanthropic: {
    badge: homepageDefaults.philanthropic.header.badge || "Philanthropic Activities",
    badgeIcon: homepageDefaults.philanthropic.header.badgeIcon || "/assets/leaders/sparkle-icon.svg",
    description: homepageDefaults.philanthropic.header.description || "",
    activities: homepageDefaults.philanthropic.activities.map((a) => ({
      title: a.title,
      highlight: a.highlight,
      description: a.description,
      image: a.image,
    })),
  },
  testimonials: {
    badge: homepageDefaults.testimonials.header.badge || "Testimonials",
    badgeIcon: homepageDefaults.testimonials.header.badgeIcon || "/assets/common/sparkle-vector.svg",
    description: homepageDefaults.testimonials.header.description || "",
    mobileDescription: homepageDefaults.testimonials.mobileDescription || "",
    testimonials: homepageDefaults.testimonials.testimonials.map((t) => ({
      quote: t.quote,
      name: t.name,
      role: t.role,
      avatar: t.avatar,
      rating: t.rating,
    })),
  },
}

/* ------------------------------------------------------------------ */
/*  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 num(val: unknown, fallback = 0): number {
  if (typeof val === "number") return val
  if (typeof val === "string") {
    const n = parseInt(val, 10)
    if (!isNaN(n)) return n
  }
  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 getAboutData(): Promise<AboutData> {
  const d = aboutDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("about")

  if (!entry) return d

  const founder = (entry.founder as AnyRec | undefined) ?? {}
  const visionaryBeginnings = (entry.visionaryBeginnings as AnyRec | undefined) ?? {}
  const aboutCompany = (entry.aboutCompany as AnyRec | undefined) ?? {}
  const goldenRules = (entry.goldenRules as AnyRec | undefined) ?? {}
  const timeline = (entry.timeline as AnyRec | undefined) ?? {}
  const gallery = (entry.gallery as AnyRec | undefined) ?? {}
  const pastVentures = (entry.pastVentures as AnyRec | undefined) ?? {}
  const charitableTrust = (entry.charitableTrust as AnyRec | undefined) ?? {}
  const philanthropic = (entry.philanthropic as AnyRec | undefined) ?? {}
  const testimonials = (entry.testimonials as AnyRec | undefined) ?? {}

  // Nested arrays
  const founderSlideRows = (founder.slides as AnyRec[] | undefined) ?? []
  const goldenRuleRows = (goldenRules.cards as AnyRec[] | undefined) ?? []
  const timelineYearRows = (timeline.years as AnyRec[] | undefined) ?? []
  const galleryImageRows = (gallery.images as AnyRec[] | undefined) ?? []
  const ventureRows = (pastVentures.ventures as AnyRec[] | undefined) ?? []
  const aidItemRows = (charitableTrust.aidItems as AnyRec[] | undefined) ?? []
  const trustSlideRows = (charitableTrust.slides as AnyRec[] | undefined) ?? []
  const activityRows = (philanthropic.activities as AnyRec[] | undefined) ?? []
  const testimonialRows = (testimonials.testimonials as AnyRec[] | undefined) ?? []

  return {
    founder: {
      slides: withFallback(
        founderSlideRows.map((row, i) => {
          const fb = d.founder.slides[i] ?? d.founder.slides[0]
          return {
            badge: str(row.badge, fb?.badge || ""),
            badgeIcon: d.founder.slides[0].badgeIcon,
            bio: withFallback(
              ((row.bio as AnyRec[] | undefined) ?? []).map((p) => str(p.text)),
              fb?.bio || [],
            ),
            watermark: titleCase(str(row.watermark, fb?.watermark || "")),
            image: media(row.image_8x9) || fb?.image || "",
            quote: str(row.quote, fb?.quote || ""),
            quoteAttribution: str(row.quoteAttribution, fb?.quoteAttribution || ""),
          }
        }),
        d.founder.slides,
      ),
    },
    visionaryBeginnings: {
      heading: str(visionaryBeginnings.heading, d.visionaryBeginnings.heading),
      description: str(visionaryBeginnings.description, d.visionaryBeginnings.description),
      bannerImage: media(visionaryBeginnings.bannerImage_3x1) || d.visionaryBeginnings.bannerImage,
      mobileBannerImage: media(visionaryBeginnings.mobileBannerImage_1x1) || d.visionaryBeginnings.mobileBannerImage,
    },
    aboutCompany: {
      badge: str(aboutCompany.badge, d.aboutCompany.badge),
      badgeIcon: d.aboutCompany.badgeIcon,
      description: str(aboutCompany.description, d.aboutCompany.description),
      image: media(aboutCompany.image_1x1) || d.aboutCompany.image,
    },
    goldenRules: {
      badge: str(goldenRules.badge, d.goldenRules.badge),
      badgeIcon: d.goldenRules.badgeIcon,
      description: str(goldenRules.description, d.goldenRules.description),
      cards: withFallback(
        goldenRuleRows.map((row, i) => {
          const fb = d.goldenRules.cards[i] ?? d.goldenRules.cards[0]
          return {
            num: str(row.num, fb?.num || ""),
            title: str(row.title, fb?.title || ""),
            description: str(row.description, fb?.description || ""),
            icon: media(row.icon_1x1) || fb?.icon || "",
          }
        }),
        d.goldenRules.cards,
      ),
    },
    timeline: {
      badge: str(timeline.badge, d.timeline.badge),
      badgeIcon: d.timeline.badgeIcon,
      backgroundImage: media(timeline.backgroundImage_3x2) || d.timeline.backgroundImage,
      years: withFallback(
        timelineYearRows.map((row) => {
          const year = str(row.year)
          const fbYear = d.timeline.years.find((item) => item.year === year)
          return {
            year,
            slides: withFallback(
              ((row.slides as AnyRec[] | undefined) ?? []).map((s, i) => {
                const fb = fbYear?.slides[i]
                return {
                  image: media(s.image_16x9) || fb?.image || "",
                  body: str(s.body, fb?.body || ""),
                }
              }).filter((slide) => slide.image),
              fbYear?.slides || [],
            ),
          }
        }).filter((year) => year.slides.length > 0),
        d.timeline.years,
      ),
    },
    gallery: {
      badge: str(gallery.badge, d.gallery.badge),
      badgeIcon: d.gallery.badgeIcon,
      description: str(gallery.description, d.gallery.description),
      images: withFallback(
        galleryImageRows.map((row) => ({
          src: media(row.src_3x2),
          aspect: str(row.aspect),
        })).filter((image) => image.src),
        d.gallery.images,
      ),
    },
    pastVentures: {
      badge: str(pastVentures.badge, d.pastVentures.badge),
      badgeIcon: d.pastVentures.badgeIcon,
      description: str(pastVentures.description, d.pastVentures.description),
      ventures: withFallback(
        ventureRows.map((row, i) => {
          const fb = d.pastVentures.ventures[i] ?? d.pastVentures.ventures[0]
          return {
            name: str(row.name, fb?.name || ""),
            description: str(row.description, fb?.description || ""),
            image: media(row.image_3x2) || fb?.image || "",
            logo: media(row.logo_1x1) || fb?.logo || "",
          }
        }),
        d.pastVentures.ventures,
      ),
    },
    charitableTrust: {
      badge: str(charitableTrust.badge, d.charitableTrust.badge),
      badgeIcon: d.charitableTrust.badgeIcon,
      description: str(charitableTrust.description, d.charitableTrust.description),
      watermarkText: titleCase(str(charitableTrust.watermarkText, d.charitableTrust.watermarkText)),
      aidIntroText: str(charitableTrust.aidIntroText, d.charitableTrust.aidIntroText),
      aidBulletIcon: media(charitableTrust.aidBulletIcon_1x1) || d.charitableTrust.aidBulletIcon,
      aidItems: withFallback(
        aidItemRows.map((row) => str(row.text)),
        d.charitableTrust.aidItems,
      ),
      slides: withFallback(
        trustSlideRows.map((row) => media(row.image_16x10)).filter(Boolean),
        d.charitableTrust.slides,
      ),
    },
    philanthropic: {
      badge: str(philanthropic.badge, d.philanthropic.badge),
      badgeIcon: d.philanthropic.badgeIcon,
      description: str(philanthropic.description, d.philanthropic.description),
      activities: withFallback(
        activityRows.map((row, i) => {
          const fb = d.philanthropic.activities[i] ?? d.philanthropic.activities[0]
          return {
            title: str(row.title, fb?.title || ""),
            highlight: str(row.highlight, fb?.highlight || ""),
            description: str(row.description, fb?.description || ""),
            image: media(row.image_5x3) || fb?.image || "",
          }
        }),
        d.philanthropic.activities,
      ),
    },
    testimonials: {
      badge: str(testimonials.badge, d.testimonials.badge),
      badgeIcon: d.testimonials.badgeIcon,
      description: str(testimonials.description, d.testimonials.description),
      mobileDescription: str(testimonials.mobileDescription, d.testimonials.mobileDescription),
      testimonials: withFallback(
        testimonialRows.map((row, i) => {
          const fb = d.testimonials.testimonials[i] ?? d.testimonials.testimonials[0]
          return {
            quote: str(row.quote, fb?.quote || ""),
            name: str(row.name, fb?.name || ""),
            role: str(row.role, fb?.role || ""),
            avatar: media(row.avatar_1x1) || fb?.avatar || "",
            rating: num(row.rating, fb?.rating || 5),
          }
        }),
        d.testimonials.testimonials,
      ),
    },
  }
}
