import { createClient } from '@supabase/supabase-js'

export interface NavLinkItem {
  label: string
  href: string
}

export interface FooterLinkGroup {
  label: string
  links: NavLinkItem[]
}

export interface HeroStat {
  value: number
  suffix: string
  label: string
}

export interface CommunityMetric {
  value: number
  suffix: string
  label: string
  sublabel: string
}

export interface ServiceOffering {
  id: string
  icon_key: 'zap' | 'chart' | 'calendar' | 'globe'
  title: string
  description: string
  features: string[]
  accent: string
  span: string
  large: boolean
}

export interface ProcessStepContent {
  step: string
  icon_key: 'search' | 'pencil' | 'code' | 'rocket'
  title: string
  description: string
}

export interface ValueProp {
  title: string
  body: string
}

export interface SiteContent {
  navbar: {
    links: NavLinkItem[]
    ctaLabel: string
  }
  footer: {
    description: string
    locationLine: string
    linkGroups: FooterLinkGroup[]
    legalLine: string
  }
  hero: {
    eyebrow: string
    headlineWords: string[]
    accentWords: string[]
    subtext: string
    ctaPrimaryLabel: string
    ctaSecondaryLabel: string
    stats: HeroStat[]
  }
  community: {
    sectionLabel: string
    headingPrefix: string
    headingAccent: string
    paragraph1: string
    paragraph2: string
    cities: string[]
    metrics: CommunityMetric[]
  }
  servicesSection: {
    sectionLabel: string
    headingPrefix: string
    headingAccent: string
    body: string
    offerings: ServiceOffering[]
  }
  processSection: {
    sectionLabel: string
    headingPrefix: string
    headingAccent: string
    steps: ProcessStepContent[]
    valueProps: ValueProp[]
  }
  beforeAfterSection: {
    sectionLabel: string
    headingPrefix: string
    headingAccent: string
    body: string
  }
  ctaSection: {
    sectionLabel: string
    headingPrefix: string
    headingAccent: string
    body: string
    primaryLabel: string
    secondaryLabel: string
  }
}

