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 { Breadcrumbs } from "@/components/breadcrumbs"
import { PublicPageHeader, PublicSurface } from "@/components/public-surface"
import type { Metadata } from "next"

const WORDPRESS_SLUG = "best-vending-machine-supplier-in-salt-lake-city-utah"
const DISPLAY_TITLE =
  "The Best Vending Machine Supplier in Salt Lake City, Utah"
const DISPLAY_DESCRIPTION =
  "A closer look at how Rocky Mountain Vending supports Utah businesses with free placement, machine sales, repairs, manuals, and responsive local service."

function stripLeadingH1(html: string) {
  return html.replace(/<h1[^>]*>[\s\S]*?<\/h1>/i, "")
}

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

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

  return generateSEOMetadata({
    title: DISPLAY_TITLE,
    description: page.seoDescription || page.excerpt || "",
    excerpt: page.excerpt,
    date: page.date,
    modified: page.modified,
    image: page.images?.[0]?.localPath,
    path: "/blog/best-vending-machine-supplier-in-salt-lake-city-utah",
  })
}

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

    if (!page) {
      notFound()
    }

    let imageMapping: any = {}
    try {
      imageMapping = loadImageMapping()
    } catch (e) {
      imageMapping = {}
    }

    const content = page.content ? (
      <div className="max-w-none">
        {cleanWordPressContent(stripLeadingH1(String(page.content)), {
          imageMapping,
          pageTitle: DISPLAY_TITLE,
          prioritizeFirstImage: true,
        })}
      </div>
    ) : (
      <p className="text-muted-foreground">No content available.</p>
    )

    let structuredData
    try {
      structuredData = generateStructuredData({
        title: DISPLAY_TITLE,
        description: page.seoDescription || page.excerpt || "",
        url:
          page.link ||
          page.urlPath ||
          `https://rockymountainvending.com/best-vending-machine-supplier-in-salt-lake-city-utah/`,
        datePublished: page.date,
        dateModified: page.modified || page.date,
        type: "WebPage",
      })
    } catch (e) {
      structuredData = {
        "@context": "https://schema.org",
        "@type": "WebPage",
        headline: DISPLAY_TITLE,
        description: page.seoDescription || "",
        url: `https://rockymountainvending.com/best-vending-machine-supplier-in-salt-lake-city-utah/`,
      }
    }

    return (
      <>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
        />
        <Breadcrumbs
          className="container mx-auto max-w-6xl px-4 pt-6"
          items={[
            { label: "Blog", href: "/blog" },
            {
              label: DISPLAY_TITLE,
              href: "/blog/best-vending-machine-supplier-in-salt-lake-city-utah",
            },
          ]}
        />
        <article className="container mx-auto max-w-6xl px-4 py-8 md:py-12">
          <PublicSurface className="space-y-8 md:space-y-10">
            <PublicPageHeader
              eyebrow="Rocky Journal"
              title={DISPLAY_TITLE}
              description={DISPLAY_DESCRIPTION}
            />
            <div className="prose prose-stone max-w-none prose-headings:font-semibold prose-headings:text-foreground prose-p:text-muted-foreground prose-li:text-muted-foreground">
              {content}
            </div>
          </PublicSurface>
        </article>
      </>
    )
  } catch (error) {
    if (process.env.NODE_ENV === "development") {
      console.error(
        "Error rendering Best Vending Machine Supplier page:",
        error
      )
    }
    notFound()
  }
}
