'use client'

import { useState, useEffect, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Shield, ChevronDown, ChevronUp } from 'lucide-react'
import { useApp } from '@/lib/context'

const COOKIE_NAME = 'bp_consent'
const SITE_ID = process.env.NEXT_PUBLIC_CONSENT_SITE_ID || 'breakpilot-marketing'

interface ConsentState {
  essential: boolean
  functional: boolean
  analytics: boolean
}

const defaultConsent: ConsentState = {
  essential: true,
  functional: false,
  analytics: false,
}

const texts = {
  de: {
    title: 'Cookie-Einwilligung',
    description: 'Wir verwenden Cookies, um unsere Website zu verbessern. Essenzielle Cookies sind für die Grundfunktionen erforderlich. Weitere Informationen finden Sie in unserer',
    privacyLink: 'Datenschutzerklärung',
    acceptAll: 'Alle akzeptieren',
    rejectAll: 'Nur notwendige',
    settings: 'Einstellungen',
    save: 'Auswahl speichern',
    categories: {
      essential: { name: 'Notwendig', description: 'Erforderlich für die Grundfunktionen der Website.', required: true },
      functional: { name: 'Funktional', description: 'Ermöglicht erweiterte Funktionen wie Spracheinstellungen und Theme-Präferenzen.' },
      analytics: { name: 'Analyse', description: 'Hilft uns zu verstehen, wie Besucher die Website nutzen.' },
    },
  },
  en: {
    title: 'Cookie Consent',
    description: 'We use cookies to improve our website. Essential cookies are required for basic functionality. For more information, please see our',
    privacyLink: 'Privacy Policy',
    acceptAll: 'Accept All',
    rejectAll: 'Essential Only',
    settings: 'Settings',
    save: 'Save Preferences',
    categories: {
      essential: { name: 'Essential', description: 'Required for basic website functionality.', required: true },
      functional: { name: 'Functional', description: 'Enables enhanced features like language settings and theme preferences.' },
      analytics: { name: 'Analytics', description: 'Helps us understand how visitors use the website.' },
    },
  },
}

function getSessionId(): string {
  if (typeof window === 'undefined') return ''
  try {
    let sid = sessionStorage.getItem('bp_session_id')
    if (!sid) {
      sid = crypto.randomUUID()
      sessionStorage.setItem('bp_session_id', sid)
    }
    return sid
  } catch { return '' }
}

function getFingerprint(): string {
  const nav = typeof navigator !== 'undefined' ? navigator : null
  const raw = [nav?.language, nav?.platform, screen?.width, screen?.height, new Date().getTimezoneOffset()].join('|')
  let hash = 0
  for (let i = 0; i < raw.length; i++) {
    hash = ((hash << 5) - hash + raw.charCodeAt(i)) | 0
  }
  return 'fp_' + Math.abs(hash).toString(36)
}

function getSavedConsent(): ConsentState | null {
  if (typeof window === 'undefined') return null
  try {
    const stored = localStorage.getItem(COOKIE_NAME)
    if (stored) return JSON.parse(stored)
  } catch { /* ignore */ }
  return null
}

function detectDevice(): { device_type: string; browser: string; os: string } {
  const ua = navigator.userAgent
  const device_type = /Mobi|Android/i.test(ua)
    ? (/Tablet|iPad/i.test(ua) ? 'tablet' : 'mobile')
    : 'desktop'
  const browserMatch = ua.match(/(Chrome|Safari|Firefox|Edge|Opera|OPR)\/[\d.]+/)
  const browser = browserMatch
    ? browserMatch[0].replace('OPR', 'Opera')
    : 'Unknown'
  const osMatch = ua.match(/(Windows NT [\d.]+|Mac OS X [\d_.]+|Linux|Android [\d.]+|iOS [\d._]+)/)
  const os = osMatch ? osMatch[0].replace(/_/g, '.') : 'Unknown'
  return { device_type, browser, os }
}

type ConsentMethod = 'accept_all' | 'reject_all' | 'custom_selection'

interface ScriptEntry { src: string; category: string }
interface CookieEntry { name: string; domain: string; expiry_days: number; category: string }

