import Link from "next/link";
import Icon from "./Icon";
import JsonLd from "./JsonLd";
import {
  getServicesByCategory,
  type Service,
  type ServiceCategory,
} from "@/lib/services";

const SITE = "https://socialex.pro";

const categoryConfig: Record<
  ServiceCategory,
  {
    listHref: string;
    listLabel: string;
    eyebrow: string;
    breadcrumb: string;
    voirTout: string;
  }
> = {
  societes: {
    listHref: "/societes",
    listLabel: "Retour aux Sociétés",
    eyebrow: "Droit des Sociétés",
    breadcrumb: "Sociétés",
    voirTout: "Tous les services Sociétés",
  },
  marques: {
    listHref: "/marques",
    listLabel: "Retour aux Marques",
    eyebrow: "Droit des Marques",
    breadcrumb: "Marques",
    voirTout: "Tous les services Marques",
  },
};

/* Méthode générique pour les modifications statutaires.
   Les services bespoke (création, dépôt comptes, dissolution, dépôt marque)
   ont leur propre page avec leur propre méthodologie. */
const defaultSteps = [
  {
    n: "01",
    t: "Audit de l'opération",
    d: "Vérification des statuts en vigueur, identification des contraintes et choix du formalisme adapté à la forme sociale.",
  },
  {
    n: "02",
    t: "Décision et procès-verbal",
    d: "Convocation de l'assemblée si requise, rédaction du procès-verbal et de la décision conforme aux statuts.",
  },
  {
    n: "03",
    t: "Mise à jour des statuts",
    d: "Refonte ou amendement des statuts, mise en cohérence avec la décision adoptée.",
  },
  {
    n: "04",
    t: "Annonce légale et déclaration au greffe",
    d: "Publication de l'annonce légale dans un journal habilité et déclaration de modification au RCS.",
  },
  {
    n: "05",
    t: "Mise à jour du K-bis et des registres",
    d: "Réception du K-bis modifié, mise à jour du registre des décisions.",
  },
];

