import { notFound } from 'next/navigation'
import { loadImageMapping } from '@/lib/wordpress-content'
import { generateSEOMetadata, generateStructuredData } from '@/lib/seo'
import { getPageBySlug } from '@/lib/wordpress-data-loader'
import { cleanWordPressContent } from '@/lib/clean-wordPress-content'
import type { Metadata } from 'next'
import { PublicPageHeader, PublicSurface } from '@/components/public-surface'
import { RequestMachineForm } from '@/components/forms/request-machine-form'

const WORDPRESS_SLUG = 'vending-machines-for-sale-in-utah'

export async function generateMetadata(): Promise<Metadata> {
  const page = getPageBySlug(WORDPRESS_SLUG)

  if (!page) {
    return {
      title: 'Page Not Found | Rocky Mountain Vending',
    }
  }

  return generateSEOMetadata({
    title: page.title || 'Vending Machines for Sale in Utah',
    description: page.seoDescription || page.excerpt || '',
    excerpt: page.excerpt,
    date: page.date,
    modified: page.modified,
    image: page.images?.[0]?.localPath,
  })
}

export default async function MachinesForSalePage() {
  try {
    const page = getPageBySlug(WORDPRESS_SLUG)

    if (!page) {
      notFound()
    }

    let imageMapping: Record<string, string> = {}
    try {
      imageMapping = loadImageMapping()
    } catch {
      imageMapping = {}
    }

    const structuredData = (() => {
      try {
        return generateStructuredData({
          title: page.title || 'Vending Machines for Sale in Utah',
          description: page.seoDescription || page.excerpt || '',
          url: page.link || page.urlPath || 'https://rockymountainvending.com/vending-machines/machines-for-sale/',
          datePublished: page.date,
          dateModified: page.modified || page.date,
          type: 'WebPage',
        })
      } catch {
        return {
          '@context': 'https://schema.org',
          '@type': 'WebPage',
          headline: page.title || 'Vending Machines for Sale in Utah',
          description: page.seoDescription || '',
          url: 'https://rockymountainvending.com/vending-machines/machines-for-sale/',
        }
      }
    })()

    return (
      <>
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }} />
        <div className="container mx-auto px-4 py-10 md:py-14">
          <PublicPageHeader
            eyebrow="Machine Sales"
            title={page.title || 'Vending Machines for Sale in Utah'}
            description="If you need help comparing machine options, payment hardware, or support paths, this page now keeps the same clean Rocky Mountain Vending styling as the rest of the site."
          />

          <PublicSurface className="mt-10">
            <div className="max-w-none">{cleanWordPressContent(String(page.content || ''), { imageMapping, pageTitle: page.title })}</div>
          </PublicSurface>

          <section className="mt-12 grid gap-6 lg:grid-cols-[0.95fr_1.05fr]">
            <PublicSurface>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-primary/80">Free Placement</p>
              <h2 className="mt-3 text-3xl font-semibold tracking-tight text-balance">Need a free machine instead of buying one?</h2>
              <p className="mt-3 text-base leading-relaxed text-muted-foreground">
                If you&apos;re a business looking for placement rather than a purchase, use the request form here and we&apos;ll help you sort out the right next step.
              </p>
            </PublicSurface>
            <PublicSurface>
              <RequestMachineForm />
            </PublicSurface>
          </section>
        </div>
      </>
    )
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.error('Error rendering Machines for Sale page:', error)
    }
    notFound()
  }
}
