/**
 * lib/api.ts
 * Typed API helpers for the NxtLab backend.
 * All data comes from GET /api/content/page-data/ (ISR cached).
 */

const API_BASE = process.env.API_BASE ?? process.env.NEXT_PUBLIC_API_BASE ?? 'http://127.0.0.1:8000'

// ── Types ────────────────────────────────────────────────────────────────────

export interface HeroStat {
  id: number
  value: string
  label: string
  order: number
  is_active: boolean
}

export interface HeroData {
  id: number
  badge_text: string
  headline_line1: string
  headline_line2: string
  subheadline: string
  cta_primary_text: string
  cta_primary_href: string
  cta_secondary_text: string
  cta_secondary_href: string
  hero_video_url: string
  stats: HeroStat[]
}

export interface MarqueeItem {
  id: number
  text: string
  order: number
  is_active: boolean
}

export interface Service {
  id: number
  icon: string
  title: string
  description: string
  tag: string
  order: number
  is_active: boolean
}

export interface AboutValue {
  id: number
  text: string
  order: number
  is_active: boolean
}

export interface AboutStat {
  id: number
  value: string
  label: string
  order: number
  is_active: boolean
}

export interface AboutData {
  id: number
  heading_line1: string
  heading_line2: string
  paragraph1: string
  paragraph2: string
  cta_text: string
  cta_href: string
  logo_image_url: string
  values: AboutValue[]
  stats: AboutStat[]
}

export interface ProjectTechStack {
  id: number
  name: string
  category: string
  order: number
  is_active: boolean
}

export interface ProjectTimeline {
  id: number
  phase: string
  duration: string
  description: string
  order: number
  is_active: boolean
}

export interface ProjectHighlight {
  id: number
  text: string
  order: number
  is_active: boolean
}

export interface Project {
  id: number
  slug: string
  name: string
  category: string
  url: string
  image_url: string
  alt_text: string
  tag: string
  description: string
  full_description: string
  accent_color: string
  year: string
  role: string
  client: string
  is_featured: boolean
  order: number
  tech_stack: ProjectTechStack[]
  timeline: ProjectTimeline[]
  highlights: ProjectHighlight[]
}

export interface ProcessStep {
  id: number
  number: string
  title: string
  description: string
  icon: string
  order: number
  is_active: boolean
}

export interface Stat {
  id: number
  value: number
  suffix: string
  label: string
  sublabel: string
  order: number
  is_active: boolean
}

export interface Testimonial {
  id: number
  quote: string
  name: string
  role: string
  avatar_initials: string
  accent_color: string
  image_url?: string
  order: number
  is_active: boolean
}

export interface SiteSettings {
  id: number
  site_name: string
  tagline: string
  email: string
  location: string
  linkedin_url: string
  github_url: string
  twitter_url: string
  instagram_url: string
  available_for_projects: boolean
  logo_url?: string        // Cloudinary URL for site logo
}

export interface PageSections {
  services_badge: string
  services_heading: string
  services_subheading: string
  process_badge: string
  process_heading: string
  process_subheading: string
  testimonials_badge: string
  testimonials_heading: string
  testimonials_heading_suffix: string
  testimonials_companies_label: string
  pricing_badge: string
  pricing_heading_line1: string
  pricing_heading_line2: string
  pricing_perk_1: string
  pricing_perk_2: string
  pricing_perk_3: string
  pricing_bottom_link_text: string
  cta_badge: string
  cta_heading_line1: string
  cta_heading_line2: string
  cta_subheading: string
  cta_button_text: string
  cta_secondary_text: string
  // Section image URLs (Cloudinary) — all optional
  cta_image_url?: string
  footer_banner_url?: string
  infrastructure_image_url?: string
  integrations_image_url?: string
  pricing_image_url?: string
  metrics_image_url?: string
  process_image_url?: string
  developers_image_url?: string
}

export interface Expertise {
  id: number
  name: string
  stacks: string
  status: string
  order: number
  is_active: boolean
}

export interface TechStackItem {
  id: number
  name: string
  category: string
  order: number
  is_active: boolean
}

export interface PricingPlan {
  id: number
  name: string
  description: string
  monthly_price: number | null
  annual_price: number | null
  is_featured: boolean
  cta_text: string
  cta_href: string
  features: string[]
  order: number
  is_active: boolean
}

export interface QualityFeature {
  id: number
  icon: string
  title: string
  description: string
  image_url: string
  order: number
  is_active: boolean
}

export interface QualityData {
  id: number
  badge_text: string
  heading_line1: string
  heading_line2: string
  description: string
  score_value: string
  score_label: string
  certifications: string[]
  features: QualityFeature[]
}

export interface TeamMember {
  id: number
  name: string
  role: string
  initials: string
  accent_color: string
  gradient: string
  description: string
  image_url?: string
  is_founder: boolean
  order: number
  is_active: boolean
}

export interface PageData {
  hero: HeroData | null
  marquee: MarqueeItem[]
  services: Service[]
  about: AboutData | null
  projects: Project[]
  process_steps: ProcessStep[]
  stats: Stat[]
  testimonials: Testimonial[]
  settings: SiteSettings | null
  sections: PageSections
  expertise: Expertise[]
  tech_stack: TechStackItem[]
  pricing: PricingPlan[]
  quality: QualityData | null
  team: TeamMember[]
}

// ── Fetcher ──────────────────────────────────────────────────────────────────

/**
 * Fetches all page content in a single request.
 * Uses Next.js ISR: revalidate every 5 minutes.
 * Falls back to null on error so the site still renders with defaults.
 */
export async function fetchPageData(): Promise<PageData | null> {
  try {
    const res = await fetch(`${API_BASE}/api/content/page-data/`, {
      next: { revalidate: 300 },
      signal: AbortSignal.timeout(15000), // 15s timeout
    })
    if (!res.ok) return null
    return (await res.json()) as PageData
  } catch {
    return null
  }
}

/**
 * POST a contact form submission to the backend.
 */
export async function submitContact(data: {
  name: string
  email: string
  project_type: string
  budget?: string
  message: string
}): Promise<{ success: boolean; message?: string; errors?: Record<string, string[]> }> {
  try {
    const res = await fetch(`${API_BASE}/api/content/contact/`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    })
    const json = await res.json()
    if (res.ok) return { success: true, message: json.message }
    return { success: false, errors: json }
  } catch {
    return { success: false, message: 'Network error. Please try again.' }
  }
}