export const defaultSiteContent: SiteContent = {
  navbar: {
    links: [
      { label: 'Services', href: '#services' },
      { label: 'Process', href: '#process' },
      { label: 'ROI Calculator', href: '#roi' },
    ],
    ctaLabel: 'Book a Strategy Call',
  },
  footer: {
    description:
      'Artisan business systems for Central Florida and beyond. We build custom digital tools that fit the way your business actually works.',
    locationLine: 'Central Florida - serving clients worldwide',
    linkGroups: [
      {
        label: 'Services',
        links: [
          { label: 'Micro-Apps', href: '#services' },
          { label: 'Data Automation', href: '#services' },
          { label: 'Scheduling Systems', href: '#services' },
          { label: 'Artisan Web Systems', href: '#services' },
        ],
      },
      {
        label: 'Company',
        links: [
          { label: 'Process', href: '#process' },
          { label: 'ROI Calculator', href: '#roi' },
          { label: 'Book a Call', href: '/booking' },
        ],
      },
    ],
    legalLine: 'Built in Central Florida. Deployed worldwide.',
  },
  hero: {
    eyebrow: "Central Florida's Business Systems Studio",
    headlineWords: ['Your', 'Business', 'Runs', 'on', 'Custom', 'Systems', '-', 'We', 'Build', 'Them.'],
    accentWords: ['Custom', 'Systems'],
    subtext:
      'DaliTek helps Central Florida businesses eliminate manual work and operate with clarity. We build web apps, automations, and digital systems that fit the way you actually work.',
    ctaPrimaryLabel: 'Book a Strategy Call',
    ctaSecondaryLabel: 'Talk to DaliBot',
    stats: [
      { value: 40, suffix: '+', label: 'Hours saved per client monthly' },
      { value: 3, suffix: 'x', label: 'Faster operations on average' },
      { value: 100, suffix: '%', label: 'Custom-built, no bloat' },
    ],
  },
  community: {
    sectionLabel: 'Central Florida First',
    headingPrefix: 'Your community deserves',
    headingAccent: 'better systems.',
    paragraph1:
      'We start in our backyard. Central Florida businesses are the backbone of this region - roofers, cleaners, consultants, tour operators, service companies - and most are still stuck in spreadsheets and disconnected tools.',
    paragraph2:
      'DaliTek modernizes local businesses without bloated software by building systems around how you already work. While our roots are in Central Florida, we also work with clients across the U.S. and globally.',
    cities: ['Orlando', 'Winter Garden', 'Ocoee', 'Clermont'],
    metrics: [
      { value: 50, suffix: '+', label: 'Hours of manual work eliminated', sublabel: 'per client, per month' },
      { value: 12, suffix: '+', label: 'Local businesses modernized', sublabel: 'and counting' },
      { value: 0, suffix: ' bloated', label: 'Off-the-shelf platforms', sublabel: 'everything is custom-built' },
    ],
  },
  servicesSection: {
    sectionLabel: 'What We Build',
    headingPrefix: 'Systems that fit your',
    headingAccent: 'business',
    body:
      'Every tool we build is designed around your workflow - not a template and not a generic platform. Custom-fit from day one.',
    offerings: [
      {
        id: 'micro-apps',
        icon_key: 'zap',
        title: 'Micro-Apps',
        description:
          'Lightweight custom tools that replace spreadsheet chaos. Estimators, intake forms, internal dashboards, and client-facing portals.',
        features: ['Quote and estimator tools', 'Internal dashboards', 'Client portals', 'Intake systems'],
        accent: '#6366f1',
        span: 'col-span-1 md:col-span-2',
        large: true,
      },
      {
        id: 'data-automation',
        icon_key: 'chart',
        title: 'Data and Spreadsheet Automation',
        description:
          'We streamline Excel, Power Query, and Python workflows so your data works for you instead of against you.',
        features: ['Spreadsheet cleanup', 'Automated reporting', 'Power Query pipelines', 'Python data tools'],
        accent: '#38bdf8',
        span: 'col-span-1',
        large: false,
      },
      {
        id: 'scheduling',
        icon_key: 'calendar',
        title: 'Scheduling and Operations Systems',
        description:
          'Booking pages, job scheduling, and operations dashboards that eliminate back-and-forth and improve visibility.',
        features: ['Booking flows', 'Job tracking', 'Operations dashboards', 'Admin automation'],
        accent: '#a78bfa',
        span: 'col-span-1',
        large: false,
      },
      {
        id: 'web-systems',
        icon_key: 'globe',
        title: 'Artisan Web Systems',
        description:
          'High-converting websites built as business infrastructure, not templates. Built to capture leads and drive action.',
        features: ['Custom business websites', 'Lead capture systems', 'Conversion optimization', 'SEO-ready architecture'],
        accent: '#f59e0b',
        span: 'col-span-1 md:col-span-2',
        large: true,
      },
    ],
  },
  processSection: {
    sectionLabel: 'How It Works',
    headingPrefix: 'From bottleneck to',
    headingAccent: 'clarity',
    steps: [
      {
        step: '01',
        icon_key: 'search',
        title: 'Discover',
        description:
          'We map your real workflow, where time gets lost, and where the highest leverage automation should happen first.',
      },
      {
        step: '02',
        icon_key: 'pencil',
        title: 'Design',
        description:
          'We design architecture and UX before building so outcomes are clear and execution stays aligned.',
      },
      {
        step: '03',
        icon_key: 'code',
        title: 'Build',
        description:
          'We build custom systems, validate them with real scenarios, and iterate quickly to fit your operations.',
      },
      {
        step: '04',
        icon_key: 'rocket',
        title: 'Launch',
        description:
          'We deploy and support rollout so your team can adopt the new system smoothly and confidently.',
      },
    ],
    valueProps: [
      {
        title: 'No guesswork',
        body: 'You know exactly what is being built before implementation starts.',
      },
      {
        title: 'Fast turnaround',
        body: 'Most projects are delivered in weeks, not months.',
      },
      {
        title: 'You own it',
        body: 'Your core system belongs to your business without forced lock-in.',
      },
      {
        title: 'Local partnership',
        body: 'Central Florida-first collaboration with global delivery capability.',
      },
    ],
  },
  beforeAfterSection: {
    sectionLabel: 'The Transformation',
    headingPrefix: 'See the difference',
    headingAccent: 'a system makes',
    body: 'Compare a real service workflow before and after structure, automation, and system design.',
  },
  ctaSection: {
    sectionLabel: 'Ready to modernize?',
    headingPrefix: 'Your business runs on',
    headingAccent: 'systems that fit.',
    body:
      'Stop working around your tools. Book a free strategy session or start a conversation with DaliBot - no pressure, just clarity.',
    primaryLabel: 'Book a Strategy Call',
    secondaryLabel: 'Talk to DaliBot',
  },
}

type ContentRow = {
  block_key: keyof SiteContent
  content: Record<string, unknown>
}

function mergeObject<T>(base: T, incoming: unknown): T {
  if (!incoming || typeof incoming !== 'object' || Array.isArray(incoming)) return base
  return { ...base, ...incoming } as T
}

export async function getSiteContent(): Promise<SiteContent> {
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
  const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY

  if (!supabaseUrl || !supabaseAnonKey) return defaultSiteContent

  const supabase = createClient(supabaseUrl, supabaseAnonKey, {
    auth: { persistSession: false, autoRefreshToken: false },
  })

  const { data, error } = await supabase
    .from('site_content_blocks')
    .select('block_key, content')
    .eq('is_active', true)

  if (error || !data) return defaultSiteContent

  const rows = data as ContentRow[]
  const rowMap = new Map(rows.map((r) => [r.block_key, r.content]))

  return {
    navbar: mergeObject(defaultSiteContent.navbar, rowMap.get('navbar')),
    footer: mergeObject(defaultSiteContent.footer, rowMap.get('footer')),
    hero: mergeObject(defaultSiteContent.hero, rowMap.get('hero')),
    community: mergeObject(defaultSiteContent.community, rowMap.get('community')),
    servicesSection: mergeObject(defaultSiteContent.servicesSection, rowMap.get('servicesSection')),
    processSection: mergeObject(defaultSiteContent.processSection, rowMap.get('processSection')),
    beforeAfterSection: mergeObject(defaultSiteContent.beforeAfterSection, rowMap.get('beforeAfterSection')),
    ctaSection: mergeObject(defaultSiteContent.ctaSection, rowMap.get('ctaSection')),
  }
}
