import type { FeatureIconKind } from "@/lib/generation/brand-visual-style";
import type { SocialImageContext } from "@/lib/generation/social-image";
import {
  buildLogoBlock,
  buildVerticalProductPanel,
  escapeXml,
  featureIconSvg,
  multilineTextSvg,
  wrapText,
} from "@/lib/generation/brand-svg-shared";

export const STORY_SLIDE_COUNT = 5;

/** One vertical 9:16 frame for multi-screen marketing video. */
export function buildStorySlideSvg(ctx: SocialImageContext, slideIndex: number): string {
  const style = ctx.brandStyle;
  const w = 1080;
  const h = 1920;
  const idx = Math.max(0, Math.min(slideIndex, STORY_SLIDE_COUNT - 1));
  const seed = ctx.layoutSeed ?? 0;
  // Per-regenerate composition shift so every video scene layout differs.
  const layoutShift = (seed + idx * 17) % 3;
  const primary = style.primaryColor;
  const accent = style.accentColor;
  const headline =
    idx === 0
      ? ctx.headline
      : idx === 1
        ? ctx.problemTheme || ctx.headline
        : idx === 2
          ? ctx.subheadline || ctx.brandStyle.tagline
          : idx === 3
            ? ctx.brandResponse || ctx.brandStyle.primaryService || ctx.headline
            : ctx.brandStyle.ctaLine || "Ready to get started?";

  const body =
    idx === 0
      ? style.tagline
      : idx === 1
        ? ctx.problemTheme
        : idx === 2
          ? ctx.subheadline
          : idx === 3
            ? ctx.brandResponse || style.features.find((f) => f.icon === "solution")?.detail || style.primaryService
            : [style.website, style.contactPhone, style.contactEmail].filter(Boolean).join(" · ") ||
              `${style.ctaSubline}`;

  const slideLabel =
    idx === 0
      ? "THE HOOK"
      : idx === 1
        ? "THE CHALLENGE"
        : idx === 2
          ? "THE IMPACT"
          : idx === 3
            ? style.primaryService.slice(0, 18).toUpperCase() || "HOW WE HELP"
            : "TAKE ACTION";

  const iconKind: FeatureIconKind =
    idx === 0 ? "benefit" : idx === 1 ? "challenge" : idx === 2 ? "impact" : idx === 3 ? "solution" : "service";

  const headlineLines = wrapText(headline, idx === 0 ? 18 : 22, idx === 0 ? 3 : 2);
  const bodyLines = wrapText(body, 36, 4);
  const logoX = layoutShift === 1 ? 812 : 48;
  const logo = buildLogoBlock(ctx, { x: logoX, y: 36, maxWidth: 220, maxHeight: 72 });
  const panelY = layoutShift === 2 ? 880 : 920;
  const productPanel = buildVerticalProductPanel(ctx, {
    x: layoutShift === 1 ? 60 : 80,
    y: panelY,
    width: 920,
    height: 560,
  });

  const stepDots = Array.from({ length: STORY_SLIDE_COUNT }, (_, i) => {
    const cx = 540 + (i - 2) * 56;
    const fill = i === idx ? accent : "#cbd5e1";
    return `<circle cx="${cx}" cy="1780" r="10" fill="${fill}"/>`;
  }).join("");

  const contentX = layoutShift === 1 ? 100 : 80;
  const headlineSvg = multilineTextSvg(contentX, 280, headlineLines, {
    fontSize: idx === 0 ? 52 : 44,
    fontWeight: "bold",
    fill: primary,
    lineHeight: 58,
  });

  const accentLine = `<rect x="${contentX}" y="${280 + headlineLines.length * 58 + 16}" width="${layoutShift === 2 ? 180 : 120}" height="6" rx="3" fill="${layoutShift === 0 ? accent : primary}"/>`;

  const bodySvg = multilineTextSvg(contentX, 320 + headlineLines.length * 58 + 48, bodyLines, {
    fontSize: 28,
    fill: "#334155",
    lineHeight: 38,
  });

  const iconX = layoutShift === 1 ? 120 : 920;
  const iconBlock = featureIconSvg(style.vertical, iconKind, iconX, 220, accent, 56);

  const badgeX = contentX;
  const slideBadge = `
  <rect x="${badgeX}" y="196" width="${slideLabel.length * 14 + 40}" height="44" rx="22" fill="${layoutShift === 2 ? accent : primary}" opacity="0.12"/>
  <text x="${badgeX + 20}" y="226" fill="${primary}" font-family="Arial,Helvetica,sans-serif" font-size="18" font-weight="700" letter-spacing="1">${escapeXml(slideLabel)}</text>`;

  const ctaBlock =
    idx === 4
      ? `
  <rect x="80" y="1520" width="920" height="120" rx="16" fill="${layoutShift === 1 ? accent : primary}"/>
  <text x="120" y="1578" fill="white" font-family="Arial,sans-serif" font-size="32" font-weight="bold">${escapeXml(style.ctaLine.slice(0, 40))}</text>
  <text x="120" y="1618" fill="${layoutShift === 1 ? primary : accent}" font-family="Arial,sans-serif" font-size="24" font-weight="600">${escapeXml(ctx.companyName)} · ${escapeXml(style.website)}</text>`
      : "";

  const seedMark = `<desc id="regen-slide-${seed}-${idx}">shift-${layoutShift}</desc>`;

  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
  ${seedMark}
  <defs>
    <linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:${primary};stop-opacity:${layoutShift === 0 ? 0.08 : 0.12}"/>
      <stop offset="100%" style="stop-color:${accent};stop-opacity:${layoutShift === 2 ? 0.2 : 0.14}"/>
    </linearGradient>
    <linearGradient id="photoGrad" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:${primary};stop-opacity:0.12"/>
      <stop offset="50%" style="stop-color:${accent};stop-opacity:0.18"/>
      <stop offset="100%" style="stop-color:#e2e8f0"/>
    </linearGradient>
  </defs>
  <rect width="${w}" height="${h}" fill="${style.lightBg}"/>
  <rect width="${w}" height="${h}" fill="url(#bgGrad)"/>
  <rect x="0" y="0" width="${w}" height="128" fill="white"/>
  <rect x="0" y="126" width="${w}" height="3" fill="${primary}" opacity="0.2"/>
  ${logo}
  ${slideBadge}
  ${iconBlock}
  ${headlineSvg}
  ${accentLine}
  ${bodySvg}
  ${productPanel}
  ${ctaBlock}
  <rect x="0" y="1820" width="${w}" height="100" fill="${primary}"/>
  <rect x="0" y="1860" width="${w}" height="60" fill="${accent}"/>
  <text x="80" y="1860" fill="white" font-family="Arial,sans-serif" font-size="22" font-weight="600">${escapeXml(style.website)}</text>
  <text x="620" y="1860" fill="white" font-family="Arial,sans-serif" font-size="22" font-weight="600">${escapeXml(ctx.companyName)}</text>
  ${stepDots}
  <text x="540" y="1810" text-anchor="middle" fill="#64748b" font-family="Arial,sans-serif" font-size="16">${idx + 1} / ${STORY_SLIDE_COUNT}</text>
</svg>`;

  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}

/** Decode data-URL SVG to raw markup for file write. */
export function decodeSvgDataUrl(dataUrl: string): string | null {
  if (!dataUrl.startsWith("data:image/svg+xml")) return null;
  if (dataUrl.includes(";base64,")) {
    const b64 = dataUrl.split(";base64,")[1];
    if (!b64) return null;
    return Buffer.from(b64, "base64").toString("utf-8");
  }
  const encoded = dataUrl.replace(/^data:image\/svg\+xml;charset=utf-8,/, "");
  try {
    return decodeURIComponent(encoded);
  } catch {
    return null;
  }
}