function detectScripts(): { blocked: ScriptEntry[]; released: ScriptEntry[] } {
  const scripts = Array.from(document.querySelectorAll('script[src]'))
  const released: ScriptEntry[] = []
  const blocked: ScriptEntry[] = []
  for (const el of scripts) {
    const src = el.getAttribute('src') || ''
    if (/google.*tag|gtag|analytics/i.test(src)) released.push({ src, category: 'analytics' })
    else if (/facebook|fbevents|linkedin|tiktok/i.test(src)) released.push({ src, category: 'marketing' })
  }
  return { blocked, released }
}

function detectCookies(): CookieEntry[] {
  const cookies: CookieEntry[] = []
  for (const c of document.cookie.split(';')) {
    const name = c.trim().split('=')[0]
    if (!name) continue
    let category = 'functional'
    if (/^_ga|^_gid|^_gat/i.test(name)) category = 'analytics'
    else if (/^_fb|^_gcl|^_li/i.test(name)) category = 'marketing'
    else if (/^bp_consent|^session|^csrf/i.test(name)) category = 'essential'
    cookies.push({ name, domain: window.location.hostname, expiry_days: 0, category })
  }
  return cookies
}

async function sendConsent(consent: ConsentState, method: ConsentMethod, vendorConsents?: Record<string, boolean>): Promise<string | null> {
  try {
    const { device_type, browser, os } = detectDevice()
    const { blocked, released } = detectScripts()
    const cookies_set = detectCookies()
    const res = await fetch('/api/consent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        site_id: SITE_ID,
        device_fingerprint: getFingerprint(),
        categories: [
          'essential',
          ...(consent.functional ? ['functional'] : []),
          ...(consent.analytics ? ['analytics'] : []),
        ],
        vendors: Object.keys(vendorConsents || {}).filter(k => vendorConsents?.[k]),
        vendor_consents: vendorConsents || {},
        user_agent: navigator.userAgent,
        consent_method: method,
        page_url: window.location.href,
        referrer: document.referrer || null,
        device_type,
        browser,
        os,
        screen_resolution: `${screen.width}x${screen.height}`,
        consent_scope: 'domain',
        session_id: getSessionId(),
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        scripts_blocked: blocked,
        scripts_released: released,
        cookies_set,
      }),
    })
    const result = await res.json().catch(() => null)
    if (result?.id) {
      localStorage.setItem('bp_consent_id', result.id)
      return result.id
    }
    return null
  } catch {
    return null
  }
}

interface VendorConfig {
  vendor_name: string
  category_key: string
  description_de?: string
  description_en?: string
  cookie_names?: string[]
  retention_days?: number
}

