import { NextRequest, NextResponse } from 'next/server'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const url = searchParams.get('url')

    if (!url) {
      return NextResponse.json(
        { success: false, error: 'URL is required' },
        { status: 400 }
      )
    }

    // Add protocol if missing
    let fullUrl = url
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      fullUrl = 'https://' + url
    }

    // Parse domain
    const urlObj = new URL(fullUrl)
    const domain = urlObj.hostname
    const origin = urlObj.origin

    // Try multiple methods to get favicon
    const faviconUrls: string[] = []

    // Special handling for known domains
    const knownFavicons: Record<string, string> = {
      'docs.google.com': 'https://ssl.gstatic.com/docs/documents/images/kix-favicon7.ico',
      'drive.google.com': 'https://ssl.gstatic.com/images/branding/product/2x/drive_2020q4_48dp.png',
      'sheets.google.com': 'https://ssl.gstatic.com/docs/spreadsheets/favicon3.ico',
      'slides.google.com': 'https://ssl.gstatic.com/docs/presentations/images/favicon5.ico',
      'forms.google.com': 'https://ssl.gstatic.com/docs/spreadsheets/forms/favicon_qp2.png',
      'calendar.google.com': 'https://ssl.gstatic.com/calendar/images/dynamiclogo_2020q4/calendar_31_2x.png',
      'meet.google.com': 'https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v1/web-96dp/logo_meet_2020q4_color_2x_web_96dp.png',
      'mail.google.com': 'https://ssl.gstatic.com/ui/v1/icons/mail/rfr/gmail.ico',
      'youtube.com': 'https://www.youtube.com/s/desktop/your_icon_path/img/favicon_144x144.png',
      'www.youtube.com': 'https://www.youtube.com/s/desktop/your_icon_path/img/favicon_144x144.png',
      'github.com': 'https://github.githubassets.com/favicons/favicon.svg',
      'www.github.com': 'https://github.githubassets.com/favicons/favicon.svg',
      'twitter.com': 'https://abs.twimg.com/favicons/twitter.2.ico',
      'x.com': 'https://abs.twimg.com/favicons/twitter.2.ico',
      'facebook.com': 'https://static.xx.fbcdn.net/rsrc.php/yD/r/d4ZBER11xfB.ico',
      'www.facebook.com': 'https://static.xx.fbcdn.net/rsrc.php/yD/r/d4ZBER11xfB.ico',
      'instagram.com': 'https://static.cdninstagram.com/rsrc.php/v3/yI/r/VsNE-OHk_8a.png',
      'www.instagram.com': 'https://static.cdninstagram.com/rsrc.php/v3/yI/r/VsNE-OHk_8a.png',
      'linkedin.com': 'https://static.licdn.com/aero-v1/sc/h/akt4ae504epesldzj74dzred8',
      'www.linkedin.com': 'https://static.licdn.com/aero-v1/sc/h/akt4ae504epesldzj74dzred8',
      'wa.me': 'https://static.whatsapp.net/rsrc.php/v3/yP/r/rYZqPCBaG70.png',
      'whatsapp.com': 'https://static.whatsapp.net/rsrc.php/v3/yP/r/rYZqPCBaG70.png',
      'www.whatsapp.com': 'https://static.whatsapp.net/rsrc.php/v3/yP/r/rYZqPCBaG70.png',
      'tiktok.com': 'https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/tiktok/webapp/main/webapp-desktop/8152caf0c8e8bc67ae0d.png',
      'www.tiktok.com': 'https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/tiktok/webapp/main/webapp-desktop/8152caf0c8e8bc67ae0d.png',
    }

    // Check if domain matches known favicons
    if (knownFavicons[domain]) {
      faviconUrls.push(knownFavicons[domain])
    }

    // Method 1: Fetch HTML and parse <link rel="icon">
    try {
      const response = await fetch(fullUrl, {
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        },
        signal: AbortSignal.timeout(5000), // 5 second timeout
      })

      if (response.ok) {
        const html = await response.text()

        // Find all possible favicon link tags
        const iconRegexes = [
          /<link[^>]*rel=["']shortcut icon["'][^>]*href=["']([^"']+)["']/i,
          /<link[^>]*rel=["']icon["'][^>]*href=["']([^"']+)["']/i,
          /<link[^>]*href=["']([^"']+)["'][^>]*rel=["']shortcut icon["']/i,
          /<link[^>]*href=["']([^"']+)["'][^>]*rel=["']icon["']/i,
          /<link[^>]*rel=["']apple-touch-icon["'][^>]*href=["']([^"']+)["']/i,
        ]

        for (const regex of iconRegexes) {
          const match = html.match(regex)
          if (match && match[1]) {
            let faviconUrl = match[1]

            // Handle relative URLs
            if (faviconUrl.startsWith('//')) {
              faviconUrl = 'https:' + faviconUrl
            } else if (faviconUrl.startsWith('/')) {
              faviconUrl = origin + faviconUrl
            } else if (!faviconUrl.startsWith('http')) {
              faviconUrl = origin + '/' + faviconUrl
            }

            faviconUrls.push(faviconUrl)
          }
        }
      }
    } catch (e) {
      console.error('Error fetching HTML:', e)
    }

    // Method 2: Common favicon locations
    faviconUrls.push(`${origin}/favicon.ico`)
    faviconUrls.push(`${origin}/favicon.png`)
    faviconUrls.push(`${origin}/apple-touch-icon.png`)

    // Method 3: External favicon services as final fallback
    faviconUrls.push(`https://www.google.com/s2/favicons?domain=${domain}&sz=128`)
    faviconUrls.push(`https://icons.duckduckgo.com/ip3/${domain}.ico`)
    faviconUrls.push(`https://favicons.githubusercontent.com/${domain}`)

    // Return the list of possible favicon URLs
    return NextResponse.json({
      success: true,
      faviconUrls: [...new Set(faviconUrls)], // Remove duplicates
      domain,
    })
  } catch (error) {
    console.error('Favicon API error:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to get favicon' },
      { status: 500 }
    )
  }
}
