/**
 * SEO utilities for domain pages and marketplace listings
 */

import { SITE_URL } from '@/lib/seo'

const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || SITE_URL

export interface DomainListing {
  domain: string
  price: number
  priceType: 'fixed' | 'minimum' | 'make_offer'
  description?: string
  seller?: string
  views?: number
  featured?: boolean
  createdAt?: string
  category?: string
  tags?: string[]
}

/**
 * Generate rich snippets for domain listing
 */
export function generateDomainListingSchema(listing: DomainListing) {
  const baseSchema = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: listing.domain,
    description: listing.description || `Premium domain name ${listing.domain} for sale`,
    category: listing.category || 'Domain Names',
    brand: {
      '@type': 'Brand',
      name: 'Pounce Marketplace',
    },
    sku: listing.domain.replace(/\./g, '-'),
    image: `${siteUrl}/api/og/domain?domain=${encodeURIComponent(listing.domain)}&price=${listing.price}`,
    url: `${siteUrl}/buy/${encodeURIComponent(listing.domain.replace(/\./g, '-'))}`,
  }

  // Offer details
  const offer: any = {
    '@type': 'Offer',
    priceCurrency: 'USD',
    seller: {
      '@type': listing.seller ? 'Person' : 'Organization',
      name: listing.seller || 'Pounce',
    },
    availability: 'https://schema.org/InStock',
    url: `${siteUrl}/buy/${encodeURIComponent(listing.domain.replace(/\./g, '-'))}`,
  }

  // Price based on type
  if (listing.priceType === 'fixed') {
    offer.price = listing.price.toFixed(2)
  } else if (listing.priceType === 'minimum') {
    offer.price = listing.price.toFixed(2)
    offer.priceSpecification = {
      '@type': 'PriceSpecification',
      price: listing.price.toFixed(2),
      priceCurrency: 'USD',
      minPrice: listing.price.toFixed(2),
    }
  } else {
    // Make offer
    offer.priceSpecification = {
      '@type': 'PriceSpecification',
      priceCurrency: 'USD',
      valueAddedTaxIncluded: false,
    }
  }

  return {
    ...baseSchema,
    offers: offer,
  }
}

/**
 * Generate metadata for domain listing page
 */
export function generateDomainMetadata(listing: DomainListing) {
  const priceText =
    listing.priceType === 'fixed'
      ? `$${listing.price.toFixed(2)}`
      : listing.priceType === 'minimum'
      ? `Starting at $${listing.price.toFixed(2)}`
      : 'Make an Offer'

  const title = `${listing.domain} - ${priceText} | Premium Domain for Sale`
  const description =
    listing.description ||
    `Buy ${listing.domain} premium domain name. ${priceText}. Secure instant transfer. 0% commission marketplace.${
      listing.featured ? ' ⭐ Featured listing.' : ''
    }`

  return {
    title,
    description,
    keywords: [
      listing.domain,
      `buy ${listing.domain}`,
      `${listing.domain} for sale`,
      'premium domain',
      'domain marketplace',
      'buy domain name',
      ...(listing.tags || []),
    ],
    openGraph: {
      title,
      description,
      url: `${siteUrl}/buy/${encodeURIComponent(listing.domain.replace(/\./g, '-'))}`,
      type: 'product' as const,
      images: [
        {
          url: `${siteUrl}/api/og/domain?domain=${encodeURIComponent(listing.domain)}&price=${listing.price}`,
          width: 1200,
          height: 630,
          alt: `${listing.domain} - Premium Domain`,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image' as const,
      title,
      description,
      images: [`${siteUrl}/api/og/domain?domain=${encodeURIComponent(listing.domain)}&price=${listing.price}`],
    },
  }
}

/**
 * Generate breadcrumb for domain page
 */
export function generateDomainBreadcrumb(domain: string, category?: string) {
  const items = [
    { name: 'Home', url: '/' },
    { name: 'Market', url: '/market' },
  ]

  if (category) {
    items.push({ name: category, url: `/market?category=${encodeURIComponent(category)}` })
  }

  // Public listing pages are keyed by listing slug; we keep breadcrumb URL generic here.
  items.push({ name: domain, url: `/buy/${encodeURIComponent(domain.replace(/\./g, '-'))}` })

  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.name,
      item: `${siteUrl}${item.url}`,
    })),
  }
}

/**
 * Generate FAQ schema for domain buying process
 */
