/**
 * Green Energy page data layer.
 *
 * Mirrors the homepage pattern: bundled defaults are always available,
 * and when Strapi is enabled the single-type content is merged on top.
 */

import { fetchSingle, getMediaUrl } from "@/lib/strapi/client"
import { isStrapiEnabled } from "@/lib/strapi/config"
import { titleCase } from "@/lib/api/casing"
import type {
  GreenEnergyData,
  GreenEnergyStatCardData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults (current hardcoded content)                      */
/* ------------------------------------------------------------------ */

export const greenEnergyDefaults: GreenEnergyData = {
  hero: {
    heading: "Green Energy",
    mobileBackgroundImage: "/assets/green-energy/hero-bg-mobile.jpg",
    desktopBackgroundImage: "/assets/green-energy/hero-bg-desktop.jpg",
  },
  stats: [
    {
      icon: "/assets/green-energy/icon-calendar.svg",
      title: "29th Nov 2024",
      description: "Established to strengthen our commitment to green energy",
    },
    {
      icon: "/assets/green-energy/icon-solar.svg",
      title: "2 MW",
      description: "Solar Power Plant Commissioned Uthamapalayam, Theni District",
    },
    {
      icon: "/assets/green-energy/icon-production.svg",
      title: "3 Million+",
      description: "Annual Renewable Energy Production.",
    },
    {
      icon: "/assets/green-energy/icon-renewable.svg",
      title: "100%",
      description: "Renewable energy improves efficiency and cuts transmission losses.",
    },
    {
      icon: "/assets/green-energy/icon-ccr.svg",
      title: "CCR Program",
      description: "Aligned With it Under the Corporate Climate Responsibility (CCR) Program",
    },
    {
      icon: "/assets/green-energy/icon-goals.svg",
      title: "National Goals",
      description: "Supporting Global Climate Action Frameworks",
    },
  ],
  about: {
    badge: "about Green Energy",
    badgeIcon: "/assets/green-energy/about-badge.svg",
    mobileWatermarkText: "About SAFL",
    desktopWatermarkText: "About us",
    decorativeImage: "/assets/green-energy/decorative-1.svg",
    paragraphs: [
      `Vital Green Energy Pvt. Ltd. has taken a significant step in its commitment to environmental sustainability with the commissioning of a solar power plant in Uthamapalayam, Theni District. Operational since 29 November 2024, this milestone initiative forms a key part of the company's Corporate Climate Responsibility (CCR) program, reinforcing its mission to reduce carbon emissions and promote the adoption of renewable energy.`,
      `The initiative focuses on reducing greenhouse gas emissions, promoting sustainable practices, and investing in clean energy technologies for a safer and greener future. As part of its renewable energy efforts, the company generates clean power through its solar plant for captive consumption, which is utilized to operate its amusement park in Chennai.`,
      `The solar facility generates approximately 3 million (30 lakh) units of clean electricity annually, significantly reducing dependence on conventional energy sources. This self-sustaining power system not only minimizes environmental impact but also strengthens the company's long-term focus on energy efficiency and sustainable operations. By supplying renewable energy for captive use at MGM Diamond Beach Resorts Pvt. Ltd., the initiative ensures lower transmission losses while improving energy reliability and cost efficiency.`,
      `This project reflects MGM's philosophy of integrating sustainability into its core business operations rather than treating it as a separate function. Aligned with India's national renewable energy goals and global climate action frameworks, it highlights MGM's proactive role in environmental stewardship. The initiative stands as a model for the hospitality and leisure industry, demonstrating how responsible corporate action can align business growth with ecological responsibility to build a cleaner and more sustainable future.`,
    ],
  },
}

/* ------------------------------------------------------------------ */
/*  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 getGreenEnergyData(): Promise<GreenEnergyData> {
  const d = greenEnergyDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("green-energy")

  if (!entry) return d

  const hero = (entry.hero as AnyRec | undefined) ?? {}
  const statsWrapper = (entry.stats as AnyRec | undefined) ?? {}
  const about = (entry.about as AnyRec | undefined) ?? {}
  const statRows = (statsWrapper.stats as AnyRec[] | undefined) ?? []
  const paragraphRows = (about.paragraphs as AnyRec[] | undefined) ?? []

  return {
    hero: {
      heading: str(hero.heading),
      mobileBackgroundImage: media(hero.mobileBackgroundImage_9x16),
      desktopBackgroundImage: media(hero.desktopBackgroundImage_16x9),
    },
    stats: statRows.map((row) => ({
      icon: media(row.icon_1x1) || str(row.iconUrl),
      title: str(row.title),
      description: str(row.description),
    })),
    about: {
      badge: str(about.badge),
      badgeIcon: d.about.badgeIcon,
      mobileWatermarkText: titleCase(str(about.mobileWatermarkText)),
      desktopWatermarkText: titleCase(str(about.desktopWatermarkText)),
      decorativeImage: d.about.decorativeImage,
      paragraphs: paragraphRows.map((row) => str(row.text)),
    },
  }
}