export default function ConsentBanner() {
  const { lang } = useApp()
  const t = texts[lang]
  const [visible, setVisible] = useState(false)
  const [showDetails, setShowDetails] = useState(false)
  const [consent, setConsent] = useState<ConsentState>(defaultConsent)
  const [vendors, setVendors] = useState<VendorConfig[]>([])
  const [vendorConsents, setVendorConsents] = useState<Record<string, boolean>>({})

  useEffect(() => {
    const saved = getSavedConsent()
    if (!saved) {
      setVisible(true)
    }
    // Load vendor config from backend
    fetch('/api/consent/config')
      .then(r => r.json())
      .then(data => {
        const v = data?.vendors || []
        setVendors(v)
        // Default all vendors to true
        const defaults: Record<string, boolean> = {}
        for (const vendor of v) defaults[vendor.vendor_name] = true
        setVendorConsents(defaults)
      })
      .catch(() => {})
  }, [])

  const save = useCallback((state: ConsentState, method: ConsentMethod) => {
    localStorage.setItem(COOKIE_NAME, JSON.stringify(state))
    sendConsent(state, method, vendorConsents)
    setVisible(false)
    window.dispatchEvent(new CustomEvent('consent-change', { detail: state }))
  }, [vendorConsents])

  const acceptAll = () => save({ essential: true, functional: true, analytics: true }, 'accept_all')
  const rejectAll = () => save({ essential: true, functional: false, analytics: false }, 'reject_all')
  const saveSelection = () => save(consent, 'custom_selection')

  if (!visible) return null

  const categories = Object.entries(t.categories) as [string, { name: string; description: string; required?: boolean }][]

  return (
    <AnimatePresence>
      <motion.div
        initial={{ y: 100, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={{ y: 100, opacity: 0 }}
        transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
        className="fixed bottom-0 left-0 right-0 z-[9999] p-4 md:p-6"
      >
        <div className="max-w-3xl mx-auto rounded-2xl bg-enterprise-dark/95 backdrop-blur-xl border border-white/[0.08] shadow-2xl shadow-black/40 p-6">
          {/* Header */}
          <div className="flex items-start gap-3 mb-4">
            <div className="w-8 h-8 rounded-lg bg-accent-electric/10 flex items-center justify-center shrink-0 mt-0.5">
              <Shield className="w-4 h-4 text-accent-electric" />
            </div>
            <div>
              <h3 className="text-sm font-bold text-white mb-1">{t.title}</h3>
              <p className="text-xs text-white/50 leading-relaxed">
                {t.description}{' '}
                <a href="/datenschutz" className="text-accent-electric hover:underline">{t.privacyLink}</a>.
              </p>
            </div>
          </div>

          {/* Category details */}
          <AnimatePresence>
            {showDetails && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.2 }}
                className="overflow-hidden mb-4"
              >
                <div className="space-y-2 pt-2 border-t border-white/[0.06]">
                  {categories.map(([key, cat]) => {
                    const catVendors = vendors.filter(v => v.category_key === key)
                    return (
                      <div key={key} className="rounded-xl bg-white/[0.03] border border-white/[0.06]">
                        <label className="flex items-center justify-between p-3 cursor-pointer hover:bg-white/[0.05] transition-colors">
                          <div className="flex-1 mr-4">
                            <span className="text-xs font-semibold text-white">{cat.name}</span>
                            <p className="text-xs text-white/40 mt-0.5">{cat.description}</p>
                          </div>
                          <input
                            type="checkbox"
                            checked={cat.required || consent[key as keyof ConsentState]}
                            disabled={cat.required}
                            onChange={(e) => {
                              setConsent(prev => ({ ...prev, [key]: e.target.checked }))
                              for (const v of catVendors) {
                                setVendorConsents(prev => ({ ...prev, [v.vendor_name]: e.target.checked }))
                              }
                            }}
                            className="w-4 h-4 rounded accent-accent-electric"
                          />
                        </label>
                        {catVendors.length > 0 && consent[key as keyof ConsentState] && (
                          <div className="px-3 pb-3 space-y-1">
                            {catVendors.map(v => (
                              <label key={v.vendor_name} className="flex items-center justify-between pl-4 py-1 text-xs cursor-pointer">
                                <div className="flex-1 mr-2">
                                  <span className="text-white/60">{v.vendor_name}</span>
                                  {v.retention_days && <span className="text-white/30 ml-1">({v.retention_days}d)</span>}
                                </div>
                                <input
                                  type="checkbox"
                                  checked={vendorConsents[v.vendor_name] ?? true}
                                  onChange={(e) => setVendorConsents(prev => ({ ...prev, [v.vendor_name]: e.target.checked }))}
                                  className="w-3 h-3 rounded accent-accent-electric"
                                />
                              </label>
                            ))}
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Buttons */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
            <button
              onClick={acceptAll}
              className="flex-1 px-4 py-2.5 rounded-xl bg-accent-electric text-white text-xs font-semibold hover:bg-blue-500 transition-colors"
            >
              {t.acceptAll}
            </button>
            <button
              onClick={rejectAll}
              className="flex-1 px-4 py-2.5 rounded-xl bg-white/[0.06] border border-white/[0.08] text-white/70 text-xs font-semibold hover:bg-white/[0.1] transition-colors"
            >
              {t.rejectAll}
            </button>
            <button
              onClick={() => showDetails ? saveSelection() : setShowDetails(true)}
              className="flex-1 px-4 py-2.5 rounded-xl bg-white/[0.06] border border-white/[0.08] text-white/70 text-xs font-semibold hover:bg-white/[0.1] transition-colors flex items-center justify-center gap-1.5"
            >
              {showDetails ? t.save : t.settings}
              {!showDetails && <ChevronDown className="w-3 h-3" />}
              {showDetails && <ChevronUp className="w-3 h-3" />}
            </button>
          </div>

          {/* Powered by */}
          <p className="text-center mt-3 text-[10px] text-white/20 font-mono">
            Consent managed by BreakPilot CMP
          </p>
        </div>
      </motion.div>
    </AnimatePresence>
  )
}
