/**
 * Scene-first banner planning — problem → industry → scene → layout → visual motifs.
 * Used by full-banner prompts, hero prompts, and SVG composite fallback.
 */

import {
  BANNER_LAYOUT_IDS,
  type BannerLayoutId,
  pickBannerLayout,
} from "@/lib/generation/banner-layouts";

export type BannerIndustryVertical =
  | "education_admissions"
  | "healthcare"
  | "legal"
  | "insurance"
  | "finance"
  | "fax_comms"
  | "telecom"
  | "email"
  | "general_b2b";

export type CtaStyleId = "pill" | "rect" | "outline" | "wide_bar" | "dual_tone";
export type LogoPlacementId = "top_left" | "top_center" | "top_right";
export type IconSetId = "shield_docs" | "network_routes" | "charts_growth" | "compliance_audit";
export type BackgroundMotifId =
  | "curved_panel"
  | "diagonal_split"
  | "soft_orbs"
  | "grid_mesh"
  | "map_arcs"
  | "glass_card";

export type DesignStyleId =
  | "gen_z_bold"
  | "glass_gradient"
  | "editorial_minimal"
  | "neo_brutalist"
  | "premium_saas";

export interface BannerScenePlan {
  layoutId: BannerLayoutId;
  layoutSeed: number;
  industry: BannerIndustryVertical;
  problemStatement: string;
  sceneTitle: string;
  sceneDescription: string;
  visualMotifs: string[];
  iconSet: IconSetId;
  backgroundMotif: BackgroundMotifId;
  ctaStyle: CtaStyleId;
  logoPlacement: LogoPlacementId;
  accentEmphasis: "primary" | "accent" | "balanced";
  designStyle: DesignStyleId;
  avoidGenericOfficePhoto: true;
}

const DESIGN_STYLES: DesignStyleId[] = [
  "gen_z_bold",
  "glass_gradient",
  "editorial_minimal",
  "neo_brutalist",
  "premium_saas",
];

const CTA_STYLES: CtaStyleId[] = ["pill", "rect", "outline", "wide_bar", "dual_tone"];
const BACKGROUNDS: BackgroundMotifId[] = [
  "curved_panel",
  "diagonal_split",
  "soft_orbs",
  "grid_mesh",
  "map_arcs",
  "glass_card",
];
const ICON_SETS: IconSetId[] = [
  "shield_docs",
  "network_routes",
  "charts_growth",
  "compliance_audit",
];

export function detectBannerIndustry(input: {
  industry?: string;
  solutionCategory?: string;
  visualHint?: string;
  caption?: string;
  companyName?: string;
}): BannerIndustryVertical {
  const blob = [
    input.industry,
    input.solutionCategory,
    input.visualHint,
    input.caption,
    input.companyName,
  ]
    .filter(Boolean)
    .join(" ")
    .toLowerCase();

  // Admissions/MBBS projects are education stories, not healthcare products.
  // This must run before healthcare detection because "medical/MBBS" appears
  // in the audience context and previously caused doctor/hospital creatives.
  if (
    /admission|enrol(?:l)?ment|student|education|university|college|study.?abroad|mbbs|counsell?ing|parent.?trust|visa/i.test(
      blob,
    )
  ) {
    return "education_admissions";
  }
  if (/health|hospital|clinic|hipaa|medical|patient/.test(blob)) return "healthcare";
  if (/legal|law|court|contract|attorney|counsel/.test(blob)) return "legal";
  if (/insurance|claims|policyholder|underwrit/.test(blob)) return "insurance";
  if (/financ|bank|payment|approv|treasury|fintech/.test(blob)) return "finance";
  if (/fax|efax|document|secure.?deliver|audit.?trail|broadcast/.test(blob)) return "fax_comms";
  if (/sms|dialer|call.?rout|telecom|voip|missed.?route/.test(blob)) return "telecom";
  if (/email|inbox|smtp|campaign/.test(blob)) return "email";
  return "general_b2b";
}

