import Link from "next/link";
import { Fragment } from "react";
import type { CSSProperties, ReactNode } from "react";

import { Button } from "@/components/ui/button";
import { Container } from "@/components/ui/container";
import { SectionHead } from "@/components/ui/section-head";

import { CountUp } from "./_components/count-up";
import { Faq } from "./_components/faq";
import { Reveal } from "./_components/reveal";
import styles from "./service-landing.module.css";

/* ----------------------------------------------------------------
   Shared service-landing template.
   Renders the full service page (hero + audit card, trust bar,
   problems, deliverables, animated process bento, count-up results,
   testimonials, FAQ, CTA) from a typed ServiceContent model so every
   service page shares one design. Faithful to the wordpress-seo page
   the design was finalized on.
   ---------------------------------------------------------------- */

export type Metric = { lab: string; val: string; pill: string; warn?: boolean };
export type Chip = { letter: string; label: string; bg: string };
export type Problem = { title: string; desc: string; icon: ReactNode };
export type Deliverable = {
  span: "wide" | "third";
  icon: ReactNode;
  title: string;
  desc: string;
  bullets?: string[];
};
export type CodeToken = { cls?: "k" | "v" | "mut"; text: string };
export type Bar = { lab: string; w: number; good: string };
export type Step = {
  num: number;
  when: string;
  title: string;
  desc: string;
  viz: "radar" | "bars" | "code" | "graph" | "chart";
  bars?: Bar[];
  code?: CodeToken[][];
};
export type Result = {
  value: number;
  prefix?: string;
  suffix?: string;
  dec?: number;
  out?: string;
  grad?: boolean;
  label: string;
};
export type Testimonial = {
  quote: string;
  name: string;
  role: string;
  initials: string;
  bg: string;
};
export type QA = { q: string; a: string };

export type ServiceContent = {
  slug: string;
  hero: {
    pillBold: string;
    pillRest: string;
    titleLead: string;
    titleAccent: string;
    sub: string;
    notes: string[];
  };
  ctaPrimaryLabel: string;
  ctaGhostLabel: string;
  ctaGhostHref: string;
  auditCard: {
    url: string;
    score: string;
    heading: string;
    tag: string;
    metrics: Metric[];
    rows: [string, string][];
  };
  trust: { caption: string; chips: Chip[] };
  problems: {
    eyebrow: string;
    title: string;
    titleGrad: string;
    subtitle: string;
    items: Problem[];
  };
  deliverables: {
    eyebrow: string;
    title: string;
    titleGrad: string;
    subtitle: string;
    items: Deliverable[];
  };
  process: {
    eyebrow: string;
    title: string;
    titleGrad: string;
    subtitle: string;
    steps: Step[];
  };
  results: { eyebrow: string; title: string; items: Result[] };
  testimonials: {
    eyebrow: string;
    title: string;
    titleGrad: string;
    items: Testimonial[];
  };
  faq: { eyebrow: string; title: string; items: QA[] };
  cta: { title: string; sub: string; note: string };
};

