/**
 * Cookie Banner — Configuration & Category Generation
 *
 * Default texts, styling, and category generation from data points.
 */

import {
  DataPoint,
  CookieBannerCategory,
  CookieBannerConfig,
  CookieBannerStyling,
  CookieBannerTexts,
  CookieInfo,
  LocalizedText,
  SupportedLanguage,
} from '../types'
import { DEFAULT_COOKIE_CATEGORIES } from '../catalog/loader'

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

function t(text: LocalizedText, language: SupportedLanguage): string {
  return text[language]
}

// =============================================================================
// DEFAULT CONFIGURATION
// =============================================================================

export const DEFAULT_COOKIE_BANNER_TEXTS: CookieBannerTexts = {
  title: { de: 'Cookie-Einstellungen', en: 'Cookie Settings' },
  description: {
    de: 'Wir verwenden Cookies, um Ihnen die bestmoegliche Nutzung unserer Website zu ermoeglichen. Einige Cookies sind technisch notwendig, waehrend andere uns helfen, Ihre Nutzererfahrung zu verbessern.',
    en: 'We use cookies to provide you with the best possible experience on our website. Some cookies are technically necessary, while others help us improve your user experience.',
  },
  acceptAll: { de: 'Alle akzeptieren', en: 'Accept All' },
  rejectAll: { de: 'Nur notwendige', en: 'Essential Only' },
  customize: { de: 'Einstellungen', en: 'Customize' },
  save: { de: 'Auswahl speichern', en: 'Save Selection' },
  privacyPolicyLink: {
    de: 'Mehr in unserer Datenschutzerklaerung',
    en: 'More in our Privacy Policy',
  },
}

export const DEFAULT_COOKIE_BANNER_STYLING: CookieBannerStyling = {
  position: 'BOTTOM',
  theme: 'LIGHT',
  primaryColor: '#6366f1',
  secondaryColor: '#f1f5f9',
  textColor: '#1e293b',
  backgroundColor: '#ffffff',
  borderRadius: 12,
  maxWidth: 480,
}

// =============================================================================
// GENERATOR FUNCTIONS
// =============================================================================

function getExpiryFromRetention(retention: string): string {
  const mapping: Record<string, string> = {
    '24_HOURS': '24 Stunden / 24 hours',
    '30_DAYS': '30 Tage / 30 days',
    '90_DAYS': '90 Tage / 90 days',
    '12_MONTHS': '1 Jahr / 1 year',
    '24_MONTHS': '2 Jahre / 2 years',
    '36_MONTHS': '3 Jahre / 3 years',
    'UNTIL_REVOCATION': 'Bis Widerruf / Until revocation',
    'UNTIL_PURPOSE_FULFILLED': 'Session',
    'UNTIL_ACCOUNT_DELETION': 'Bis Kontoschliessung / Until account deletion',
  }
  return mapping[retention] || 'Session'
}

export function generateCookieCategories(
  dataPoints: DataPoint[]
): CookieBannerCategory[] {
  const cookieDataPoints = dataPoints.filter((dp) => dp.cookieCategory !== null)

  return DEFAULT_COOKIE_CATEGORIES.map((defaultCat) => {
    const categoryDataPoints = cookieDataPoints.filter(
      (dp) => dp.cookieCategory === defaultCat.id
    )

    const cookies: CookieInfo[] = categoryDataPoints.map((dp) => ({
      name: dp.code,
      provider: 'First Party',
      purpose: dp.purpose,
      expiry: getExpiryFromRetention(dp.retentionPeriod),
      type: 'FIRST_PARTY',
    }))

    return {
      ...defaultCat,
      dataPointIds: categoryDataPoints.map((dp) => dp.id),
      cookies,
    }
  }).filter((cat) => cat.dataPointIds.length > 0 || cat.isRequired)
}

export function generateCookieBannerConfig(
  tenantId: string,
  dataPoints: DataPoint[],
  customTexts?: Partial<CookieBannerTexts>,
  customStyling?: Partial<CookieBannerStyling>
): CookieBannerConfig {
  const categories = generateCookieCategories(dataPoints)

  return {
    id: `cookie-banner-${tenantId}`,
    tenantId,
    categories,
    styling: { ...DEFAULT_COOKIE_BANNER_STYLING, ...customStyling },
    texts: { ...DEFAULT_COOKIE_BANNER_TEXTS, ...customTexts },
    updatedAt: new Date(),
  }
}
