// app/(lib)/services/aboutService.ts
import { apiClient } from "../../app/api/client";
import { handleAPIError } from "../utils/apiErrorHandler";

export interface AboutHeading {
  mainHeading?: string;
  subHeading?: string;
}

export interface AboutSection {
  mainHeading?: string;
  subHeading?: string;
  ctaButtonText?: string;
  paragraph1?: string;
  paragraph2?: string;
  paragraph3?: string;
  description?: string;
  features?: string; // JSON stringified array
  programs?: string; // JSON stringified array
  images?: string; // JSON stringified array
  imagesPreviews?: string; // JSON stringified array
}

export interface SliderImages {
  sliderImages?: string; // JSON stringified array
  reverseSliderImages?: string; // JSON stringified array
  sliderImagesPreviews?: string; // JSON stringified array
  reverseSliderImagesPreviews?: string; // JSON stringified array
}

export interface AboutContent {
  heading?: AboutHeading;
  whoWeAre?: AboutSection;
  ourMethod?: AboutSection;
  ourMission?: AboutSection;
  whatChildrenGain?: AboutSection;
  sliderImages?: SliderImages;
  sliderTexts?: any;
  bottomSliders?: any;
}

export interface AboutPageData {
  page_id: string;
  franchisee_id?: string | null;
  title: string;
  is_global: boolean;
  slug: string;
  seo_title?: string;
  seo_description?: string;
  template: {
    id: string;
    name: string;
    slug: string;
  };
  status: string;
  content: AboutContent;
  translated_content?: AboutContent;
}

export interface AboutPageDataWithTranslations {
  default: AboutContent;
  translated?: AboutContent;
}

export class AboutService {
  private readonly endpoint = "pages/about";

  async fetchByDomain(domain: string, franchiseeId?: string | null, language?: string): Promise<AboutPageDataWithTranslations> {
    const startTime = Date.now();

    try {
      const params: Record<string, string> = {};
      if (franchiseeId) params.franchiseeId = franchiseeId;
      if (language && language !== "default") params.lang = language;

      const response = await apiClient.get<any>(
        this.endpoint,
        {
          headers: { "X-Domain": domain },
          params: Object.keys(params).length > 0 ? params : undefined,
        }
      );

      if (!response.data?.status || !response.data?.data?.content) {
        return this.getDefaultData();
      }

      const elapsed = Date.now() - startTime;

      return {
        default: response.data.data.content,
        translated: response.data.data.translated_content || undefined,
      };
    } catch (error) {
      return handleAPIError(error, domain, startTime, this.getDefaultData.bind(this));
    }
  }

  private async getDefaultData(): Promise<AboutPageDataWithTranslations> {
    try {
      return {
        default: {
          heading: {
            mainHeading: "About young engineers",
            subHeading: "Where Learning Meets Imagination",
          },
          whoWeAre: {
            mainHeading: "Who we are",
            paragraph1: "Young Engineers helps children discover the joy of learning through play and creativity.",
            paragraph2: "Our team of passionate educators and STEM professionals make every lesson engaging, safe, and inspiring — combining fun, hands-on building with real science and engineering concepts to help every child grow curious and confident",
            ctaButtonText: "Discover Programs",
          },
          ourMethod: {
            mainHeading: "Our Method",
            paragraph1: "We call it \"Edutainment\" — a unique blend of education and entertainment.",
            paragraph2: "Our programs combine storytelling, teamwork, and hands-on model building using LEGO® and other construction materials.",
            paragraph3: "Children learn complex STEM principles like physics, energy, mechanics, and coding — without even realizing they're learning, because they're too busy having fun!",
            ctaButtonText: "Discover programs",
          },
          ourMission: {
            mainHeading: "Our Mission",
            subHeading: "What Parents Often Notice in Their Children After Our Classes",
            paragraph1: "Since 2008, Young Engineers has been inspiring children around the world to explore science, technology, engineering, and mathematics (STEM) in the most engaging and meaningful way — by building",
            paragraph2: "Our mission is to make learning hands-on, exciting, and purposeful, helping children develop problem-solving skills, creativity, and confidence as they build real working models and discover how the world around",
            paragraph3: "Every Young Engineers session is designed to spark curiosity and show kids that science isn't just something you read about — it's something you can build",
            features: JSON.stringify([
              { featureTitle: "Stronger Logic & Critical Thinking" },
              { featureTitle: "Boosted Confidence & Independence" },
              { featureTitle: "Improved Teamwork & Communication" },
              { featureTitle: "Visible Progress & Genuine Curiosity" },
            ]),
            ctaButtonText: "Discover programs",
          },
          whatChildrenGain: {
            mainHeading: "What Children Gain",
            programs: JSON.stringify([{ programHeading: "Program for developing confidence " }]),
          },
        },
      };
    } catch (error) {
      console.error("[AboutService] Failed to load default data:", error);
      return { default: {} };
    }
  }
}

export const aboutService = new AboutService();
