/**
 * Vital Industries 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 {
  VitalIndustriesData,
  VitalStatCardData,
  VitalPackagingStatData,
  VitalProductData,
  VitalMilestoneTabData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults                                                   */
/* ------------------------------------------------------------------ */

export const vitalIndustriesDefaults: VitalIndustriesData = {
  hero: {
    mobileImage: "/assets/vital-industries/vital-mobile-bg.jpg",
    desktopImage: "/assets/herohome/Vital Industries.jpg",
    heading: "Vital Industries",
  },
  stats: {
    cards: [
      { icon: "/assets/vital-industries/icon-incorporation.svg", title: "May 2008", description: "Incorporation Year" },
      { icon: "/assets/vital-industries/icon-pet.svg", title: "Packaging, PET & Logistics", description: "Core Sectors" },
      { icon: "/assets/vital-industries/icon-carton.svg", title: "90,000", description: "Initial Carton Box Capacity (2008) Per Month" },
      { icon: "/assets/vital-industries/icon-carton.svg", title: "8.5 Lakh+", description: "Current Carton Box Capacity Per Month" },
      { icon: "/assets/vital-industries/icon-paper.svg", title: "75 Tonnes", description: "Initial Paper Production Per Month" },
      { icon: "/assets/vital-industries/icon-paper.svg", title: "360+ Tonnes", description: "Current Paper Production Per Month" },
    ],
  },
  about: {
    badge: "about Vital Industries",
    badgeIcon: "/assets/vital-industries/vector-badge-red.svg",
    mobileWatermarkText: "Vital Industries",
    desktopWatermarkText: "About us",
    decorativeImage: "/assets/vital-industries/decorative-corner.svg",
    paragraphs: [
      "Vital Trading, a key industrial arm of the MGM Group, commenced operations in May 2008 at Mundiyambakkam, Tamil Nadu. Officially incorporated as Vital Industries Private Limited in 2009, the company has grown from a modest packaging unit into a small-scale manufacturing and logistics hub serving both domestic and international markets.",
      "From its early days of producing approximately 90,000 carton boxes per month, the company has significantly scaled its operations to over 8.5 lakh boxes monthly. This growth has been driven by continuous investments in infrastructure, automation, and supply chain optimization. Today, Vital Industries caters to diverse sectors, including FMCG, retail, and food & beverage.",
      "Production capacity has also expanded remarkably—from 75 tonnes of paper material per month to over 360 tonnes. This progress is supported by advanced machinery, a skilled workforce, and efficient manufacturing processes that ensure consistent quality and timely delivery.",
      "A key pillar of Vital Industries' operations is its robust logistics network. Vital Transport, launched in 2010 with just three tankers, has evolved into a large-scale transportation division with a fleet of over 115 vehicles. This includes tankers, trucks, and delivery vans, enabling seamless movement of raw materials and finished goods across multiple regions.",
      "This integrated logistics capability strengthens the company's end-to-end supply chain model, ensuring efficiency, reliability, and timely distribution.",
    ],
  },
  packaging: {
    badge: "Packaging",
    badgeIcon: "/assets/vital-industries/vector-badge-dark.svg",
    description: "Since its inception, Vital Industries has transformed from a modest carton box manufacturer into a large-scale packaging and logistics hub. Through continuous investments in infrastructure, automation, and supply chain optimization, the company has achieved substantial growth in operational capacity. Today, it serves domestic and international markets with efficient and high-quality packaging solutions.",
    companyInfoLabel: "Company Information:",
    stats: [
      { value: "6.13 Lakh", label: "SAFL Villupuram, Boxes distributed" },
      { value: "8.5 Lakh+", label: "Carton Boxes Manufactured Per Month" },
      { value: "1.9 Lakh+", label: "Boxes distributed in Kerala & Pondy" },
      { value: "360+ Tonnes", label: "Tonnes of Paper Produced Monthly" },
    ],
    bullets: [
      "Steady Business Expansion – Evolved from a small-scale operation into a high-capacity manufacturing and logistics center.",
      "Strategic Infrastructure Development – Growth driven by continuous investments in modern facilities and production capabilities.",
      "Advanced Manufacturing Process – Uses efficient and streamlined production systems to ensure consistency and reliability.",
      "Automation Integration – Adoption of automation has improved productivity and operational efficiency.",
      "Diverse Industry Service – Provides solutions for sectors including FMCG, retail, and food & beverage industries.",
      "Portfolio Diversification – Expanded offerings beyond paper-based packaging through the MGM SAFL Distribution network.",
    ],
  },
  transport: {
    badge: "Transport",
    badgeIcon: "/assets/vital-industries/vector-badge-red.svg",
    description: "Vital Transport, established in 2010, has grown from a fleet of three tankers into a strong transportation network with over 115 vehicles. The company plays a key role in supporting efficient logistics operations across India. Specializing in ENA (Extra Neutral Alcohol) transportation, it ensures smooth and reliable distribution services. With a focus on scalability and operational excellence, Vital Transport continues to strengthen its nationwide presence.",
    enaTransportationLabel: "ENA Transportation:",
    productsLabel: "Products Transported:",
    enaBullets: [
      "ENA Transportation – Reliable transportation and distribution of ENA across India.",
      "Supply Network – Supplying to SAFL Villupuram, Transworld Chennai, Normandy, Cochin, and Accord Distilleries.",
    ],
    products: [
      { name: "IMFL", image: "/assets/vital%20industries(updated)/IMFL.jpeg" },
      { name: "Palm Oil", image: "/assets/vital%20industries(updated)/palm%20oil.jpg" },
      { name: "Cements", image: "/assets/vital%20industries(updated)/cement.jpg" },
      { name: "Limestone", image: "/assets/vital%20industries(updated)/limestone.jpg" },
      { name: "Cashew", image: "/assets/vital%20industries(updated)/cashew.jpg" },
      { name: "Salt", image: "/assets/vital-industries/product-salt.jpg" },
      { name: "Cement sheets", image: "/assets/vital-industries/product-cementsheets.jpg" },
      { name: "Bottles", image: "/assets/vital-industries/product-bottles.jpg" },
    ],
  },
  milestone: {
    badge: "Milestone Highlights",
    badgeIcon: "/assets/vital-industries/vector-badge-red.svg",
    watermarkText: "Vital Industries India Pvt Ltd.",
    tabs: [
      {
        tabName: "Logistics",
        image: "/assets/vital-industries/vital-transport.jpeg",
        bullets: [
          "Established Presence – Founded in 2010, starting operations with 3 tankers.",
          "Fleet Expansion – Expanded to a fleet of 115+ vehicles, including tankers, trucks, and delivery vans.",
          "Pan-India Operations – Provides logistics and transportation services across India.",
          "ENA Transportation Expertise – Specialized in Extra Neutral Alcohol (ENA) transportation with a dedicated fleet of 10 trucks.",
          "Major Supply Locations – Key supply destinations include SAFL Villupuram, Transworld Chennai, Normandy (Cochin), and Tuticorin.",
          "Diverse Cargo Handling – Transports IMFL, Palm Oil, Cement, Limestone, Cashew, Salt, Cement Sheets, and Bottles.",
          "Core Business Strengths – Strong logistics network with scalable operations, reliable delivery, sustainability focus, and integrated support for packaging and distribution.",
        ],
      },
      {
        tabName: "Plastics",
        image: "/assets/vital-industries/vital-plastic.jpg",
        bullets: [
          "Division Name: Vital Plastic",
          "Operations Started: 2014",
          "Location: Nandyal, Andhra Pradesh",
          "Core Products: PET Preforms & Liquor Bottle Caps",
          "Industry Focus: Liquor Manufacturing",
          "Quality Standard: Adheres to International Manufacturing Standards",
          "Business Strength: Export-Ready Production & Scalable Plastic Packaging Solutions",
        ],
      },
      {
        tabName: "Packaging",
        image: "/assets/vital-industries/vital-package.jpg",
        bullets: [
          "Sector – Packaging industry with manufacturing and logistics capabilities.",
          "Growth Journey – Expanded from a modest carton box unit into a high-capacity manufacturing and logistics hub.",
          "Initial Capacity – Started with a production capacity of 90,000 carton boxes per month.",
          "Current Capacity – Increased production to 8.5 Lakh+ carton boxes per month.",
          "Key Distribution Network – SAFL Villupuram: 6.13 Lakh boxes | Kerala & Pondicherry: 1.9 Lakh+ boxes.",
          "Industries Served – Catering to FMCG, Retail, and Food & Beverage sectors.",
          "Paper Production Growth – Expanded from 75 tonnes/month to 360+ tonnes/month.",
        ],
      },
    ],
  },
}

