/**
 * Logistics page data layer.
 *
 * Same pattern as homepage & safl: 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 type {
  LogisticsData,
  LogisticsStatCardData,
  LogisticsDivisionStatData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults                                                   */
/* ------------------------------------------------------------------ */

export const logisticsDefaults: LogisticsData = {
  hero: {
    mobileImage: "/assets/logistics/hero-bg-mobile.jpg",
    desktopImage: "/assets/logistics/Logistics_Banner.jpg",
    heading: "Logistics",
  },
  stats: {
    cards: [
      { icon: "/assets/logistics/icon-founded.svg", title: "1982", description: "Founded as a Partnership Firm" },
      { icon: "/assets/logistics/icon-pvt-ltd.svg", title: "2011", description: "Became a Private Limited Company" },
      { icon: "/assets/logistics/icon-ports.svg", title: "10+", description: "Major Port Locations Across India" },
      { icon: "/assets/logistics/icon-machinery.svg", title: "1000+", description: " Heavy Machinery & Equipment Operated" },
      { icon: "/assets/logistics/icon-expertise.svg", title: "3+", description: " Decades of Logistics Expertise" },
      { icon: "/assets/logistics/icon-clients.svg", title: "100+", description: "Industrial & Power Sector Clients" },
      { icon: "/assets/logistics/icon-logistics.svg", title: "End-to-End", description: "Integrated Logistics Solutions" },
      { icon: "/assets/logistics/icon-commitment.svg", title: "100%", description: "Commitment to Total Customer Satisfaction" },
    ],
  },
  about: {
    badge: "about Logistics",
    badgeIcon: "/assets/logistics/vector-badge.svg",
    mobileWatermarkText: "About SAFL",
    desktopWatermarkText: "About us",
    decorativeImage: "/assets/logistics/decorative-corner.svg",
    paragraphs: [
      "MGM Anand Transport Pvt. Ltd. commenced its journey on January 4, 1982, as a partnership firm and later transitioned into a Private Limited Company in 2011, growing into a trusted leader in port-based logistics and bulk cargo handling. Starting as a subcontractor transporting coal to the Ennore Thermal Power Station for TANGEDCO, the company steadily expanded its operations and capabilities over the years. Today, with a strong presence across major ports including Chennai, Ennore, Tuticorin, Vizag, Haldia, Kakinada, Paradeep, Mangalore, Cochin, and Goa, it has evolved into a comprehensive multi-modal logistics enterprise. Through integrated transportation solutions across road, rail, and sea, and specialized operations in transport and port logistics, the company delivers seamless end-to-end cargo handling and logistics services to support diverse industrial and infrastructure requirements across India.",
    ],
  },
  companyDetails: {
    badge: "MGM Anand Transport Pvt. Ltd.",
    badgeIcon: "/assets/logistics/vector-badge.svg",
    description: "MGM Anand Transport Pvt. Ltd. has established itself as a trusted leader in port-based logistics and bulk cargo handling, with over four decades of industry expertise. With a strong presence across major ports and integrated transport solutions, the company delivers reliable, large-scale logistics services across India.",
    watermarkText: "Key Port Locations",
    mapImage: "/assets/logistics/mgm-port-map.png",
    companyInfoLabel: "Company Information:",
    companyPoints: [
      "Founded: January 4, 1982",
      "Incorporated as Pvt. Ltd.: 2011",
      "Core Business: Port-based cargo handling and multi-modal logistics",
      "Operational Presence: 10+ key ports across India",
      "Fleet & Workforce Strength: 309+ including tankers, trucks, vans, and operational teams",
      "Equipment Portfolio: 1000+ machinery and equipment including tippers, payloaders, excavators, dozers, forklifts, and cranes",
    ],
    divisionOverviewLabel: "Division Overview:",
    divisionOverview: [
      { value: "40+ Years", label: "Years of Industry Expertise" },
      { value: "309+ Strength", label: "Workforce, Fleet & Vehicles" },
      { value: "1000+ Equipment", label: "Machinery and Operational Assets" },
      { value: "2 Segments", label: "Transport & Port Logistics" },
    ],
  },
}

/* ------------------------------------------------------------------ */
/*  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 getLogisticsData(): Promise<LogisticsData> {
  const d = logisticsDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("logistics")

  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 companyDetails = (entry.companyDetails as AnyRec | undefined) ?? {}
  const cardRows = (statsWrapper.cards as AnyRec[] | undefined) ?? []
  const paragraphRows = (about.paragraphs as AnyRec[] | undefined) ?? []
  const companyPointRows = (companyDetails.companyPoints as AnyRec[] | undefined) ?? []
  const divisionRows = (companyDetails.divisionOverview as AnyRec[] | undefined) ?? []

  return {
    hero: {
      mobileImage: media(hero.mobileImage_9x16),
      desktopImage: media(hero.desktopImage_12x5),
      heading: str(hero.heading),
    },
    stats: {
      cards: cardRows.map((row) => ({
            icon: media(row.icon_1x1),
            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)),
    },
    companyDetails: {
      badge: str(companyDetails.badge),
      badgeIcon: d.companyDetails.badgeIcon,
      description: str(companyDetails.description),
      watermarkText: titleCase(str(companyDetails.watermarkText)),
      mapImage: media(companyDetails.mapImage_1x1),
      companyInfoLabel: str(companyDetails.companyInfoLabel),
      companyPoints: withFallback(
        companyPointRows.map((row) => str(row.point)),
        d.companyDetails.companyPoints,
      ),
      divisionOverviewLabel: str(companyDetails.divisionOverviewLabel),
      divisionOverview: divisionRows.map((row) => ({
            value: str(row.value),
            label: str(row.label),
          })),
    },
  }
}
