// Note templates: pre-built starting documents so a new note can look
// intentional from the first click instead of a blank page. Built-in and
// free for now — `origin` exists so a future template marketplace can add
// purchasable entries without changing how templates are consumed.

export type NoteTemplateCategory =
  | "work"
  | "productivity"
  | "learning"
  | "personal"
  | "creative"
  | "custom";

export interface NoteTemplate {
  id: string;
  name: string;
  description: string;
  category: NoteTemplateCategory;
  icon: string;
  // "builtin" ships with Mindavio. "custom" was created by a user from one of
  // their own notes and published to the marketplace (note_design_templates).
  origin: "builtin" | "custom";
  // EUR cents. 0 = free. Same purchase system as covers/stickers.
  price: number;
  content: Record<string, unknown>;
  // Only set for origin: "custom".
  creatorId?: string;
  // Bundled note cover (see note-covers.ts) applied automatically when this
  // template is used — part of what makes an exclusive template feel like a
  // complete package instead of just text.
  coverId?: string;
  // Flags Mindavio's premium flagship templates for separate, elevated
  // presentation in the marketplace (not mixed into the regular grid).
  exclusive?: boolean;
  // Short questions asked right before the note is created — answers replace
  // matching {{key}} tokens in the content so the template starts personalized
  // instead of full of generic placeholders.
  wizardQuestions?: Array<{ key: string; label: string; placeholder?: string }>;
  // When set, using this template also schedules a recurring reminder for the
  // ritual the template is built around (e.g. a weekly review).
  reminderBlueprint?: {
    title: string;
    recurrenceRule: "weekly" | "monthly";
  };
}

export const CATEGORY_META: Record<
  NoteTemplateCategory,
  { label: string; accent: string; icon: string; ring: string; text: string }
> = {
  work: {
    label: "Work",
    accent: "bg-indigo-500/12",
    icon: "bg-indigo-500/15 text-indigo-300",
    ring: "border-indigo-500/20",
    text: "text-indigo-300",
  },
  productivity: {
    label: "Productivity",
    accent: "bg-sky-500/12",
    icon: "bg-sky-500/15 text-sky-300",
    ring: "border-sky-500/20",
    text: "text-sky-300",
  },
  learning: {
    label: "Learning",
    accent: "bg-amber-500/12",
    icon: "bg-amber-500/15 text-amber-300",
    ring: "border-amber-500/20",
    text: "text-amber-300",
  },
  personal: {
    label: "Personal",
    accent: "bg-emerald-500/12",
    icon: "bg-emerald-500/15 text-emerald-300",
    ring: "border-emerald-500/20",
    text: "text-emerald-300",
  },
  creative: {
    label: "Creative",
    accent: "bg-violet-500/12",
    icon: "bg-violet-500/15 text-violet-300",
    ring: "border-violet-500/20",
    text: "text-violet-300",
  },
  custom: {
    label: "Community",
    accent: "bg-pink-500/12",
    icon: "bg-pink-500/15 text-pink-300",
    ring: "border-pink-500/20",
    text: "text-pink-300",
  },
};

function paragraph(text = "") {
  return {
    type: "paragraph",
    content: text ? [{ type: "text", text }] : [],
  };
}

function heading(text: string, level: 1 | 2 | 3 = 2) {
  return {
    type: "heading",
    attrs: { level },
    content: [{ type: "text", text }],
  };
}

function bulletList(items: string[]) {
  return {
    type: "bulletList",
    content: items.map((text) => ({
      type: "listItem",
      content: [paragraph(text)],
    })),
  };
}

function taskList(items: string[]) {
  return {
    type: "taskList",
    content: items.map((text) => ({
      type: "taskItem",
      attrs: { checked: false },
      content: [paragraph(text)],
    })),
  };
}

function quote(text: string) {
  return { type: "blockquote", content: [paragraph(text)] };
}

function tableRow(cells: string[], header = false): Record<string, unknown> {
  return {
    type: "tableRow",
    content: cells.map((text) => ({
      type: header ? "tableHeader" : "tableCell",
      content: [paragraph(text)],
    })),
  };
}

function table(headers: string[], rows: string[][]): Record<string, unknown> {
  return {
    type: "table",
    content: [tableRow(headers, true), ...rows.map((row) => tableRow(row))],
  };
}

function chart(
  title: string,
  chartType: "bar" | "line" | "pie",
  data: Array<{ label: string; value: number }>
): Record<string, unknown> {
  return { type: "chartBlock", attrs: { title, chartType, data } };
}

