/**
 * Optional reference library (docs / manual inspiration only).
 * Live generation does NOT select campaign themes from this list —
 * creative-brief-builder derives beats from company URL scrape + brand.
 */

export type StoryAct =
  | "challenge"
  | "recognition"
  | "solution"
  | "proof"
  | "path_forward";

export interface ContextLibraryEntry {
  id: string;
  title: string;
  problem: string;
  impact: string;
  hashtags: string;
  /** Preferred narrative act in a 5-beat campaign arc */
  act: StoryAct;
  /** Industries where this problem resonates most (empty = universal) */
  industries: string[];
  /** Tags for scoring relevance */
  themes: string[];
}

/** 20 reusable Problem → Impact contexts (source: Generic Context Library doc). */
export const CONTEXT_LIBRARY: ContextLibraryEntry[] = [
  {
    id: "digital-transformation",
    title: "Lack of Digital Transformation",
    problem:
      "Many organizations continue relying on outdated processes, manual workflows, and disconnected systems that reduce operational efficiency.",
    impact:
      "Productivity declines, operational costs increase, and businesses struggle to compete in a rapidly evolving digital market.",
    hashtags: "#DigitalTransformation #BusinessGrowth #Innovation #Automation",
    act: "challenge",
    industries: ["Technology / Software", "Finance", "Healthcare", "Retail"],
    themes: ["automation", "efficiency", "modernization"],
  },
  {
    id: "customer-experience",
    title: "Poor Customer Experience",
    problem:
      "Businesses often focus heavily on acquiring new customers while overlooking the experience of their existing customers.",
    impact:
      "Customer satisfaction declines, repeat business decreases, and negative word-of-mouth impacts long-term growth.",
    hashtags: "#CustomerExperience #BusinessSuccess #CustomerRetention #Growth",
    act: "recognition",
    industries: ["Retail", "Healthcare", "Salon / Beauty", "Finance"],
    themes: ["customer", "retention", "service"],
  },
  {
    id: "data-driven",
    title: "Lack of Data-Driven Decisions",
    problem:
      "Important business decisions are frequently made based on assumptions instead of reliable data and analytics.",
    impact:
      "Companies miss growth opportunities, waste resources, and increase the risk of poor strategic decisions.",
    hashtags: "#DataDriven #BusinessIntelligence #Analytics #Leadership",
    act: "proof",
    industries: ["Finance", "Technology / Software", "Marketing / Agency"],
    themes: ["analytics", "strategy", "insights"],
  },
  {
    id: "rising-competition",
    title: "Rising Competition",
    problem:
      "Growing competition makes it increasingly difficult for businesses to differentiate their products and services.",
    impact:
      "Customer acquisition becomes more expensive while maintaining market share requires continuous innovation.",
    hashtags: "#BusinessStrategy #Competition #Innovation #Growth",
    act: "challenge",
    industries: ["Retail", "Salon / Beauty", "Marketing / Agency", "Technology / Software"],
    themes: ["competition", "differentiation", "market"],
  },
  {
    id: "skill-gap",
    title: "Employee Skill Gap",
    problem:
      "Rapid technological advancements create skill gaps that many organizations fail to address through continuous learning.",
    impact:
      "Productivity slows, innovation decreases, and businesses struggle to adopt new technologies effectively.",
    hashtags: "#Upskilling #FutureOfWork #Leadership #Learning",
    act: "recognition",
    industries: ["Education", "Healthcare", "Technology / Software"],
    themes: ["skills", "training", "workforce"],
  },
  {
    id: "communication",
    title: "Inefficient Communication",
    problem:
      "Poor communication between teams often leads to misunderstandings, delays, and duplicated efforts.",
    impact:
      "Project timelines extend, operational efficiency decreases, and customer satisfaction suffers.",
    hashtags: "#Teamwork #Communication #Productivity #Leadership",
    act: "recognition",
    industries: ["Marketing / Agency", "Technology / Software", "Healthcare"],
    themes: ["collaboration", "teams", "workflow"],
  },
  {
    id: "customer-feedback",
    title: "Ignoring Customer Feedback",
    problem:
      "Many businesses collect customer feedback but rarely use it to improve products or services.",
    impact:
      "Customer expectations remain unmet, reducing loyalty and increasing customer churn.",
    hashtags: "#CustomerFeedback #BusinessGrowth #CustomerSuccess #Innovation",
    act: "recognition",
    industries: ["Retail", "Healthcare", "Technology / Software"],
    themes: ["feedback", "improvement", "loyalty"],
  },
  {
    id: "tech-without-strategy",
    title: "Technology Without Strategy",
    problem:
      "Organizations invest in new technologies without aligning them with clear business objectives.",
    impact:
      "Technology investments fail to deliver expected returns and create unnecessary operational complexity.",
    hashtags: "#Technology #DigitalStrategy #Innovation #BusinessGrowth",
    act: "challenge",
    industries: ["Technology / Software", "Finance", "Marketing / Agency"],
    themes: ["strategy", "technology", "ROI"],
  },
  {
    id: "short-term-thinking",
    title: "Short-Term Thinking",
    problem:
      "Businesses often prioritize immediate profits over sustainable long-term planning.",
    impact:
      "Short-term gains may lead to declining customer trust, weaker brand reputation, and slower future growth.",
    hashtags: "#Leadership #BusinessStrategy #LongTermGrowth #Success",
    act: "path_forward",
    industries: ["Finance", "Retail", "Healthcare"],
    themes: ["strategy", "sustainability", "leadership"],
  },
  {
    id: "lack-innovation",
    title: "Lack of Innovation",
    problem:
      "Companies become comfortable with existing products and processes instead of continuously innovating.",
    impact:
      "Competitors capture market share while customer expectations evolve beyond what the business offers.",
    hashtags: "#Innovation #BusinessGrowth #FutureReady #Leadership",
    act: "path_forward",
    industries: ["Technology / Software", "Marketing / Agency", "Retail"],
    themes: ["innovation", "growth", "future"],
  },
  {
    id: "time-management",
    title: "Poor Time Management",
    problem:
      "Teams spend significant time on repetitive tasks instead of focusing on high-value activities.",
    impact:
      "Efficiency decreases, employee burnout increases, and overall business performance suffers.",
    hashtags: "#Productivity #TimeManagement #Automation #Business",
    act: "recognition",
    industries: ["Marketing / Agency", "Technology / Software", "B2B Communications / eFax"],
    themes: ["productivity", "automation", "efficiency"],
  },
  {
    id: "weak-online-presence",
    title: "Weak Online Presence",
    problem:
      "Many businesses underestimate the importance of maintaining a strong and consistent digital presence.",
    impact:
      "Potential customers choose competitors who demonstrate greater credibility and visibility online.",
    hashtags: "#DigitalMarketing #Branding #OnlineBusiness #Growth",
    act: "challenge",
    industries: ["Salon / Beauty", "Retail", "Marketing / Agency", "B2B Communications / eFax"],
    themes: ["social", "visibility", "branding"],
  },
  {
    id: "resistance-change",
    title: "Resistance to Change",
    problem:
      "Organizations often resist adopting new ideas, technologies, or business models.",
    impact:
      "Adaptation slows, competitive advantage weakens, and long-term growth opportunities are missed.",
    hashtags: "#ChangeManagement #Innovation #Leadership #BusinessGrowth",
    act: "recognition",
    industries: ["Healthcare", "Finance", "Education"],
    themes: ["change", "adaptation", "leadership"],
  },
  {
    id: "poor-automation",
    title: "Poor Process Automation",
    problem:
      "Repetitive manual tasks consume valuable employee time and increase the likelihood of human errors.",
    impact:
      "Operational costs rise while scalability and business efficiency remain limited.",
    hashtags: "#Automation #DigitalTransformation #Efficiency #Business",
    act: "solution",
    industries: ["Technology / Software", "B2B Communications / eFax", "Finance"],
    themes: ["automation", "efficiency", "scale"],
  },
  {
    id: "inconsistent-branding",
    title: "Inconsistent Brand Messaging",
    problem:
      "Businesses communicate different messages across platforms without a consistent brand voice.",
    impact:
      "Customer trust weakens, brand recognition decreases, and marketing effectiveness declines.",
    hashtags: "#Branding #Marketing #BusinessGrowth #CustomerTrust",
    act: "challenge",
    industries: ["Marketing / Agency", "Salon / Beauty", "Retail"],
    themes: ["branding", "voice", "trust"],
  },
  {
    id: "ai-adoption",
    title: "Lack of AI Adoption",
    problem:
      "Many organizations delay adopting AI despite its growing role in improving productivity and decision-making.",
    impact:
      "Competitors gain operational advantages while businesses miss opportunities for automation and innovation.",
    hashtags: "#ArtificialIntelligence #AI #Innovation #FutureOfWork",
    act: "solution",
    industries: ["Technology / Software", "Marketing / Agency", "Finance"],
    themes: ["AI", "innovation", "productivity"],
  },
  {
    id: "cybersecurity",
    title: "Cybersecurity Awareness",
    problem:
      "Employees often lack sufficient awareness of modern cybersecurity threats and best practices.",
    impact:
      "Organizations face increased risks of data breaches, financial losses, and reputational damage.",
    hashtags: "#CyberSecurity #InformationSecurity #DigitalSafety #Technology",
    act: "proof",
    industries: ["Finance", "Healthcare", "Technology / Software"],
    themes: ["security", "compliance", "risk"],
  },
  {
    id: "customer-retention",
    title: "Customer Retention",
    problem:
      "Businesses invest heavily in acquiring new customers but neglect strategies for retaining existing ones.",
    impact:
      "Customer acquisition costs continue to rise while long-term profitability decreases.",
    hashtags: "#CustomerRetention #BusinessGrowth #Marketing #CustomerSuccess",
    act: "proof",
    industries: ["Retail", "Salon / Beauty", "Healthcare", "B2B Communications / eFax"],
    themes: ["retention", "loyalty", "growth"],
  },
  {
    id: "ai-content-saturation",
    title: "AI Content Saturation",
    problem:
      "As AI-generated content becomes more common, many brands publish similar ideas without adding unique perspectives.",
    impact:
      "Audience engagement declines, trust weakens, and standing out in crowded digital channels becomes more difficult.",
    hashtags: "#ContentMarketing #AIContent #LinkedIn #ThoughtLeadership",
    act: "recognition",
    industries: ["Marketing / Agency", "Technology / Software", "B2B Communications / eFax"],
    themes: ["content", "AI", "differentiation"],
  },
  {
    id: "continuous-learning",
    title: "Continuous Learning",
    problem:
      "Professionals often stop learning after gaining experience, assuming existing knowledge will remain sufficient.",
    impact:
      "Skills become outdated, career growth slows, and adapting to industry changes becomes increasingly difficult.",
    hashtags: "#CareerGrowth #ContinuousLearning #Leadership #ProfessionalDevelopment",
    act: "path_forward",
    industries: ["Education", "Healthcare", "Finance", "Technology / Software"],
    themes: ["learning", "growth", "development"],
  },
];

