import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { cache } from 'react';
import { fetchPublic } from '@/lib/server-api';
import {
  FALLBACK_SERVICES_PAGE,
  SERVICES_PAGE_SLUG,
  normalizeServicesContent,
} from '@/lib/pages-content';
import type { SitePage } from '@/lib/types';

type LoadResult = SitePage | 'missing' | null;

/**
 * Carrega a página de serviços do CMS. `cache` deduplica a chamada entre
 * `generateMetadata` e a renderização dentro da mesma requisição.
 */
const loadServicesPage = cache(async (): Promise<LoadResult> => {
  const { status, data } = await fetchPublic<SitePage>(
    `/pages/${SERVICES_PAGE_SLUG}`,
  );
  if (status === 404) return 'missing';
  if (!data) return null; // falha de rede → conteúdo padrão
  return data;
});

export async function generateMetadata(): Promise<Metadata> {
  const result = await loadServicesPage();
  const page = result && result !== 'missing' ? result : FALLBACK_SERVICES_PAGE;
  return {
    title: page.metaTitle || page.title,
    description: page.metaDescription || page.subtitle || undefined,
  };
}

export default async function ServicosPage() {
  const result = await loadServicesPage();
  if (result === 'missing') notFound();

  const page = result ?? FALLBACK_SERVICES_PAGE;
  const content = normalizeServicesContent(page.content);

  return (
    <>
      <section className="df-hero text-center">
        <div className="container">
          <h1 className="display-5 fw-bold mb-3">{content.hero.title}</h1>
          <p className="lead mb-0 mx-auto" style={{ maxWidth: 720 }}>
            {content.hero.subtitle}
          </p>
        </div>
      </section>

      <section className="container py-5">
        <div className="row g-4">
          {content.services.map((service, index) => (
            <div
              className="col-md-6 col-lg-4"
              key={`${service.title}-${index}`}
            >
              <div className="card h-100 border-0 shadow-sm df-card-hover">
                <div className="card-body text-center p-4">
                  <i
                    className={`bi ${service.icon} display-5 text-primary mb-3 d-block`}
                  />
                  <h2 className="h5 card-title">{service.title}</h2>
                  {service.description && (
                    <p className="card-text text-muted small mb-0">
                      {service.description}
                    </p>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="bg-light py-5">
        <div className="container text-center">
          <h2 className="fw-bold mb-3">{content.cta.title}</h2>
          <p className="text-muted mb-4 mx-auto" style={{ maxWidth: 560 }}>
            {content.cta.text}
          </p>
          {content.cta.buttonHref.startsWith('/') ? (
            <Link href={content.cta.buttonHref} className="btn btn-primary btn-lg px-4">
              {content.cta.buttonLabel}
            </Link>
          ) : (
            <a
              href={content.cta.buttonHref}
              className="btn btn-primary btn-lg px-4"
            >
              {content.cta.buttonLabel}
            </a>
          )}
        </div>
      </section>
    </>
  );
}