// A "live" chart computes its data from the user's own Mindavio data
// (tasks, journal) when the note is opened, instead of static numbers.
function liveChart(
  title: string,
  chartType: "bar" | "line" | "pie",
  dataSource: { type: "task_completion_rate" | "journal_mood_trend"; days?: number },
): Record<string, unknown> {
  return { type: "chartBlock", attrs: { title, chartType, data: [], dataSource } };
}

function actionChecklist(items: string[]): Record<string, unknown> {
  return { type: "actionChecklist", attrs: { items: items.map((text) => ({ text, done: false })), tasksCreated: false } };
}

function doc(...content: Record<string, unknown>[]): Record<string, unknown> {
  return { type: "doc", content };
}

export const NOTE_TEMPLATES: NoteTemplate[] = [
  {
    id: "meeting",
    name: "Meeting notes",
    description: "Agenda, decisions, and action items that don't get lost",
    category: "work",
    icon: "📋",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Context"),
      bulletList(["Date / time:", "Attendees:", "Goal of this meeting:"]),
      heading("Agenda"),
      bulletList(["Topic 1", "Topic 2", "Topic 3"]),
      heading("Decisions"),
      bulletList(["Decision —", "Owner —", "Deadline —"]),
      heading("Action items"),
      taskList(["Send summary to attendees", "Follow up on open question", "Schedule next check-in"]),
    ),
  },
  {
    id: "project-brief",
    name: "Project brief",
    description: "Goal, scope, and milestones on one page",
    category: "work",
    icon: "🧭",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Goal"),
      paragraph("What does success look like?"),
      heading("Scope"),
      bulletList(["In scope —", "Out of scope —"]),
      heading("Stakeholders"),
      bulletList(["Owner —", "Approver —", "Contributors —"]),
      heading("Milestones"),
      taskList(["Kickoff", "First draft / prototype", "Review", "Ship"]),
      heading("Risks"),
      bulletList(["Risk —", "Mitigation —"]),
    ),
  },
  {
    id: "decision-log",
    name: "Decision log",
    description: "Capture the reasoning so future-you remembers why",
    category: "work",
    icon: "⚖️",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Decision"),
      paragraph("What was decided?"),
      heading("Context"),
      paragraph("What problem or question triggered this?"),
      heading("Options considered"),
      bulletList(["Option A —", "Option B —", "Option C —"]),
      heading("Why this one"),
      quote("The deciding factor was..."),
      heading("Follow-up"),
      taskList(["Communicate the decision", "Update relevant docs", "Revisit in 30 days"]),
    ),
  },
  {
    id: "daily-planner",
    name: "Daily planner",
    description: "Three priorities, a schedule, and a clean close to the day",
    category: "productivity",
    icon: "☀️",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Today's top 3"),
      taskList(["Priority 1", "Priority 2", "Priority 3"]),
      heading("Schedule"),
      bulletList(["Morning —", "Afternoon —", "Evening —"]),
      heading("Notes"),
      paragraph(""),
      heading("End of day"),
      bulletList(["What moved forward?", "What carries over to tomorrow?"]),
    ),
  },
  {
    id: "weekly-review",
    name: "Weekly review",
    description: "Wins, blockers, lessons — then next week's focus",
    category: "productivity",
    icon: "📅",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Wins"),
      bulletList(["What went well?", "What moved forward?", "What gave energy?"]),
      heading("Blockers"),
      bulletList(["What slowed things down?", "What needs a decision?"]),
      heading("Lessons"),
      bulletList(["What did I learn?", "What should I repeat?", "What should I stop?"]),
      heading("Next week"),
      taskList(["Top priority", "Protect one thing", "Delegate or delete one thing"]),
    ),
  },
  {
    id: "brainstorm",
    name: "Brainstorm dump",
    description: "Get every idea out first, sort it out after",
    category: "creative",
    icon: "💡",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Prompt"),
      paragraph("What are you trying to solve or explore?"),
      heading("Every idea, no filter"),
      bulletList(["Idea —", "Idea —", "Idea —"]),
      heading("Best ones so far"),
      quote("Circle back to these first."),
    ),
  },
  {
    id: "study-notes",
    name: "Cornell study notes",
    description: "Key questions, notes, and a summary that sticks",
    category: "learning",
    icon: "🎓",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Topic"),
      paragraph(""),
      heading("Key questions / cues"),
      bulletList(["Question —", "Question —"]),
      heading("Notes"),
      paragraph(""),
      heading("Summary"),
      quote("In one or two sentences, what's the core idea?"),
    ),
  },
  {
    id: "reading-notes",
    name: "Reading notes",
    description: "Takeaways and quotes worth keeping from a book or article",
    category: "learning",
    icon: "📚",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Source"),
      bulletList(["Title —", "Author —", "Link —"]),
      heading("Key takeaways"),
      taskList(["Takeaway 1", "Takeaway 2", "Takeaway 3"]),
      heading("Favorite quotes"),
      quote("Quote goes here."),
      heading("How I'll apply this"),
      paragraph(""),
    ),
  },
  {
    id: "goal-tracker",
    name: "Goal tracker",
    description: "Why it matters, the milestones, and a weekly check-in",
    category: "personal",
    icon: "🎯",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Goal"),
      paragraph(""),
      heading("Why this matters"),
      quote("The real reason behind this goal."),
      heading("Milestones"),
      taskList(["Milestone 1", "Milestone 2", "Milestone 3"]),
      heading("Weekly check-in"),
      bulletList(["Progress —", "Adjustment needed —"]),
    ),
  },
  {
    id: "daily-reflection",
    name: "Daily reflection",
    description: "A two-minute check-in with yourself",
    category: "personal",
    icon: "🌙",
    origin: "builtin",
    price: 0,
    content: doc(
      heading("Grateful for"),
      paragraph(""),
      heading("Today's win"),
      paragraph(""),
      heading("What was hard"),
      paragraph(""),
      heading("Tomorrow, I'll focus on"),
      paragraph(""),
    ),
  },
  // Exclusive, paid flagship templates — real tables, live charts wired to
  // the user's own data, action checklists that create real tasks, a
  // personalization wizard, and a bundled premium cover + recurring
  // reminder — a complete package, not just headings.
  {
    id: "exclusive-founders-os",
    name: "Founder's OS",
    description: "The command center serious founders run their company from — OKRs, live momentum chart, risk register.",
    category: "work",
    icon: "🚀",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "midnight-aurora",
    wizardQuestions: [
      { key: "company", label: "Company / project name", placeholder: "Acme Inc." },
      { key: "goal", label: "This quarter's #1 goal", placeholder: "Hit €50k MRR" },
    ],
    reminderBlueprint: { title: "Weekly founder review", recurrenceRule: "weekly" },
    content: doc(
      heading("{{company}} — Founder's OS", 1),
      quote("What gets measured gets built."),
      heading("This Quarter's OKRs"),
      table(
        ["Objective", "Key Result", "Target", "Status"],
        [
          ["{{goal}}", "MRR", "€50k", "On track"],
          ["Ship the core product", "Public launch", "Q-end", "At risk"],
          ["Build the team", "Key hires", "2", "Not started"],
        ],
      ),
      heading("Momentum — tasks shipped per week"),
      liveChart("Tasks completed", "bar", { type: "task_completion_rate", days: 28 }),
      heading("Weekly Scoreboard"),
      actionChecklist(["Customer calls booked", "Ship one meaningful improvement", "Review burn + runway", "Update the board / investors"]),
      heading("Stakeholder Map"),
      bulletList(["Who needs to be informed —", "Who needs to approve —", "Who's blocked on you —"]),
      heading("Decision Log"),
      quote("Decision — Context — Why this one — Revisit by —"),
      heading("Risk Register"),
      table(
        ["Risk", "Likelihood", "Mitigation"],
        [
          ["Key customer churns", "Medium", "—"],
          ["Runway < 6 months", "Low", "—"],
        ],
      ),
    ),
  },
  {
    id: "exclusive-life-architecture",
    name: "Life Architecture",
    description: "A premium life dashboard — values, yearly pillars, a live mood chart, and a monthly review ritual.",
    category: "personal",
    icon: "🏛️",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "cherry-blossom",
    wizardQuestions: [{ key: "year_theme", label: "One word for this year", placeholder: "Momentum" }],
    reminderBlueprint: { title: "Monthly life review", recurrenceRule: "monthly" },
    content: doc(
      heading("Life Architecture — {{year_theme}}", 1),
      quote("Design the life, don't just react to it."),
      heading("Core Values"),
      bulletList(["Value —", "Value —", "Value —"]),
      heading("This Year's Pillars"),
      table(
        ["Pillar", "Why it matters", "This year's target"],
        [
          ["Health", "—", "—"],
          ["Craft / Career", "—", "—"],
          ["Relationships", "—", "—"],
          ["Money", "—", "—"],
        ],
      ),
      heading("Mood & Energy — last 4 weeks"),
      liveChart("Mood trend", "line", { type: "journal_mood_trend", days: 28 }),
      heading("Monthly Review Ritual"),
      actionChecklist(["Revisit the pillars", "What moved — what stalled", "One thing to cut next month", "One thing to go all-in on"]),
      heading("Reflection Prompts"),
      quote("If this year went perfectly, what would be different by December?"),
    ),
  },
  {
    id: "exclusive-launch-playbook",
    name: "Launch Playbook",
    description: "Everything a product launch needs — countdown checklist, channel plan, live task burn-down.",
    category: "work",
    icon: "🛰️",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "golden-hour",
    wizardQuestions: [
      { key: "product", label: "What's launching?", placeholder: "Mindavio 2.0" },
      { key: "launch_date", label: "Target launch date", placeholder: "2026-11-15" },
    ],
    reminderBlueprint: { title: "Launch readiness check-in", recurrenceRule: "weekly" },
    content: doc(
      heading("{{product}} — Launch Playbook", 1),
      quote("Launch date: {{launch_date}}"),
      heading("Pre-launch Checklist"),
      actionChecklist(["Landing page live", "Pricing finalized", "Support docs written", "Press / community list ready", "Rollback plan written"]),
      heading("Channel Plan"),
      table(
        ["Channel", "Owner", "Status"],
        [
          ["Email", "—", "—"],
          ["Social", "—", "—"],
          ["Product Hunt / communities", "—", "—"],
          ["Paid", "—", "—"],
        ],
      ),
      heading("Burn-down — tasks completed this week"),
      liveChart("Launch tasks shipped", "bar", { type: "task_completion_rate", days: 21 }),
      heading("Post-launch Retro"),
      bulletList(["What worked —", "What broke —", "What we'd do differently —"]),
    ),
  },
  {
    id: "exclusive-investor-update",
    name: "Investor Update",
    description: "The monthly update format investors actually read — metrics, asks, and a clean narrative.",
    category: "work",
    icon: "📈",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "ocean-deep",
    wizardQuestions: [
      { key: "company", label: "Company name", placeholder: "Acme Inc." },
      { key: "month", label: "Reporting month", placeholder: "October 2026" },
    ],
    reminderBlueprint: { title: "Send investor update", recurrenceRule: "monthly" },
    content: doc(
      heading("{{company}} — Investor Update, {{month}}", 1),
      heading("Headline"),
      quote("One sentence — the single most important thing that happened this month."),
      heading("Key Metrics"),
      table(
        ["Metric", "This month", "Last month", "Target"],
        [
          ["Revenue", "—", "—", "—"],
          ["Active customers", "—", "—", "—"],
          ["Burn rate", "—", "—", "—"],
          ["Runway (months)", "—", "—", "—"],
        ],
      ),
      heading("Execution — tasks shipped this month"),
      liveChart("Tasks completed", "bar", { type: "task_completion_rate", days: 30 }),
      heading("Wins"),
      bulletList(["Win —", "Win —"]),
      heading("Challenges"),
      bulletList(["Challenge — and what we're doing about it —"]),
      heading("The Ask"),
      quote("What do you specifically need from investors this month — intros, hires, advice?"),
    ),
  },
  {
    id: "exclusive-content-engine",
    name: "Content Engine",
    description: "A real content operation — idea backlog, publishing calendar, and a repurposing system.",
    category: "creative",
    icon: "🎬",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "berry-punch",
    wizardQuestions: [{ key: "niche", label: "What do you create content about?", placeholder: "Indie SaaS building" }],
    reminderBlueprint: { title: "Weekly content planning", recurrenceRule: "weekly" },
    content: doc(
      heading("Content Engine — {{niche}}", 1),
      quote("One system, every platform — not a new plan every week."),
      heading("Idea Backlog"),
      bulletList(["Idea —", "Idea —", "Idea —", "Idea —"]),
      heading("This Week's Publishing Calendar"),
      table(
        ["Day", "Platform", "Topic", "Status"],
        [
          ["Mon", "—", "—", "Idea"],
          ["Wed", "—", "—", "Idea"],
          ["Fri", "—", "—", "Idea"],
        ],
      ),
      heading("Production Checklist"),
      actionChecklist(["Outline drafted", "Draft written", "Edited", "Thumbnail / cover made", "Scheduled", "Repurposed into 2 more formats"]),
      heading("What's Working — posts shipped this month"),
      liveChart("Content shipped", "bar", { type: "task_completion_rate", days: 30 }),
      heading("Repurposing Map"),
      bulletList(["Long-form → thread —", "Long-form → short video —", "Long-form → newsletter —"]),
    ),
  },
  {
    id: "exclusive-money-map",
    name: "Money Map",
    description: "A real financial control panel — budget, net worth tracker, and a monthly money date ritual.",
    category: "personal",
    icon: "💰",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "desert-dune",
    wizardQuestions: [{ key: "money_goal", label: "What's your #1 money goal right now?", placeholder: "Save 3 months of runway" }],
    reminderBlueprint: { title: "Monthly money date", recurrenceRule: "monthly" },
    content: doc(
      heading("Money Map", 1),
      quote("Goal: {{money_goal}}"),
      heading("Monthly Budget"),
      table(
        ["Category", "Planned", "Actual"],
        [
          ["Essentials", "—", "—"],
          ["Savings / investing", "—", "—"],
          ["Discretionary", "—", "—"],
        ],
      ),
      heading("Net Worth Snapshot"),
      table(
        ["", "This month", "Last month"],
        [
          ["Assets", "—", "—"],
          ["Liabilities", "—", "—"],
          ["Net worth", "—", "—"],
        ],
      ),
      heading("Spending Trend"),
      chart("Discretionary spending", "line", [
        { label: "W1", value: 0 },
        { label: "W2", value: 0 },
        { label: "W3", value: 0 },
        { label: "W4", value: 0 },
      ]),
      heading("Monthly Money Date"),
      actionChecklist(["Review all accounts", "Update net worth", "Check progress toward the goal", "Pick one thing to improve next month"]),
    ),
  },
  {
    id: "exclusive-deep-work-season",
    name: "Deep Work Season",
    description: "A quarter of serious focus — one priority, protected blocks, and a live completion chart.",
    category: "productivity",
    icon: "🧠",
    origin: "builtin",
    price: 500,
    exclusive: true,
    coverId: "nebula-violet",
    wizardQuestions: [{ key: "focus", label: "What's the one thing you're going deep on?", placeholder: "Ship the v2 rewrite" }],
    reminderBlueprint: { title: "Deep work weekly check-in", recurrenceRule: "weekly" },
    content: doc(
      heading("Deep Work Season", 1),
      quote("The one thing: {{focus}}"),
      heading("Why This, Why Now"),
      paragraph(""),
      heading("Protected Blocks"),
      bulletList(["Mon —", "Tue —", "Wed —", "Thu —", "Fri —"]),
      heading("Guardrails"),
      bulletList(["What I'm saying no to this season —", "What gets delegated —", "What gets deleted —"]),
      heading("Progress — tasks completed per week"),
      liveChart("Deep work output", "line", { type: "task_completion_rate", days: 28 }),
      heading("Weekly Check-in"),
      actionChecklist(["Protected blocks actually protected?", "Real progress on the one thing", "Adjust next week's blocks"]),
    ),
  },
];

