import type { SocialImageContext } from "@/lib/generation/social-image";
import {
  formatScenePlanForPrompt,
  type BannerScenePlan,
} from "@/lib/generation/scene-planner";
import type { BannerLayoutId } from "@/lib/generation/banner-layouts";
import type { PostBannerContent } from "@/lib/generation/banner-post-content";

/** Dynamic post copy + locked brand contact block for on-image generation. */
export function buildBannerContentBlock(ctx: SocialImageContext): string {
  const post = ctx.postBannerContent;
  const style = ctx.brandStyle;

  const headline = (
    post?.headline ||
    ctx.product?.primaryHeadline ||
    ctx.headline ||
    ctx.brandStyle.heroHeadline.join(" ")
  )
    .trim()
    .replace(/\s+/g, " ")
    .slice(0, 90);

  let sub = (
    post?.subheadline ||
    ctx.product?.subheadline ||
    ctx.subheadline ||
    ctx.brandStyle.tagline ||
    ctx.captionExcerpt ||
    ""
  )
    .trim()
    .replace(/\s+/g, " ");
  if (sub.length > 120) {
    const cut = sub.slice(0, 120);
    const lastSpace = cut.lastIndexOf(" ");
    sub = (lastSpace > 70 ? cut.slice(0, lastSpace) : cut).replace(/[.,;:]+$/, "") + ".";
  }

  const features = post?.features?.length
    ? post.features
    : (ctx.brandStyle.features || []).slice(0, 4).map((f) => ({
        label: f.label.toUpperCase(),
        detail: f.detail?.slice(0, 40) || "",
      }));

  const featureLines = features
    .slice(0, 4)
    .map((f, i) => {
      const detail = f.detail?.trim() ? ` — ${f.detail.trim().slice(0, 40)}` : "";
      return `${i + 1}. ${f.label.toUpperCase()}${detail}`;
    })
    .join("\n");

  const cta = (style.ctaLine || "Learn More").trim().toUpperCase();
  const ctaSub = (post?.ctaSubline || style.ctaSubline || style.primaryService || "").trim();

  // LOCKED brand contact — must render exactly (no typos, no invented URLs).
  const phone = style.contactPhone?.trim();
  const email = style.contactEmail?.trim();
  const website = (ctx.website || style.website || "")
    .replace(/^https?:\/\//i, "")
    .replace(/\/$/, "");
  const company = ctx.companyName || "Brand";

  return [
    "## DYNAMIC COPY (unique to this post — spell exactly)",
    `HEADLINE: ${headline}`,
    `SUBHEADING: ${sub}`,
    "",
    `FEATURE SECTION:`,
    featureLines,
    "",
    `CTA BUTTON: ${cta}`,
    ctaSub ? `CTA SUPPORT LINE: ${ctaSub}` : "",
    "",
    "## LOCKED BRAND CONTACT (copy character-for-character — do not alter)",
    phone ? `PHONE (exact): ${phone}` : "",
    email ? `EMAIL (exact): ${email}` : "",
    website ? `WEBSITE (exact): https://${website}` : "",
    "",
    `Brand colors only: primary ${ctx.primaryColor || style.primaryColor}, accent ${ctx.accentColor || style.accentColor}.`,
    `Company name in body copy only: ${company}`,
  ]
    .filter((line, i, arr) => !(line === "" && arr[i - 1] === ""))
    .join("\n")
    .trim();
}

function layoutRecipe(layout: BannerLayoutId, seed: number): string {
  const recipes: Record<BannerLayoutId, string[]> = {
    right_image: [
      "Asymmetric split — NOT the default template. Try diagonal cut, overlapping panels, or floating card over illustration.",
    ],
    left_image: [
      "Hero storytelling LEFT; editorial copy RIGHT with bold hierarchy and offset CTA.",
    ],
    center_cta: [
      "Full-bleed scene + frosted center card; oversized CTA; feature chips in a row.",
    ],
    feature_focused: [
      "Feature CARDS dominate; headline compact; illustration as accent strip.",
    ],
    statistics_focused: [
      "Giant proof metric + upward chart; minimal copy; high-impact campaign poster.",
    ],
    full_bleed: [
      "Cinematic background; typography on frosted scrim; floating icon badges.",
    ],
    top_hero: [
      "Immersive top illustration band; bottom content board with generous padding.",
    ],
    bottom_hero: [
      "Top copy stack; bottom storytelling panel with glow and network arcs.",
    ],
    split_card: [
      "Two stacked cards on gradient backdrop; side inset illustration.",
    ],
    infographic: [
      "Vertical flow: problem → process → outcome; icon steps; no photo collage.",
    ],
    timeline: [
      "Horizontal timeline stages with icons; headline above; CTA anchored bottom.",
    ],
    enterprise_dashboard: [
      "Dashboard UI metaphor: KPI tiles, compliance badge, chart — premium SaaS.",
    ],
  };
  const options = recipes[layout] ?? recipes.right_image!;
  return options[Math.abs(seed) % options.length]!;
}

/**
 * Premium social banner prompt — scene-first, post-unique, brand-locked contact.
 * Real company logo is composited in code — never drawn by the model.
 */
export function buildFullBannerImagePrompt(ctx: SocialImageContext): string {
  const seed = ctx.layoutSeed ?? Date.now();
  const plan: BannerScenePlan | undefined = ctx.scenePlan;
  const layout = plan?.layoutId ?? (ctx.bannerLayoutId as BannerLayoutId) ?? "right_image";
  const content = buildBannerContentBlock(ctx);
  const primary = ctx.primaryColor || ctx.brandStyle.primaryColor;
  const accent = ctx.accentColor || ctx.brandStyle.accentColor;
  const hasRealLogo = Boolean(ctx.logoDataUrl);
  const recipe = layoutRecipe(layout, seed);
  const sceneBlock = plan
    ? formatScenePlanForPrompt(plan)
    : "Design a unique industry-aware composition — avoid template left-text/right-photo.";

  // Real logo is FFmpeg-composited top-right — never ask the model for a white logo plate.
  const logoZone =
    "TOP-RIGHT (~280×100 starting near x=780, y=24): leave EMPTY. Same background color as the banner — no white box, no plate, no border, no wordmark, no tagline, no icon.";

  return [
    "Create a completely NEW 1080x1080px social media banner — unique campaign creative for THIS post only.",
    "Style: creative, modern, Gen Z–influenced, professionally attractive, high-engagement B2B social creative.",
    "This must NOT look like a reused template. Change layout structure, hero placement, motifs, and CTA treatment.",
    "",
    content,
    "",
    sceneBlock,
    "",
    "## Composition (mandatory uniqueness)",
    `Post variation token: ${seed}`,
    `Layout id: ${layout}`,
    `Recipe: ${recipe}`,
    `Sequence beat: ${ctx.sequenceIndex ?? 1}`,
    "- Avoid the repetitive left-text / right-stock-photo formula unless layout id demands split.",
    "- Use industry illustrations: document flows, secure vaults, compliance shields, network arcs — NOT generic headshots.",
    "",
    "## Typography & spacing",
    "- Modern bold sans-serif; strong hierarchy; generous whitespace.",
    "- Max 2 subheading lines; max 4 features; spell every word correctly (no typos).",
    "- Phone, email, website must match LOCKED BRAND CONTACT exactly.",
    "",
    "## Brand (colors only — logo pasted later)",
    `Primary ${primary}, accent ${accent}. Emphasis: ${plan?.accentEmphasis ?? "balanced"}.`,
    "",
    hasRealLogo
      ? [
          "## LOGO ZONE (critical — exact brand logo is pasted in post-processing)",
          "- Do NOT draw, invent, approximate, or recreate any logo, wordmark, or brand tagline.",
          `- ${logoZone}`,
          "- Keep headline and subhead on the LEFT or CENTER — never under the top-right logo zone.",
          "- Start primary headline at or below y=160 on the left half.",
        ].join("\n")
      : "- Simple wordmark allowed only if no uploaded logo.",
    "",
    "Output: ultra-sharp 1080×1080, premium social-ready, visually distinct from other posts in the campaign.",
  ].join("\n");
}