export default function ServiceDetail({ service }: { service: Service }) {
  const cfg = categoryConfig[service.category];
  const others = getServicesByCategory(service.category)
    .filter((s) => s.slug !== service.slug)
    .slice(0, 3);

  const pagePath = `${cfg.listHref}/${service.slug}`;
  const pageUrl = `${SITE}${pagePath}`;

  /* JSON-LD */
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Accueil", item: SITE },
      {
        "@type": "ListItem",
        position: 2,
        name: cfg.breadcrumb,
        item: `${SITE}${cfg.listHref}`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: service.title,
        item: pageUrl,
      },
    ],
  };

  const serviceSchema = {
    "@context": "https://schema.org",
    "@type": "Service",
    name: service.title,
    serviceType: service.title,
    description: service.description,
    provider: {
      "@type": "LegalService",
      name: "Socialex",
      url: SITE,
    },
    areaServed: { "@type": "Country", name: "France" },
    url: pageUrl,
  };

  const faqSchema = service.faqs?.length
    ? {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: service.faqs.map((f) => ({
          "@type": "Question",
          name: f.q,
          acceptedAnswer: { "@type": "Answer", text: f.a },
        })),
      }
    : null;

  return (
    <>
      <JsonLd
        data={faqSchema
          ? [breadcrumbSchema, serviceSchema, faqSchema]
          : [breadcrumbSchema, serviceSchema]}
      />

      {/* Hero */}
      <section className="pt-32 pb-24 md:pb-32">
        <div className="container-page">
          <nav
            aria-label="Fil d'ariane"
            className="flex items-center gap-2 text-xs uppercase tracking-widest text-on-surface-variant mb-12 font-serif"
          >
            <Link href="/" className="hover:text-primary transition-colors">
              Accueil
            </Link>
            <span className="opacity-50">/</span>
            <Link
              href={cfg.listHref}
              className="hover:text-primary transition-colors"
            >
              {cfg.breadcrumb}
            </Link>
            <span className="opacity-50">/</span>
            <span className="text-primary">{service.title}</span>
          </nav>

          <div className="grid grid-cols-12 gap-8 lg:gap-16 items-start">
            <div className="col-span-12 lg:col-span-7 space-y-8 reveal-hero">
              <Icon name={service.icon} className="!text-5xl text-secondary" />
              <span className="eyebrow block">{cfg.eyebrow}</span>
              <h1 className="display-lg text-primary">{service.title}</h1>
              <p className="body-lg text-on-surface-variant">
                {service.description}
              </p>
              <div className="flex flex-wrap gap-3 pt-4">
                <Link href={`${pagePath}/formulaire`} className="btn btn-primary">
                  Démarrer mon dossier
                </Link>
                <Link href={cfg.listHref} className="btn btn-secondary">
                  Autres services
                </Link>
              </div>
            </div>

            <aside className="col-span-12 lg:col-span-5 lg:sticky lg:top-32">
              <div className="bg-white border border-outline-variant p-10">
                <p className="eyebrow mb-6">Ce qui est inclus</p>
                <ul className="space-y-3">
                  {service.highlights.map((h) => (
                    <li
                      key={h}
                      className="flex items-start gap-3 body-md text-on-surface"
                    >
                      <Icon
                        name="check_circle"
                        className="!text-base text-secondary mt-1"
                      />
                      <span>{h}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </aside>
          </div>
        </div>
      </section>

      {/* Seuils (optionnel, ex: nomination CAC, dépôt comptes confidentiel) */}
      {service.thresholds && (
        <section className="reveal">
          <div className="container-page py-24 md:py-32">
            <div className="max-w-3xl mb-20">
              <span className="eyebrow block mb-4">
                {service.thresholds.eyebrow}
              </span>
              <h2 className="headline-xl text-primary mb-6">
                {service.thresholds.title}
              </h2>
              <p className="body-lg text-on-surface-variant">
                {service.thresholds.intro}
              </p>
            </div>

            <div className="bg-white border border-outline-variant overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-outline-variant/60 text-left">
                    <th className="font-serif italic text-secondary p-6">
                      Catégorie
                    </th>
                    <th className="eyebrow !text-on-surface-variant p-6">
                      Bilan
                    </th>
                    <th className="eyebrow !text-on-surface-variant p-6">
                      CA HT
                    </th>
                    <th className="eyebrow !text-on-surface-variant p-6">
                      Effectif
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {service.thresholds.rows.map((r) => (
                    <tr
                      key={r.category}
                      className="border-b border-outline-variant/40 last:border-b-0"
                    >
                      <td className="font-serif text-primary text-lg p-6">
                        {r.category}
                      </td>
                      <td className="text-on-surface p-6">{r.bilan}</td>
                      <td className="text-on-surface p-6">{r.ca}</td>
                      <td className="text-on-surface p-6">{r.effectif}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {service.thresholds.footer && (
              <p className="mt-8 body-md text-on-surface-variant max-w-3xl">
                {service.thresholds.footer}
              </p>
            )}
          </div>
        </section>
      )}

      {/* Méthodologie */}
      <section className="bg-surface-container-low reveal">
        <div className="container-page py-24 md:py-32">
          <div className="max-w-3xl mb-20">
            <span className="eyebrow block mb-4">Notre méthodologie</span>
            <h2 className="headline-xl text-primary mb-6">
              De l'audit initial
              <br />
              <span className="italic font-normal">à la mise à jour du K-bis.</span>
            </h2>
            <p className="body-lg text-on-surface-variant">
              Une procédure structurée, traçable et sécurisée. Vous savez à
              chaque instant où en est votre dossier.
            </p>
          </div>
          <ol className="space-y-0 border-t border-outline-variant/60">
            {(service.steps ?? defaultSteps).map((s) => (
              <li
                key={s.n}
                className="grid grid-cols-12 gap-6 py-10 border-b border-outline-variant/60"
              >
                <div className="col-span-12 md:col-span-2">
                  <p className="font-serif italic text-secondary text-3xl">
                    {s.n}
                  </p>
                </div>
                <div className="col-span-12 md:col-span-10 space-y-3">
                  <h3 className="headline-md !text-xl text-primary">
                    {s.t}
                  </h3>
                  <p className="body-md text-on-surface-variant">{s.d}</p>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* Tarif */}
      <section className="reveal">
        <div className="container-page py-24 md:py-32">
          <div className="max-w-4xl mx-auto bg-primary text-on-primary p-12 md:p-16 lg:p-20 text-center">
            <span className="eyebrow !text-secondary block mb-4">
              Tarif transparent
            </span>
            <h2 className="display-lg !text-3xl md:!text-4xl mb-8">
              Combien coûte cette formalité ?
            </h2>
            {service.priceEur != null && (
              <p className="font-serif font-medium leading-none mb-4 text-6xl md:text-7xl lg:text-8xl tracking-[-0.02em] text-secondary">
                {service.priceEur.toLocaleString("fr-FR")} €
              </p>
            )}
            <p className="body-md opacity-70 max-w-xl mx-auto mb-10">
              {service.priceNote ??
                "Frais externes inclus. Aucun coût caché, aucune facturation à l'heure."}
            </p>
            <div className="flex justify-center">
              <Link href={`${pagePath}/formulaire`} className="btn btn-light">
                Démarrer mon dossier
              </Link>
            </div>
            <p className="text-xs uppercase tracking-widest opacity-60 mt-8 font-serif">
              Réponse sous 24 h ouvrées · Sans engagement
            </p>
          </div>
        </div>
      </section>

      {/* FAQ — uniquement si service-specific */}
      {service.faqs && service.faqs.length > 0 && (
        <section className="bg-surface-container-low reveal">
          <div className="container-page py-24 md:py-32">
            <div className="grid grid-cols-12 gap-12">
              <div className="col-span-12 lg:col-span-4">
                <span className="eyebrow block mb-4">Questions fréquentes</span>
                <h2 className="headline-xl text-primary mb-6">
                  Les vraies questions.
                  <br />
                  <span className="italic font-normal">
                    Les vraies réponses.
                  </span>
                </h2>
                <p className="body-md text-on-surface-variant">
                  Une question manque ?{" "}
                  <Link
                    href="/contact"
                    className="text-primary underline hover:text-secondary"
                  >
                    Contactez-nous
                  </Link>
                  , réponse sous 24 h ouvrées.
                </p>
              </div>
              <div className="col-span-12 lg:col-span-8">
                {service.faqs.map((f, i) => (
                  <details
                    key={f.q}
                    className="group border-b border-outline-variant/60 py-6"
                  >
                    <summary className="flex items-baseline gap-6 list-none cursor-pointer">
                      <span className="font-serif italic text-secondary text-sm w-8 shrink-0">
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span className="flex-1 font-serif text-xl md:text-2xl text-primary tracking-[-0.01em] leading-tight">
                        {f.q}
                      </span>
                      <span className="text-xl text-on-surface-variant group-open:rotate-45 transition-transform shrink-0">
                        +
                      </span>
                    </summary>
                    <p className="mt-6 ml-14 body-md text-on-surface-variant max-w-3xl">
                      {f.a}
                    </p>
                  </details>
                ))}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Cross-links */}
      {others.length > 0 && (
        <section className="reveal">
          <div className="container-page py-24 md:py-32">
            <div className="flex items-end justify-between mb-12 flex-wrap gap-6">
              <h2 className="headline-xl text-primary">
                Continuer en {cfg.eyebrow.toLowerCase()}
              </h2>
              <Link
                href={cfg.listHref}
                className="font-serif text-sm tracking-wide uppercase border-b border-primary pb-1 hover:text-secondary hover:border-secondary transition-colors"
              >
                {cfg.voirTout}
              </Link>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 lg:gap-8">
              {others.map((s) => (
                <Link
                  key={s.slug}
                  href={`${cfg.listHref}/${s.slug}`}
                  className="group bg-white border border-outline-variant p-8 hover:border-primary transition-colors duration-500"
                >
                  <Icon name={s.icon} className="!text-3xl text-primary mb-6" />
                  <h3 className="font-serif font-medium text-xl text-primary mb-3 group-hover:text-secondary transition-colors">
                    {s.title}
                  </h3>
                  <p className="body-md text-on-surface-variant">
                    {s.excerpt}
                  </p>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* CTA final */}
      <section className="bg-primary text-on-primary reveal">
        <div className="container-page py-24 md:py-28 text-center">
          <div className="max-w-3xl mx-auto space-y-8">
            <h2 className="display-lg !text-4xl md:!text-5xl">
              Avancez sereinement sur votre dossier.
            </h2>
            <p className="body-lg opacity-70">
              Forfait clair, suivi en temps réel, réponse sous 24 h ouvrées.
            </p>
            <Link href="/contact" className="btn btn-light">
              Contacter nos experts
            </Link>
          </div>
        </div>
      </section>
    </>
  );
}