export const NOTE_TEMPLATE_CATEGORIES: NoteTemplateCategory[] = [
  "work",
  "productivity",
  "learning",
  "personal",
  "creative",
  "custom",
];

export function getNoteTemplate(id: string | undefined | null): NoteTemplate | undefined {
  if (!id) return undefined;
  return NOTE_TEMPLATES.find((template) => template.id === id);
}

// Kept for callers that never need the visual template metadata.
export function buildTemplateContent(templateId?: string): Record<string, unknown> | undefined {
  return getNoteTemplate(templateId)?.content;
}

// Replaces {{key}} tokens (in text nodes and string attrs) with the
// personalization wizard's answers — unanswered tokens become "".
export function fillTemplatePlaceholders(
  content: Record<string, unknown>,
  answers: Record<string, string>
): Record<string, unknown> {
  function replaceText(text: string): string {
    return text.replace(/\{\{(\w+)\}\}/g, (_match, key: string) => answers[key] ?? "");
  }

  function walk(node: unknown): unknown {
    if (Array.isArray(node)) return node.map(walk);
    if (node && typeof node === "object") {
      const source = node as Record<string, unknown>;
      const copy: Record<string, unknown> = { ...source };
      if (typeof copy.text === "string") copy.text = replaceText(copy.text);
      if (copy.content !== undefined) copy.content = walk(copy.content);
      if (copy.attrs && typeof copy.attrs === "object") {
        const attrs = copy.attrs as Record<string, unknown>;
        const newAttrs: Record<string, unknown> = {};
        for (const [attrKey, attrValue] of Object.entries(attrs)) {
          newAttrs[attrKey] = typeof attrValue === "string" ? replaceText(attrValue) : attrValue;
        }
        copy.attrs = newAttrs;
      }
      return copy;
    }
    return node;
  }

  return walk(content) as Record<string, unknown>;
}