/* ------------------------------------------------------------------ */
/*  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 getVitalIndustriesData(): Promise<VitalIndustriesData> {
  const d = vitalIndustriesDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("vital-industries")

  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 packaging = (entry.packaging as AnyRec | undefined) ?? {}
  const transport = (entry.transport as AnyRec | undefined) ?? {}
  const milestone = (entry.milestone as AnyRec | undefined) ?? {}
  const cardRows = (statsWrapper.cards as AnyRec[] | undefined) ?? []
  const paragraphRows = (about.paragraphs as AnyRec[] | undefined) ?? []
  const packagingStatRows = (packaging.stats as AnyRec[] | undefined) ?? []
  const packagingBulletRows = (packaging.bullets as AnyRec[] | undefined) ?? []
  const enaBulletRows = (transport.enaBullets as AnyRec[] | undefined) ?? []
  const productRows = (transport.products as AnyRec[] | undefined) ?? []
  const milestoneTabRows = (milestone.tabs as AnyRec[] | undefined) ?? []

  return {
    hero: {
      mobileImage: media(hero.mobileImage_9x16),
      desktopImage: media(hero.desktopImage_5x3),
      heading: str(hero.heading),
    },
    stats: {
      cards: cardRows.map((row) => {
        return {
          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)),
    },
    packaging: {
      badge: str(packaging.badge),
      badgeIcon: d.packaging.badgeIcon,
      description: str(packaging.description),
      companyInfoLabel: str(packaging.companyInfoLabel, d.packaging.companyInfoLabel),
      stats: packagingStatRows.map((row) => {
        return {
          value: str(row.value),
          label: str(row.label),
        }
      }),
      bullets: packagingBulletRows.map((row) => str(row.text)),
    },
    transport: {
      badge: str(transport.badge),
      badgeIcon: d.transport.badgeIcon,
      description: str(transport.description),
      enaTransportationLabel: str(transport.enaTransportationLabel, d.transport.enaTransportationLabel),
      productsLabel: str(transport.productsLabel, d.transport.productsLabel),
      enaBullets: enaBulletRows.map((row) => str(row.text)),
      products: productRows.map((row) => {
        return {
          name: str(row.name),
          image: media(row.image_4x5) || str(row.imageUrl),
        }
      }),
    },
    milestone: {
      badge: str(milestone.badge),
      badgeIcon: d.milestone.badgeIcon,
      watermarkText: titleCase(str(milestone.watermarkText)),
      tabs: milestoneTabRows.map((tab) => {
        return {
          tabName: str(tab.tabName),
          image: media(tab.image_3x2) || str(tab.imageUrl),
          bullets: ((tab.bullets as AnyRec[] | undefined) ?? []).map((row) => str(row.text)),
        }
      }),
    },
  }
}