function extractProblem(input: {
  problemTheme?: string;
  caption?: string;
  subheadline?: string;
  industry: BannerIndustryVertical;
}): string {
  const fromTheme = input.problemTheme?.trim();
  if (fromTheme && fromTheme.length > 20) return fromTheme.slice(0, 160);

  const caption = (input.caption || "").replace(/#\w+/g, " ").trim();
  const sentence = caption.split(/(?<=[.!?])\s+/).find((s) => s.length > 40);
  if (sentence) return sentence.slice(0, 160);

  const sub = input.subheadline?.trim();
  if (sub) return sub.slice(0, 160);

  const defaults: Record<BannerIndustryVertical, string> = {
    education_admissions:
      "Genuine student inquiries are lost when search, messaging, counselling, documents, and enrolment are handled in disconnected systems.",
    healthcare: "Critical patient and clinical documents stall when delivery is slow or untracked.",
    legal: "Time-sensitive contracts and filings fail when secure delivery lacks auditability.",
    insurance: "Claims packets and customer records get stuck without compliant document workflows.",
    finance: "Approvals and reports lose time when secure document exchange is fragmented.",
    fax_comms: "High-stakes documents move too slowly when communication channels are fragmented.",
    telecom: "Every missed route is lost revenue when calls land in the wrong destination.",
    email: "Important business messages get buried when inbox routing lacks intelligence.",
    general_b2b: "Operations slow down when critical communication lacks clarity and control.",
  };
  return defaults[input.industry];
}

function scenesForIndustry(industry: BannerIndustryVertical): Array<{ title: string; description: string; motifs: string[] }> {
  const map: Record<BannerIndustryVertical, Array<{ title: string; description: string; motifs: string[] }>> = {
    education_admissions: [
      {
        title: "Connected student journey",
        description:
          "Late-evening modern university admissions office: a counsellor at a clean desk receives inquiry signals from web search, messaging, email, and the university website. A transparent workflow shows Inquiry → Counselling → Document Verification → Admission Letter → Visa → Enrolment. In the background, Indian parents discuss their child's future, a student attends online counselling, an international campus is visible through glass, and a subtle map arc connects India with Uzbekistan. This is an EdTech admissions experience — absolutely no hospital treatment, doctors consulting patients, surgery, medical reports, fake analytics, passports, airplanes, or visa stamps.",
        motifs: [
          "student journey",
          "parent trust",
          "counsellor workflow",
          "international campus",
          "India Uzbekistan connection",
        ],
      },
      {
        title: "From search to enrolment",
        description:
          "Premium editorial admissions scene where one online search becomes a guided student journey. Show a counsellor coordinating multiple inquiry channels, a student on a video counselling call, parents reviewing clear next steps, and minimal glassmorphism stage cards for counselling, documents, admission letter, visa, and enrolment. Education technology only — no healthcare dashboard or clinical environment.",
        motifs: [
          "one search",
          "multi-channel inquiries",
          "online counselling",
          "transparent stages",
          "student conversion",
        ],
      },
    ],
    healthcare: [
      {
        title: "Clinical records vault",
        description:
          "Hospital corridor metaphor with glowing medical record packets flowing into an encrypted vault; HIPAA shield and checkmarks — no generic laptop selfie.",
        motifs: ["medical records", "compliance shield", "encrypted transfer", "hospital workflow"],
      },
      {
        title: "Care-team document relay",
        description:
          "Isometric care-team desks exchanging secure digital charts with audit stamps and delivery confirmation arcs.",
        motifs: ["document flow", "audit stamp", "secure delivery", "care continuity"],
      },
    ],
    legal: [
      {
        title: "Contract seal & court continuity",
        description:
          "Premium contract stack transforming into encrypted packets with seal/check icons; courthouse silhouette subtle in background fog.",
        motifs: ["contracts", "secure seal", "court continuity", "compliance"],
      },
      {
        title: "Counsel document corridor",
        description:
          "Law-office document corridor with glowing signature pads, vault door, and chain-of-custody timeline markers.",
        motifs: ["chain of custody", "e-signature", "vault", "timeline"],
      },
    ],
    insurance: [
      {
        title: "Claims packet pipeline",
        description:
          "Claims folders moving through a digital processing pipeline with status chips, customer record cards, and approval gates.",
        motifs: ["claims processing", "customer records", "approval gates", "status chips"],
      },
    ],
    finance: [
      {
        title: "Approval workflow dashboard",
        description:
          "Enterprise dashboard with approval stamps, rising report charts, and secure document lanes between finance nodes.",
        motifs: ["reports", "approval workflow", "KPI chart", "secure lanes"],
      },
    ],
    fax_comms: [
      {
        title: "Secure document transfer network",
        description:
          "3D document packets streaming across a communication network into a compliance vault; fax/scan device as a modern prop; audit trail ribbon.",
        motifs: ["document transfer", "secure delivery", "audit trails", "broadcast nodes"],
      },
      {
        title: "Broadcast + compliance grid",
        description:
          "Multi-node broadcast map with encrypted beams, shield icons, and healthcare/legal/finance destination pins — business continuity story.",
        motifs: ["broadcast systems", "compliance", "industry pins", "business continuity"],
      },
      {
        title: "Audit-ready delivery desk",
        description:
          "Modern operations desk with glowing delivery confirmations, audit checklist UI, and network arcs — not a random office portrait.",
        motifs: ["audit checklist", "delivery confirmation", "network arcs", "operations desk"],
      },
    ],
    telecom: [
      {
        title: "Intelligent routing success",
        description:
          "Desk phone + headset with success check; route map showing miss-X vs success pins; upward conversion chart.",
        motifs: ["call routing", "success pins", "conversion chart", "headset phone"],
      },
      {
        title: "Missed route = lost revenue",
        description:
          "Split visual: chaotic wrong-route X on one side, clean destination pin + green revenue arrow on the other.",
        motifs: ["missed route", "lost revenue", "destination pin", "growth arrow"],
      },
    ],
    email: [
      {
        title: "Inbox intelligence",
        description:
          "Clean inbox UI mock with priority routing arrows, delivery checkmarks, and analytics sparkline — no stock headshot.",
        motifs: ["inbox UI", "priority routing", "delivery checks", "sparkline"],
      },
    ],
    general_b2b: [
      {
        title: "Operations control story",
        description:
          "Isometric B2B operations with network nodes, trust shield, and upward KPI bars — product storytelling over stock photography.",
        motifs: ["network nodes", "trust shield", "KPI bars", "operations"],
      },
    ],
  };
  return map[industry];
}

/**
 * Brand logo is always stamped top-right via FFmpeg overlay of the uploaded asset.
 * Do not rotate placement — left/center caused collisions with headlines and white plates.
 */
function logoPlacementForLayout(_layout: BannerLayoutId, _seed: number): LogoPlacementId {
  return "top_right";
}

function designStyleForSeed(seed: number, sequenceIndex: number): DesignStyleId {
  return DESIGN_STYLES[Math.abs(seed + sequenceIndex * 11) % DESIGN_STYLES.length]!;
}

function designStyleNotes(style: DesignStyleId): string {
  const map: Record<DesignStyleId, string> = {
    gen_z_bold:
      "Gen Z–inspired: chunky sans-serif, bold color blocks, playful gradients, dynamic angles, high contrast — still professional B2B.",
    glass_gradient:
      "Glassmorphism + soft gradients, frosted panels, floating cards, premium social-ready polish.",
    editorial_minimal:
      "Editorial whitespace, restrained palette, one hero metaphor, magazine-quality hierarchy.",
    neo_brutalist:
      "Bold borders, offset shadows, asymmetric grid, confident typography — modern campaign feel.",
    premium_saas:
      "High-end SaaS ad: isometric 3D, KPI chips, curved panels, LinkedIn-carousel quality.",
  };
  return map[style];
}

/**
 * Build a complete scene plan for this generation.
 * When `excludeLayoutId` is set (regenerate), picks a different layout.
 */
export function buildBannerScenePlan(input: {
  layoutSeed: number;
  sequenceIndex?: number;
  industry?: string;
  solutionCategory?: string;
  visualHint?: string;
  visualHook?: string;
  headline?: string;
  caption?: string;
  companyName?: string;
  problemTheme?: string;
  subheadline?: string;
  excludeLayoutId?: BannerLayoutId | null;
}): BannerScenePlan {
  const sequenceIndex = input.sequenceIndex ?? 1;
  const industry = detectBannerIndustry(input);
  const layoutId = pickBannerLayout(input.layoutSeed, input.excludeLayoutId, sequenceIndex);
  const problemStatement = extractProblem({ ...input, industry });
  const pool = scenesForIndustry(industry);
  const sceneIdx =
    Math.abs(input.layoutSeed + sequenceIndex * 13 + (input.headline?.length ?? 0)) % pool.length;
  const scene = pool[sceneIdx]!;
  const iconSet = ICON_SETS[Math.abs(input.layoutSeed >> 2) % ICON_SETS.length]!;
  const backgroundMotif = BACKGROUNDS[Math.abs(input.layoutSeed >> 3) % BACKGROUNDS.length]!;
  const ctaStyle = CTA_STYLES[Math.abs(input.layoutSeed >> 1) % CTA_STYLES.length]!;
  const accentEmphasis =
    input.layoutSeed % 3 === 0 ? "accent" : input.layoutSeed % 3 === 1 ? "primary" : "balanced";
  const designStyle = designStyleForSeed(input.layoutSeed, sequenceIndex);

  const hook = input.visualHook?.trim();
  const sceneDescription = hook
    ? `${scene.description} Post-specific visual hook: ${hook.slice(0, 180)}.`
    : scene.description;

  return {
    layoutId,
    layoutSeed: input.layoutSeed,
    industry,
    problemStatement,
    sceneTitle: scene.title,
    sceneDescription,
    visualMotifs: scene.motifs,
    iconSet,
    backgroundMotif,
    ctaStyle,
    logoPlacement: logoPlacementForLayout(layoutId, input.layoutSeed),
    accentEmphasis,
    designStyle,
    avoidGenericOfficePhoto: true,
  };
}

/** Prompt block injected into full-banner / hero generation. */
export function formatScenePlanForPrompt(plan: BannerScenePlan): string {
  return [
    "## Scene plan (mandatory — design from this story, not a static template)",
    `Industry vertical: ${plan.industry}`,
    `Business problem: ${plan.problemStatement}`,
    `Scene title: ${plan.sceneTitle}`,
    `Scene direction: ${plan.sceneDescription}`,
    `Visual motifs to include: ${plan.visualMotifs.join(", ")}`,
    `Icon language: ${plan.iconSet}`,
    `Background motif: ${plan.backgroundMotif}`,
    `Design style: ${plan.designStyle} — ${designStyleNotes(plan.designStyle)}`,
    `CTA style: ${plan.ctaStyle}`,
    `Logo placement: ${plan.logoPlacement} (real logo pasted in production — leave blank zone)`,
    `Color emphasis: ${plan.accentEmphasis}`,
    `Layout id: ${plan.layoutId} (of ${BANNER_LAYOUT_IDS.length} compositions)`,
    "FORBIDDEN: generic smiling office headshot as the hero; left-text/right-photo template reused across posts.",
  ].join("\n");
}
