import { notFound } from 'next/navigation';
import Script from 'next/script';
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';

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: any = {};
    try {
      imageMapping = loadImageMapping();
    } catch (e) {
      imageMapping = {};
    }

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

    let structuredData;
    try {
      structuredData = 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 (e) {
      structuredData = {
        '@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) }}
        />
        <article className="container mx-auto px-4 py-8 md:py-12 max-w-4xl">
          <header className="mb-8">
            <h1 className="text-4xl md:text-5xl font-bold mb-6">{page.title || 'Vending Machines for Sale in Utah'}</h1>
          </header>
          {content}
        </article>

        {/* CRM Form */}
        <section className="mt-16">
          <Card className="border-border/50 hover:border-secondary/50 transition-colors">
            <CardContent className="p-8">
              <div className="text-center mb-6">
                <h3 className="text-2xl font-bold mb-2">Get Your Free Vending Machine</h3>
                <p className="text-muted-foreground">
                  Fill out the form below and we'll contact you within 24 hours to discuss your needs.
                </p>
              </div>
              <iframe
                src="https://link.sluice-box.io/widget/form/T76mIdPvC5iBwAI2wFPg"
                style={{ width: "100%", height: "650px", border: "none", borderRadius: "4px" }}
                id="inline-T76mIdPvC5iBwAI2wFPg"
                data-layout="{'id':'INLINE'}"
                data-trigger-type="alwaysShow"
                data-trigger-value=""
                data-activation-type="alwaysActivated"
                data-activation-value=""
                data-deactivation-type="neverDeactivate"
                data-deactivation-value=""
                data-form-name="Request Machine Short"
                data-height="638"
                data-layout-iframe-id="inline-T76mIdPvC5iBwAI2wFPg"
                data-form-id="T76mIdPvC5iBwAI2wFPg"
                title="Request Free Vending Machine Form"
              />
            </CardContent>
          </Card>
        </section>

        {/* Form Script */}
        <Script src="https://link.sluice-box.io/js/form_embed.js" strategy="afterInteractive" />
      </>
    );
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.error('Error rendering Machines for Sale page:', error);
    }
    notFound();
  }
}