const ACT_ORDER: StoryAct[] = [
  "challenge",
  "recognition",
  "solution",
  "proof",
  "path_forward",
];

const ACT_LABELS: Record<StoryAct, string> = {
  challenge: "Act 1 — The Challenge",
  recognition: "Act 2 — Recognition",
  solution: "Act 3 — The Solution",
  proof: "Act 4 — Proof",
  path_forward: "Act 5 — Path Forward",
};

const ACT_TAGS: Record<StoryAct, string> = {
  challenge: "Awareness",
  recognition: "Industry Insight",
  solution: "Product Value",
  proof: "Customer Success",
  path_forward: "Thought Leadership",
};

function normalizeIndustry(industry: string): string {
  return industry.trim().toLowerCase();
}

function scoreEntryForIndustry(entry: ContextLibraryEntry, industry: string): number {
  const norm = normalizeIndustry(industry);
  let score = 0;

  if (entry.industries.some((i) => normalizeIndustry(i) === norm)) score += 10;
  else if (entry.industries.length === 0) score += 2;

  if (norm.includes("marketing") && entry.themes.includes("branding")) score += 3;
  if (norm.includes("software") && entry.themes.includes("automation")) score += 3;
  if (norm.includes("efax") || norm.includes("b2b")) {
    if (entry.themes.includes("content") || entry.themes.includes("social")) score += 4;
  }
  if (norm.includes("salon") || norm.includes("beauty")) {
    if (entry.themes.includes("branding") || entry.themes.includes("visibility")) score += 5;
  }
  if (norm.includes("healthcare")) {
    if (entry.themes.includes("compliance") || entry.themes.includes("customer")) score += 4;
  }

  return score;
}

/** @deprecated Not used by live generation — beats come from website scrape + brand. Kept for docs/tools. */
export function selectContextArcForIndustry(industry: string): ContextLibraryEntry[] {
  const used = new Set<string>();
  const result: ContextLibraryEntry[] = [];

  for (const act of ACT_ORDER) {
    const candidates = CONTEXT_LIBRARY.filter((e) => e.act === act && !used.has(e.id))
      .map((entry) => ({ entry, score: scoreEntryForIndustry(entry, industry) }))
      .sort((a, b) => b.score - a.score);

    const pick = candidates[0]?.entry ?? CONTEXT_LIBRARY.find((e) => e.act === act);
    if (pick) {
      used.add(pick.id);
      result.push(pick);
    }
  }

  return result;
}

export function getActLabel(act: StoryAct): string {
  return ACT_LABELS[act];
}

export function getActTag(act: StoryAct): string {
  return ACT_TAGS[act];
}

export { ACT_ORDER, ACT_LABELS, ACT_TAGS };