/** Small check glyph reused across the hero notes and deliverable lists. */
function Check({ size = 15 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.6"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}

const arrow = (
  <svg
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2.4"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M5 12h14M13 6l6 6-6 6" />
  </svg>
);

/** One bento visualization, switched by step.viz. */
function Viz({ step }: { step: Step }) {
  switch (step.viz) {
    case "radar":
      return (
        <div className={`${styles.bviz} ${styles.vizRadar}`}>
          <div className={styles.radar}>
            <div className={styles.ring} />
            <div className={`${styles.ring} ${styles.r2}`} />
            <div className={`${styles.ring} ${styles.r3}`} />
            <div className={styles.cross} />
            <div className={`${styles.sweep} ${styles.anim}`} />
            <div
              className={`${styles.blip} ${styles.anim}`}
              style={{ left: "62%", top: "32%", animationDelay: "0s" }}
            />
            <div
              className={`${styles.blip} ${styles.anim}`}
              style={{ left: "34%", top: "58%", animationDelay: "1.2s" }}
            />
            <div
              className={`${styles.blip} ${styles.anim}`}
              style={{ left: "70%", top: "66%", animationDelay: "2.2s" }}
            />
          </div>
        </div>
      );
    case "bars":
      return (
        <div className={`${styles.bviz} ${styles.vizBars}`}>
          {(step.bars ?? []).map((b) => (
            <div key={b.lab} className={styles.vbar}>
              <span className={styles.vlab}>{b.lab}</span>
              <span className={styles.track}>
                <span
                  className={`${styles.fill} ${styles.anim}`}
                  style={{ "--w": b.w } as CSSProperties}
                />
              </span>
              <span className={styles.vgood}>{b.good}</span>
            </div>
          ))}
        </div>
      );
    case "code":
      return (
        <div className={`${styles.bviz} ${styles.vizCode}`}>
          {(step.code ?? []).map((line, li) => (
            <div key={li} className={`${styles.cl} ${styles.anim}`}>
              {line.map((tok, ti) =>
                tok.cls ? (
                  <span key={ti} className={styles[tok.cls]}>
                    {tok.text}
                  </span>
                ) : (
                  <Fragment key={ti}>{tok.text}</Fragment>
                ),
              )}
            </div>
          ))}
        </div>
      );
    case "graph":
      return (
        <div className={`${styles.bviz} ${styles.vizGraph}`}>
          <svg viewBox="0 0 220 96" fill="none" aria-hidden="true">
            <path
              className={`${styles.edge} ${styles.anim}`}
              d="M110 48 L40 24"
            />
            <path
              className={`${styles.edge} ${styles.anim} ${styles.e2}`}
              d="M110 48 L40 72"
            />
            <path
              className={`${styles.edge} ${styles.anim} ${styles.e3}`}
              d="M110 48 L186 26"
            />
            <path
              className={`${styles.edge} ${styles.anim} ${styles.e4}`}
              d="M110 48 L186 70"
            />
            <circle
              className={`${styles.node} ${styles.anim}`}
              cx="110"
              cy="48"
              r="11"
              fill="url(#bm)"
            />
            <circle
              className={`${styles.node} ${styles.anim} ${styles.n2}`}
              cx="40"
              cy="24"
              r="6"
              fill="#ff7a52"
            />
            <circle
              className={`${styles.node} ${styles.anim} ${styles.n3}`}
              cx="40"
              cy="72"
              r="6"
              fill="#2f95ff"
            />
            <circle
              className={`${styles.node} ${styles.anim} ${styles.n4}`}
              cx="186"
              cy="26"
              r="6"
              fill="#2f95ff"
            />
            <circle
              className={`${styles.node} ${styles.anim} ${styles.n5}`}
              cx="186"
              cy="70"
              r="6"
              fill="#ffce4a"
            />
          </svg>
        </div>
      );
    case "chart":
      return (
        <div className={`${styles.bviz} ${styles.vizChart}`}>
          <svg viewBox="0 0 220 96" fill="none" aria-hidden="true">
            <defs>
              <linearGradient
                id="trendg"
                x1="0"
                y1="0"
                x2="220"
                y2="0"
                gradientUnits="userSpaceOnUse"
              >
                <stop stopColor="#007BFF" />
                <stop offset="0.55" stopColor="#FF5722" />
                <stop offset="1" stopColor="#FBC02D" />
              </linearGradient>
              <linearGradient
                id="areag"
                x1="0"
                y1="0"
                x2="0"
                y2="96"
                gradientUnits="userSpaceOnUse"
              >
                <stop stopColor="#FF5722" stopOpacity="0.28" />
                <stop offset="1" stopColor="#FF5722" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path
              className={`${styles.area} ${styles.anim}`}
              d="M4 84 L44 76 L84 80 L124 54 L164 46 L208 16 L208 96 L4 96 Z"
              fill="url(#areag)"
            />
            <path
              className={`${styles.line} ${styles.anim}`}
              d="M4 84 L44 76 L84 80 L124 54 L164 46 L208 16"
            />
            <circle
              className={`${styles.tip} ${styles.anim}`}
              cx="208"
              cy="16"
              r="5"
              fill="#fff"
            />
            <circle
              className={`${styles.tip} ${styles.anim}`}
              cx="208"
              cy="16"
              r="9"
              fill="none"
              stroke="#FBC02D"
              strokeWidth="1.5"
            />
          </svg>
        </div>
      );
    default:
      return null;
  }
}

export function ServiceLanding({
  content,
  lang,
}: {
  content: ServiceContent;
  lang: string;
}) {
  const c = content;
  const contactHref = `/${lang}/contact`;
  let wideN = 0;
  let thirdN = 0;

  return (
    <div className={styles.page}>
      {/* Shared brand gradient referenced by SVG strokes/fills (url(#bm)). */}
      <svg
        width="0"
        height="0"
        aria-hidden="true"
        style={{ position: "absolute" }}
      >
        <defs>
          <linearGradient
            id="bm"
            x1="0"
            y1="1"
            x2="1"
            y2="0"
            gradientUnits="objectBoundingBox"
          >
            <stop stopColor="#007BFF" />
            <stop offset="0.55" stopColor="#FF5722" />
            <stop offset="1" stopColor="#FBC02D" />
          </linearGradient>
        </defs>
      </svg>

      {/* ============ HERO ============ */}
      <section className={styles.hero} id="top">
        <div className={styles.heroGlow} />
        <Container className={styles.heroInner}>
          <div className={styles.heroGrid}>
            <Reveal className={styles.reveal}>
              <span className={styles.heroPill}>
                <b>{c.hero.pillBold}</b> {c.hero.pillRest}
              </span>
              <h1 className={styles.heroTitle}>
                {c.hero.titleLead}{" "}
                <span className="text-gradient-brand">
                  {c.hero.titleAccent}
                </span>
              </h1>
              <p className={styles.heroSub}>{c.hero.sub}</p>
              <div className={styles.heroCta}>
                <Button asChild>
                  <Link href={contactHref}>
                    {c.ctaPrimaryLabel} {arrow}
                  </Link>
                </Button>
                <a href={c.ctaGhostHref} className={styles.btnGhost}>
                  {c.ctaGhostLabel}
                </a>
              </div>
              <p className={styles.heroNote}>
                {c.hero.notes.map((n) => (
                  <span key={n}>
                    <Check /> {n}
                  </span>
                ))}
              </p>
            </Reveal>

            {/* audit card */}
            <Reveal className={styles.reveal} delay={0.16}>
              <div className={styles.audit}>
                <div className={styles.auditBar}>
                  <div className={styles.u}>
                    <svg
                      width="12"
                      height="12"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    >
                      <rect x="3" y="3" width="18" height="18" rx="2" />
                      <path d="M3 9h18" />
                    </svg>
                    {c.auditCard.url}
                  </div>
                  <span className={styles.score}>{c.auditCard.score}</span>
                </div>
                <div className={styles.auditBody}>
                  <div className={styles.auditH}>
                    <h4>{c.auditCard.heading}</h4>
                    <span className={styles.tag}>{c.auditCard.tag}</span>
                  </div>
                  <div className={styles.cwvRow}>
                    {c.auditCard.metrics.map((m) => (
                      <div key={m.lab} className={styles.cwv}>
                        <div className={styles.lab}>{m.lab}</div>
                        <div className={styles.val}>{m.val}</div>
                        <span
                          className={`${styles.pill} ${m.warn ? styles.warn : styles.good}`}
                        >
                          {m.pill}
                        </span>
                      </div>
                    ))}
                  </div>
                  <div className={styles.auditList}>
                    {c.auditCard.rows.map(([txt, meta]) => (
                      <div key={txt} className={styles.row}>
                        <span className={styles.ck}>
                          <Check size={10} />
                        </span>
                        <span className={styles.txt}>{txt}</span>
                        <span className={styles.meta}>{meta}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </Reveal>
          </div>
        </Container>
      </section>

      {/* ============ TRUST ============ */}
      <section className={styles.trust}>
        <Reveal className={styles.reveal}>
          <Container>
            <p>{c.trust.caption}</p>
            <div className={styles.trustRow}>
              {c.trust.chips.map((chip) => (
                <span key={chip.label} className={styles.trustChip}>
                  <span className={styles.ic} style={{ background: chip.bg }}>
                    {chip.letter}
                  </span>
                  {chip.label}
                </span>
              ))}
            </div>
          </Container>
        </Reveal>
      </section>

      <Container>
        <div className={styles.hrGrad} />
      </Container>

      {/* ============ PROBLEMS ============ */}
      <section className={styles.block} id="problems">
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead
              center
              eyebrow={c.problems.eyebrow}
              title={c.problems.title}
              titleGrad={c.problems.titleGrad}
              subtitle={c.problems.subtitle}
            />
          </Reveal>
          <div className={styles.probGrid}>
            {c.problems.items.map((p, i) => (
              <Reveal
                key={p.title}
                className={styles.reveal}
                delay={0.08 * ((i % 3) + 1)}
              >
                <div className={styles.prob}>
                  <div className={styles.probIc}>
                    <svg
                      width="19"
                      height="19"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    >
                      {p.icon}
                    </svg>
                  </div>
                  <h3>{p.title}</h3>
                  <p>{p.desc}</p>
                </div>
              </Reveal>
            ))}
          </div>
        </Container>
      </section>

      {/* ============ WHAT'S INCLUDED ============ */}
      <section
        className={styles.block}
        id="included"
        style={{
          background:
            "linear-gradient(180deg,transparent,var(--background),transparent)",
        }}
      >
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead
              eyebrow={c.deliverables.eyebrow}
              title={c.deliverables.title}
              titleGrad={c.deliverables.titleGrad}
              subtitle={c.deliverables.subtitle}
            />
          </Reveal>
          <div className={styles.delivGrid}>
            {c.deliverables.items.map((d) => {
              const delay =
                d.span === "wide" ? 0.08 * ++wideN : 0.08 * ++thirdN;
              return (
                <Reveal
                  key={d.title}
                  className={`${styles.reveal} ${d.span === "wide" ? styles.wide : styles.third}`}
                  delay={delay}
                >
                  <div className={styles.deliv}>
                    <div className={styles.delivIc}>
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="url(#bm)"
                        strokeWidth="2"
                      >
                        {d.icon}
                      </svg>
                    </div>
                    <h3>{d.title}</h3>
                    <p>{d.desc}</p>
                    {d.bullets ? (
                      <ul>
                        {d.bullets.map((li) => (
                          <li key={li}>
                            <Check /> {li}
                          </li>
                        ))}
                      </ul>
                    ) : null}
                  </div>
                </Reveal>
              );
            })}
          </div>
        </Container>
      </section>

      {/* ============ PROCESS (animated bento) ============ */}
      <section className={styles.block} id="process">
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead
              center
              eyebrow={c.process.eyebrow}
              title={c.process.title}
              titleGrad={c.process.titleGrad}
              subtitle={c.process.subtitle}
            />
          </Reveal>

          <Reveal className={styles.bento}>
            {c.process.steps.map((step, i) => (
              <div
                key={step.num}
                className={`${styles.bcard} ${i === 0 ? styles.feature : ""}`}
              >
                <div className={styles.bhead}>
                  <span className={styles.bnum}>{step.num}</span>
                  <span className={styles.bwhen}>{step.when}</span>
                </div>
                <h3>{step.title}</h3>
                <p>{step.desc}</p>
                <Viz step={step} />
              </div>
            ))}
          </Reveal>
        </Container>
      </section>

      {/* ============ RESULTS ============ */}
      <section className={styles.blockTight} id="results">
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead
              center
              eyebrow={c.results.eyebrow}
              title={c.results.title}
              className="mb-11"
            />
          </Reveal>
          <Reveal className={styles.reveal} delay={0.08}>
            <div className={styles.resultsBand}>
              <div className={styles.resultsGrid}>
                {c.results.items.map((r) => (
                  <div key={r.label} className={styles.stat}>
                    <div
                      className={`${styles.big} ${r.grad ? "text-gradient-brand" : ""}`}
                    >
                      <CountUp
                        value={r.value}
                        prefix={r.prefix}
                        suffix={r.suffix}
                        dec={r.dec}
                      />
                      {r.out ? (
                        <span
                          style={{ color: "var(--ink-4)", fontSize: "0.5em" }}
                        >
                          {r.out}
                        </span>
                      ) : null}
                    </div>
                    <div className={styles.statLab}>{r.label}</div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </Container>
      </section>

      {/* ============ TESTIMONIALS ============ */}
      <section className={styles.block}>
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead
              center
              eyebrow={c.testimonials.eyebrow}
              title={c.testimonials.title}
              titleGrad={c.testimonials.titleGrad}
            />
          </Reveal>
          <div className={styles.tstGrid}>
            {c.testimonials.items.map((t, i) => (
              <Reveal
                key={t.name}
                className={styles.reveal}
                delay={0.08 * (i + 1)}
              >
                <div className={styles.tst}>
                  <div className={styles.stars} aria-label="5 out of 5 stars">
                    ★★★★★
                  </div>
                  <blockquote>{t.quote}</blockquote>
                  <div className={styles.who}>
                    <div className={styles.av} style={{ background: t.bg }}>
                      {t.initials}
                    </div>
                    <div>
                      <div className={styles.whoName}>{t.name}</div>
                      <div className={styles.whoRole}>{t.role}</div>
                    </div>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </Container>
      </section>

      {/* ============ FAQ ============ */}
      <section className={styles.blockTight} id="faq">
        <Container>
          <Reveal className={styles.reveal}>
            <SectionHead center eyebrow={c.faq.eyebrow} title={c.faq.title} />
          </Reveal>
          <Reveal className={styles.reveal} delay={0.08}>
            <Faq items={c.faq.items} />
          </Reveal>
        </Container>
      </section>

      {/* ============ CTA ============ */}
      <section className={styles.blockTight} id="cta">
        <Container>
          <Reveal className={styles.reveal}>
            <div className={styles.ctaBand}>
              <div className={styles.ctaGlow} />
              <div className={styles.ctaInner}>
                <h2>
                  {c.cta.title}
                  <span className="text-gradient-brand">.</span>
                </h2>
                <p>{c.cta.sub}</p>
                <div className={styles.heroCta}>
                  <Button asChild>
                    <Link href={contactHref}>
                      {c.ctaPrimaryLabel} {arrow}
                    </Link>
                  </Button>
                  <a href={c.ctaGhostHref} className={styles.btnGhost}>
                    {c.ctaGhostLabel}
                  </a>
                </div>
                <p className={styles.heroNote}>
                  <span>
                    <Check /> {c.cta.note}
                  </span>
                </p>
              </div>
            </div>
          </Reveal>
        </Container>
      </section>
    </div>
  );
}
