import { headers } from 'next/headers'
import { DownloadPage, type DownloadDevice } from '@/components/downloadpage'

type DownloadPageProps = {
  searchParams: Promise<Record<string, string | string[] | undefined>>
}

function detectDeviceFromHeaders(userAgent: string, clientPlatform: string): DownloadDevice {
  const combined = `${userAgent} ${clientPlatform}`

  if (/Android/i.test(combined)) return 'android'
  if (/iPhone|iPad|iPod/i.test(userAgent)) return 'ios'
  if (/Windows NT|Macintosh|MacIntel|CrOS|X11|Linux x86_64/i.test(combined)) return 'desktop'

  return 'other'
}

export default async function Page({ searchParams }: DownloadPageProps) {
  const [requestHeaders, params] = await Promise.all([headers(), searchParams])
  const userAgent = requestHeaders.get('user-agent') || ''
  const clientPlatform = requestHeaders.get('sec-ch-ua-platform') || ''
  const initialDevice = detectDeviceFromHeaders(userAgent, clientPlatform)
  const manualMode = Object.prototype.hasOwnProperty.call(params, 'manual') || Object.prototype.hasOwnProperty.call(params, 'debug')

  return <DownloadPage initialDevice={initialDevice} manualMode={manualMode} />
}