export function generateDomainFAQSchema(domain: string) {
  return {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: [
      {
        '@type': 'Question',
        name: `How do I buy ${domain}?`,
        acceptedAnswer: {
          '@type': 'Answer',
          text: `To purchase ${domain}, click the "Buy Now" button, complete the secure payment, and the domain will be transferred to your registrar account within 24-48 hours.`,
        },
      },
      {
        '@type': 'Question',
        name: 'Is the transfer process secure?',
        acceptedAnswer: {
          '@type': 'Answer',
          text: 'Yes! All transactions are processed through secure payment gateways. The domain is held in escrow until payment is confirmed, ensuring a safe transfer for both parties.',
        },
      },
      {
        '@type': 'Question',
        name: 'Are there any additional fees?',
        acceptedAnswer: {
          '@type': 'Answer',
          text: 'No! Pounce charges 0% commission. The listed price is the final price. You may need to pay your registrar\'s annual renewal fee after the first year.',
        },
      },
      {
        '@type': 'Question',
        name: 'Can I negotiate the price?',
        acceptedAnswer: {
          '@type': 'Answer',
          text: 'For "Make an Offer" listings, yes! Submit your offer through the listing page. For fixed-price listings, the price is firm.',
        },
      },
      {
        '@type': 'Question',
        name: 'What happens after I purchase?',
        acceptedAnswer: {
          '@type': 'Answer',
          text: 'After payment confirmation, the seller will initiate the domain transfer. You\'ll receive transfer instructions via email. The entire process typically completes within 24-48 hours.',
        },
      },
    ],
  }
}

/**
 * Extract domain components for SEO
 */
export function analyzeDomainSEO(domain: string) {
  const parts = domain.split('.')
  const sld = parts[0] // Second-level domain
  const tld = parts.slice(1).join('.') // TLD (supports multi-level like .co.uk)

  const length = sld.length
  const hasNumbers = /\d/.test(sld)
  const hasHyphens = /-/.test(sld)
  const isShort = length <= 6
  const isPremium = isShort && !hasNumbers && !hasHyphens

  const keywords = sld.split(/[-_]/).filter(Boolean)

  return {
    sld,
    tld,
    length,
    hasNumbers,
    hasHyphens,
    isShort,
    isPremium,
    keywords,
    score: calculateDomainScore(domain),
  }
}

/**
 * Calculate domain quality score for SEO
 */
function calculateDomainScore(domain: string): number {
  const { length, hasNumbers, hasHyphens, tld } = analyzeDomainSEO(domain)

  let score = 100

  // Length penalty
  if (length > 15) score -= 20
  else if (length > 10) score -= 10
  else if (length <= 5) score += 10

  // Character penalties
  if (hasNumbers) score -= 15
  if (hasHyphens) score -= 10

  // TLD bonus
  const premiumTLDs = ['com', 'net', 'org', 'io', 'ai', 'co']
  if (premiumTLDs.includes(tld)) score += 15

  return Math.max(0, Math.min(100, score))
}

/**
 * Generate SEO-friendly domain title
 */
export function generateDomainTitle(domain: string, includeContext: boolean = true): string {
  const { isPremium, isShort, tld } = analyzeDomainSEO(domain)

  const qualifiers = []
  if (isPremium) qualifiers.push('Premium')
  if (isShort) qualifiers.push('Short')

  const qualifierText = qualifiers.length > 0 ? `${qualifiers.join(' ')} ` : ''

  return includeContext
    ? `${domain} - ${qualifierText}.${tld.toUpperCase()} Domain for Sale`
    : domain
}

/**
 * Generate domain description for SEO
 */
export function generateDomainDescription(listing: DomainListing): string {
  const { isPremium, isShort, keywords } = analyzeDomainSEO(listing.domain)

  const qualities = []
  if (isPremium) qualities.push('premium quality')
  if (isShort) qualities.push('memorable and short')
  if (!listing.domain.includes('-') && !listing.domain.includes('_')) qualities.push('brandable')

  const qualityText = qualities.length > 0 ? `This ${qualities.join(', ')} domain ` : 'This domain '

  const useCase =
    keywords.length > 0
      ? `Perfect for ${keywords.join(', ')} related businesses, startups, or branding projects.`
      : 'Perfect for startups, businesses, or branding projects.'

  return `${qualityText}is available for purchase. ${useCase} Secure instant transfer. 0% marketplace commission. ${
    listing.priceType === 'fixed' ? `Buy now for $${listing.price.toFixed(2)}` : 'Make an offer today'
  }.`
}

