// Home Page API Service
// Fetches data from Payload CMS for the homepage

export interface ServiceFeature {
  icon?: string
  title?: string
  description?: string
  link?: {
    url?: string
  }
}

interface PortfolioSection {
  headline?: string
  subheadline?: string
  itemsToShow?: number
}

interface CTASection {
  headline?: string
  description?: string
  buttonText?: string
  buttonLink?: string
}

export interface HomeData {
  heroHeadline?: string
  heroSubheadline?: string
  heroDesktopVideo?: {
    url?: string
    filename?: string
    alt?: string
    sizes?: {
      thumbnail?: {
        url?: string
      }
    }
  }
  heroMobileVideo?: {
    url?: string
    filename?: string
    alt?: string
  }
  heroFallbackImage?: {
    url?: string
    filename?: string
    alt?: string
  }
  heroLogo?: {
    url?: string
    filename?: string
    alt?: string
  }
  serviceFeatures?: ServiceFeature[]
  portfolioSection?: PortfolioSection
  ctaSection?: CTASection
}

export interface ServiceItem {
  icon?: string
  title?: string
  description?: string
  link?: {
    url?: string
  }
}

export interface PortfolioItem {
  id: string
  title: string
  slug: string
  url?: string
  image?: {
    url?: string
    alt?: string
    filename?: string
    sizes?: {
      thumbnail?: {
        url?: string
      }
    }
  }
  description?: string
  websiteType?: string
  tags?: Array<{ tag?: string }>
}

// Get API base URL
function getApiBaseUrl(): string {
  if (typeof process !== 'undefined' && process.env?.PAYLOAD_CMS_URL) {
    return process.env.PAYLOAD_CMS_URL
  }
  return import.meta.env.PUBLIC_PAYLOAD_CMS_URL || 'https://enchun-admin.anlstudio.cc'
}

const PAYLOAD_URL = getApiBaseUrl()
const PAYLOAD_API_KEY = import.meta.env.PAYLOAD_CMS_API_KEY

// Build common headers
function getHeaders(): HeadersInit {
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  }

  if (PAYLOAD_API_KEY) {
    headers['Authorization'] = `Bearer ${PAYLOAD_API_KEY}`
  }

  return headers
}

// Fetch Home global data
export async function getHomeData(draft = false): Promise<HomeData | null> {
  try {
    const draftParam = draft ? '?draft=true' : ''
    const response = await fetch(`${PAYLOAD_URL}/api/globals/home${draftParam}`, {
      headers: getHeaders(),
    })

    if (!response.ok) {
      console.error('Failed to fetch home data:', response.status, response.statusText)
      return null
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error fetching home data:', error)
    return null
  }
}

// Fetch Portfolio items for preview
export async function getPortfolioPreview(limit = 3): Promise<PortfolioItem[]> {
  try {
    const response = await fetch(
      `${PAYLOAD_URL}/api/portfolio?sort=-updatedAt&limit=${limit}&depth=1`,
      {
        headers: getHeaders(),
      }
    )

    if (!response.ok) {
      console.error('Failed to fetch portfolio items:', response.status)
      return []
    }

    const data = await response.json()
    return data.docs || []
  } catch (error) {
    console.error('Error fetching portfolio items:', error)
    return []
  }
}

// Combined fetch for homepage
export async function getHomepageData(draft = false): Promise<{
  home: HomeData | null
  portfolioItems: PortfolioItem[]
}> {
  // First fetch home data to get the itemsToShow value
  const home = await getHomeData(draft)
  const limit = home?.portfolioSection?.itemsToShow || 3

  // Then fetch portfolio items with the correct limit
  const portfolioItems = await getPortfolioPreview(limit)

  return { home, portfolioItems }
}
