// coPilotCampaign.jsx — builds the outreach plan shown in the campaign modal.
// Copy adapts to BOTH the lead type and (for pre-claim leads) the phase:
//   requested  → responsive, fast, fewer touches (they already asked)
//   identified → surface the gap/need, a fuller educational sequence
//   partial    → gentle re-engage, invite them to finish the analysis
// The producer voice is the logged-in user, "Morgan Pierce" (the MP avatar).
//
// AGENT-OF-RECORD SPEC:
//   • Every campaign is FROM and signed by the policyholder's agent. For this demo
//     the logged-in producer (Morgan Pierce) is the agent of record on every policy,
//     so all outreach comes from Morgan. (See coPilotData.jsx — prevAgent / agent.)
//   • For BOTH beneficiary types (pre- and post-claim) the first two touches
//     explicitly introduce Morgan as the policy OWNER's agent, so the beneficiary
//     knows who is contacting them and why — there's a pre-established family
//     relationship on top of Helm. Pre-claim uses present tense ("I'm Robert's
//     agent"); post-claim references having handled the owner's claim together.

const PRODUCER = "Morgan Pierce";
const PRODUCER_FIRST = "Morgan";

const cpMoney = (n) => "$" + Number(n).toLocaleString("en-US");
const commissionFor = (base) => "$" + Math.round(base * 0.00215).toLocaleString("en-US");

const EMAIL = (to, subject, body) => ({ kind: "email", to, from: PRODUCER, subject, body });
const SMS = (to, text) => ({ kind: "sms", to, text });
const CALL = (who, note, opener, beats) => ({ kind: "call", who, note, opener, beats });

// step color/icon by channel
const CH = {
  email: { color: "var(--helm-purple)", icon: "email", label: "Email" },
  sms: { color: "var(--helm-blue)", icon: "sms", label: "SMS" },
  call: { color: "var(--helm-orange)", icon: "call", label: "Call" },
};
const step = (day, ch, short, note, content) => ({ day, kind: CH[ch].label, color: CH[ch].color, icon: CH[ch].icon, short, note, content });

// ===================================================================
function buildCampaign(lead) {
  if (lead.type === "policyholder_gap") return gapPlan(lead);
  if (lead.type === "bene_pre") return benePrePlan(lead);
  return postClaimPlan(lead);
}

// --------------------------------------------------- POLICYHOLDER GAP
function gapPlan(lead) {
  const to = lead.contact.email, phone = lead.contact.phone, n = lead.first;
  const gap = lead.recCoverage - lead.currentCoverage;
  const commission = commissionFor(gap);
  const phase = lead.phase;

  const status = [
    `Reviewing ${n}'s policy ${lead.policy} and Helm needs analysis`,
    `Sizing the gap: ${cpMoney(lead.currentCoverage)} held vs ${cpMoney(lead.recCoverage)} recommended`,
    phase === "requested" ? "Honoring their request, moving quickly to options"
      : phase === "partial" ? "Designing a gentle re-engagement, not a hard sell"
      : "Mapping a coverage-review sequence",
    `Writing each message in ${PRODUCER_FIRST}'s voice`,
    "Finalizing the plan",
  ];

  if (phase === "requested") {
    return {
      title: `A fast-track coverage plan for ${n}.`,
      kicker: "Policy owner · coverage gap · requesting contact",
      commission, buildStatus: status,
      steps: [
        step("Day 0", "email", "You asked, here's the plan",
          "First touch · automatic when you approve",
          EMAIL(to, `${n}, let's close that ${cpMoney(gap)} gap`, [
            `Hi ${n},`,
            `Thanks for flagging through Helm that you'd like to add coverage, and I'm glad you did. Your current ${lead.policy} sits at ${cpMoney(lead.currentCoverage)}, and the needs analysis you completed points to about ${cpMoney(lead.recCoverage)} given where your income and family are today.`,
            `That's roughly a ${cpMoney(gap)} gap. The good news: closing it is straightforward, and your existing Banner Life history works in your favor on rate.`,
            `I've sketched two options below. Reply with the one that resonates and I'll put exact numbers behind it, or grab 15 minutes with me this week.`,
            `Talk soon,`, PRODUCER,
          ])),
        step("Day 2", "email", "Two ways to close it",
          "Follows up with concrete options",
          EMAIL(to, `Two simple ways to get to ${cpMoney(lead.recCoverage)}`, [
            `Hi ${n},`,
            `Here are the two paths I mentioned, both keeping your current policy intact:`,
            `Option A: Add a ${cpMoney(gap)} Term 20 rider. Lowest monthly, covers the highest-obligation years.`,
            `Option B: Convert to a single ${cpMoney(lead.recCoverage)} Term 30. One policy, more breathing room, locked for 30 years.`,
            `Tell me which direction feels right and I'll send firm pricing same day.`,
            PRODUCER,
          ])),
        step("Day 5", "call", `${PRODUCER_FIRST} calls`,
          "You make this call · Helm drops talking points on your calendar",
          CALL(n, "Quick confirm-and-quote call", `"Hi ${n}, wanted to put a voice to the options and get you a number today."`, [
            "Open warmly · thank them for raising it",
            `Confirm the ${cpMoney(gap)} gap and which option fits`,
            "Walk the rate · note the Banner Life history credit",
            'Soft close · "Want me to prep the paperwork?"',
          ])),
        step("Day 8", "email", `Quote: ${cpMoney(lead.recCoverage)}`,
          "Sends after the call confirms a direction",
          EMAIL(to, `Your quote: ${cpMoney(lead.recCoverage)} total coverage`, [
            `Hi ${n},`,
            `Here's the quote from our call: total coverage of ${cpMoney(lead.recCoverage)}, Banner Life, carrying your existing medical-history credit.`,
            `Paperwork moves through Helm in about a week. Click below to e-sign, or reply if you'd like to adjust anything first.`,
            PRODUCER,
          ])),
      ],
    };
  }

  if (phase === "partial") {
    return {
      title: `A gentle re-engagement for ${n}.`,
      kicker: "Policy owner · coverage gap · partial analysis",
      commission, buildStatus: status,
      steps: [
        step("Day 0", "email", "Pick up where you left off",
          "First touch · automatic when you approve",
          EMAIL(to, `${n}, want to finish what you started?`, [
            `Hi ${n},`,
            `I noticed you began a coverage review in Helm but didn't get to the end. No problem at all, life gets busy.`,
            `From what you did complete, there may be room to strengthen your current ${cpMoney(lead.currentCoverage)} policy. It's only a few more questions to know for sure, and I'm happy to walk through them with you.`,
            `No pressure either way; just want to make sure nothing important is sitting half-finished.`,
            `Whenever you're ready,`, PRODUCER,
          ])),
        step("Day 5", "sms", "Light nudge",
          "Sends only if the Day 0 email isn't opened",
          SMS(phone, `Hi ${n}, ${PRODUCER_FIRST} here. No rush; whenever you want to finish that quick coverage review, I can wrap it up with you in 10 minutes. Just say the word.`)),
        step("Day 9", "email", "What we found so far",
          "Shares the partial picture, low-key",
          EMAIL(to, "A quick read on where your coverage stands", [
            `Hi ${n},`,
            `Even from a partial review, your current policy looks a little light for your stage. Finishing the analysis would tell us the exact number, but you're likely under-covered by a meaningful margin.`,
            `If you'd like, I can finish it for you over a 15-minute call. No quote pressure, just clarity.`,
            PRODUCER,
          ])),
        step("Day 14", "call", `${PRODUCER_FIRST} calls`,
          "You make this call · optional close",
          CALL(n, "Finish-the-analysis call", `"Hi ${n}, thought it'd be easier to just finish that review together. Got a few minutes?"`, [
            "Open warmly · no sales pressure",
            "Finish the remaining needs-analysis questions live",
            "Share the resulting number and what it means",
            'If interested, offer to send options',
          ])),
      ],
    };
  }

  // identified (default)
  return {
    title: `A coverage-review plan for ${n}.`,
    kicker: "Policy owner · coverage gap · needs identified",
    commission, buildStatus: status,
    steps: [
      step("Day 0", "email", "Surface the gap",
        "First touch · automatic when you approve",
        EMAIL(to, `${n}, a quick note about your coverage`, [
          `Hi ${n},`,
          `You recently completed a coverage needs analysis in Helm, and thank you. Reading through it, your current ${lead.policy} at ${cpMoney(lead.currentCoverage)} looks a bit light for where you are now.`,
          `The analysis points to closer to ${cpMoney(lead.recCoverage)}, about a ${cpMoney(gap)} gap. I don't think it's urgent, but it's worth a look while your rate is favorable.`,
          `Would you be open to 15 minutes to talk it through? No pitch, just want you to have the full picture.`,
          `Warmly,`, PRODUCER,
        ])),
      step("Day 4", "sms", "Light nudge",
        "Sends only if the Day 0 email isn't opened by Day 3",
        SMS(phone, `Hi ${n}, ${PRODUCER_FIRST} here. Just making sure my note didn't get buried; happy to walk through your coverage review whenever works.`)),
      step("Day 7", "email", "Two simple options",
        "Follows up with concrete options",
        EMAIL(to, `Two simple ways to close the ${cpMoney(gap)} gap`, [
          `Hi ${n},`,
          `No worries if last week ran long. Two straightforward options, both built on your existing policy:`,
          `Option A: Add a ${cpMoney(gap)} Term 20 rider. Lighter monthly, covers the key years.`,
          `Option B: Convert to a ${cpMoney(lead.recCoverage)} Term 30. One policy, more room, locked for 30 years.`,
          `Reply with the one that resonates and I'll put numbers behind it.`,
          PRODUCER,
        ])),
      step("Day 11", "call", `${PRODUCER_FIRST} calls`,
        "You make this call · Helm drops talking points on your calendar",
        CALL(n, "Talk-it-through call", `"Hi ${n}, wanted to put a voice to the notes I've been sending. Good time?"`, [
          "Open warmly · ask how things are going",
          `Frame the ${cpMoney(gap)} gap plainly`,
          "Walk Option A vs Option B at a high level",
          'Soft close · "Want me to put paperwork together?"',
        ])),
      step("Day 14", "email", `Quote: ${cpMoney(lead.recCoverage)}`,
        "Sends only after a direction is confirmed",
        EMAIL(to, `The quote we discussed: ${cpMoney(lead.recCoverage)}`, [
          `Hi ${n},`,
          `Here's the quote from our call: ${cpMoney(lead.recCoverage)} total coverage, Banner Life, carrying your existing medical-history credit.`,
          `Paperwork moves through Helm in about a week. Click below to e-sign, or reply to talk anything through first.`,
          PRODUCER,
        ])),
    ],
  };
}

// --------------------------------------------------- PRE-CLAIM BENEFICIARY
function benePrePlan(lead) {
  const to = lead.contact.email, phone = lead.contact.phone, n = lead.first;
  const rec = lead.recCoverage;
  const commission = commissionFor(rec);
  const phase = lead.phase;

  const status = [
    `Reviewing ${n}'s profile: beneficiary on ${lead.owner}'s policy`,
    `Sizing a recommendation near ${cpMoney(rec)} from the needs analysis`,
    phase === "requested" ? "Honoring their request; they asked to talk"
      : phase === "partial" ? "Designing a soft introduction, not a hard sell"
      : "Mapping a first-policy education sequence",
    `Writing each message in ${PRODUCER_FIRST}'s voice`,
    "Finalizing the plan",
  ];

  if (phase === "requested") {
    return {
      title: `A first-policy plan for ${n}.`,
      kicker: "Beneficiary · pre-claim · requesting contact",
      commission, buildStatus: status,
      steps: [
        step("Day 0", "email", "You asked, let's talk",
          "First touch · automatic when you approve",
          EMAIL(to, `${n}, great to connect about your own coverage`, [
            `Hi ${n},`,
            `I'm ${PRODUCER}, ${lead.owner}'s life insurance agent, and you're named as a beneficiary on their policy. Thanks for reaching out through Helm; I'd love to help you set up coverage of your own.`,
            `Now that there are people depending on you, it makes sense to have your own policy. Your needs analysis points to around ${cpMoney(rec)}. As a first policy that's very manageable, and starting young keeps the rate low for decades.`,
            `Want to grab 15 minutes this week? I'll walk you through it simply.`,
            `Talk soon,`, PRODUCER,
          ])),
        step("Day 3", "email", "How a first policy works",
          "Light education + two options",
          EMAIL(to, `Two simple ways to get to ${cpMoney(rec)}`, [
            `Hi ${n},`,
            `Following up as ${lead.owner}'s agent. A quick primer, then two options:`,
            `Option A: Term 20 at ${cpMoney(rec)}. Covers your highest-responsibility years at the lowest monthly.`,
            `Option B: Term 30 at ${cpMoney(rec)}. Locks today's rate for 30 years; ideal this young.`,
            `Reply with the one that resonates and I'll send real numbers.`,
            PRODUCER,
          ])),
        step("Day 6", "call", `${PRODUCER_FIRST} calls`,
          "You make this call · Helm drops talking points on your calendar",
          CALL(n, "Friendly first-policy call", `"Hi ${n}, excited to help you get your own policy in place. Got a few minutes?"`, [
            "Open warmly · this is likely their first policy",
            "Explain term vs whole in one plain sentence each",
            `Confirm the ${cpMoney(rec)} target and option`,
            'Soft close · "Want me to prep the application?"',
          ])),
        step("Day 9", "email", `Quote: ${cpMoney(rec)} Term 30`,
          "Sends after the call confirms a direction",
          EMAIL(to, `Your quote: ${cpMoney(rec)} Term 30-year`, [
            `Hi ${n},`,
            `Here's the quote from our call: ${cpMoney(rec)} Term 30-year, Banner Life. Locked for 30 years.`,
            `Paperwork is quick through Helm. Click below to e-sign, or reply with any questions.`,
            PRODUCER,
          ])),
      ],
    };
  }

  if (phase === "partial") {
    return {
      title: `A soft introduction for ${n}.`,
      kicker: "Beneficiary · pre-claim · partial analysis",
      commission, buildStatus: status,
      steps: [
        step("Day 0", "email", "A note as your family's beneficiary",
          "First touch · automatic when you approve",
          EMAIL(to, `${n}, a thought about coverage of your own`, [
            `Hi ${n},`,
            `I'm ${PRODUCER}, ${lead.owner}'s life insurance agent, and you're named as a beneficiary on their policy. I noticed you recently started looking at coverage for yourself in Helm, then didn't finish. Totally fine, it's a lot to think about.`,
            `If it's helpful, I can answer the basics with zero pressure. Sometimes a first policy is simpler and cheaper than people expect, especially young.`,
            `No rush at all. Just here when you want to pick it back up.`,
            `Warmly,`, PRODUCER,
          ])),
        step("Day 5", "sms", "Light nudge",
          "Sends only if the Day 0 email isn't opened",
          SMS(phone, `Hi ${n}, it's ${PRODUCER_FIRST}, ${lead.owner}'s insurance agent. Whenever you want to finish that quick coverage review, I can wrap it up with you in 10 minutes, no pressure.`)),
        step("Day 10", "email", "The basics, simply",
          "Gentle education, low-key",
          EMAIL(to, "Coverage of your own: the short version", [
            `Hi ${n},`,
            `Three quick things people in your spot usually want to know: it's cheaper the younger you start, term is the simple low-cost path, and a quick chat is enough to size it.`,
            `If you'd like, I can finish your needs analysis over a 15-minute call and tell you the exact number.`,
            PRODUCER,
          ])),
        step("Day 15", "call", `${PRODUCER_FIRST} calls`,
          "You make this call · optional",
          CALL(n, "Finish-the-analysis call", `"Hi ${n}, thought it'd be easier to just finish that review together. Few minutes?"`, [
            "Open warmly · no sales pressure",
            "Finish the remaining questions live",
            "Share the resulting number plainly",
            "If interested, offer to send options",
          ])),
      ],
    };
  }

  // identified (default)
  return {
    title: `A first-policy plan for ${n}.`,
    kicker: "Beneficiary · pre-claim · needs identified",
    commission, buildStatus: status,
    steps: [
      step("Day 0", "email", "Coverage of your own",
        "First touch · automatic when you approve",
        EMAIL(to, `${n}, a quick note about your own coverage`, [
          `Hi ${n},`,
          `I'm ${PRODUCER}, ${lead.owner}'s life insurance agent, and you're named as a beneficiary on their policy. You recently completed a coverage needs analysis in Helm (nice work); it suggests it's worth having coverage of your own, around ${cpMoney(rec)}.`,
          `As a first policy that's very manageable, and your age works strongly in your favor on rate.`,
          `Would you be open to 15 minutes to talk it through? No pressure. Just want you to have the full picture.`,
          `Warmly,`, PRODUCER,
        ])),
      step("Day 4", "sms", "Light nudge",
        "Sends only if the Day 0 email isn't opened by Day 3",
        SMS(phone, `Hi ${n}, it's ${PRODUCER_FIRST}, ${lead.owner}'s insurance agent. Just making sure my note didn't get buried; happy to walk through coverage options whenever works.`)),
      step("Day 7", "email", "Two simple options",
        "Follows up with concrete options",
        EMAIL(to, `Two simple ways to get to ${cpMoney(rec)}`, [
          `Hi ${n},`,
          `Two straightforward paths for a first policy:`,
          `Option A: Term 20 at ${cpMoney(rec)}. Lowest monthly, covers the key years.`,
          `Option B: Term 30 at ${cpMoney(rec)}. Locks today's young rate for 30 years.`,
          `Reply with the one that resonates and I'll put numbers behind it.`,
          PRODUCER,
        ])),
      step("Day 11", "call", `${PRODUCER_FIRST} calls`,
        "You make this call · Helm drops talking points on your calendar",
        CALL(n, "Talk-it-through call", `"Hi ${n}, wanted to put a voice to the notes I've been sending. Good time?"`, [
          "Open warmly · likely their first policy",
          "Explain term vs whole in plain terms",
          `Confirm the ${cpMoney(rec)} target and option`,
          'Soft close · "Want me to prep the application?"',
        ])),
      step("Day 14", "email", `Quote: ${cpMoney(rec)} Term 30`,
        "Sends only after a direction is confirmed",
        EMAIL(to, `The quote we discussed: ${cpMoney(rec)} Term 30-year`, [
          `Hi ${n},`,
          `Here's the quote from our call: ${cpMoney(rec)} Term 30-year, Banner Life. Locked for 30 years.`,
          `Paperwork is quick through Helm. Click below to e-sign, or reply with any questions.`,
          PRODUCER,
        ])),
    ],
  };
}

// --------------------------------------------------- POST-CLAIM BENEFICIARY
function postClaimPlan(lead) {
  const to = lead.contact.email, phone = lead.contact.phone, n = lead.first;
  const rec = lead.recCoverage;
  const commission = commissionFor(rec);

  return {
    title: `A 14-day check-in plan for ${n}.`,
    kicker: "Beneficiary · post-claim",
    commission,
    buildStatus: [
      `Reviewing ${n}'s profile and recent activity`,
      `Weighing the coverage need from ${lead.owner}'s claim`,
      "Mapping a 14-day, five-touch sequence",
      `Writing each message in ${PRODUCER_FIRST}'s voice`,
      "Finalizing the plan",
    ],
    steps: [
      step("Day 0", "email", "Personal check-in",
        "First touch · automatic when you approve the plan",
        EMAIL(to, `Checking in, ${n}, and one thought about the family plan`, [
          `Hi ${n},`,
          `It's ${PRODUCER}. I handled ${lead.owner}'s life insurance policy, and I helped you through the claim earlier this year. I hope this finds you and the family settling into a steadier rhythm; it's been a couple of months since we closed everything out, and I wanted to check in.`,
          `Going back through the plan you built with Helm, I think this is a good moment to make sure your own coverage holds the shape of what you're building for the people who count on you. The proceeds in your Helm Cash account give us room to design that without anything feeling rushed.`,
          `If you'd be open to it, I'd love 15 minutes next week. No pitch, just a check-in.`,
          `With care,`, PRODUCER,
        ])),
      step("Day 4", "sms", "Light nudge",
        "Sends only if the Day 0 email isn't opened by Day 3",
        SMS(phone, `Hey ${n}, it's ${PRODUCER_FIRST}, ${lead.owner}'s agent who helped with the claim. Just wanted to make sure my note didn't get lost in the shuffle. No rush at all. Let me know whenever works for a quick chat.`)),
      step("Day 7", "email", "Two simple options",
        "Follows up with concrete options",
        EMAIL(to, "Two simple options for the family plan", [
          `Hi ${n},`,
          `No worries if last week ran long. Two simple options, both keeping the people who depend on you covered without overshooting.`,
          `Option A: Term 20 at ${cpMoney(rec - 50000)}. Lower monthly, lighter footprint.`,
          `Option B: Term 30 at ${cpMoney(rec)}. A little more breathing room, carries further out.`,
          `Reply with the one that resonates and I'll put numbers behind it.`,
          PRODUCER,
        ])),
      step("Day 11", "call", `${PRODUCER_FIRST} calls`,
        "You make this call · Helm puts notes on your calendar",
        CALL(n, "Warm check-in call", `"Hey ${n}, wanted to put a voice to the notes I've been sending. How are you doing?"`, [
          "Open warmly · ask how the family is",
          `Reference ${lead.owner}'s policy without dwelling`,
          "Walk through Option A vs Option B at a high level",
          'Soft close · "Want me to put paperwork together?"',
        ])),
      step("Day 14", "email", `Quote: ${cpMoney(rec)} T-30`,
        "Sends only after a direction is confirmed",
        EMAIL(to, `The quote we discussed: ${cpMoney(rec)} Term 30-year`, [
          `Hi ${n},`,
          `Here's the quote from our call. ${cpMoney(rec)} Term 30-year, Banner Life, with the same medical-history credit ${lead.owner}'s policy carried.`,
          `Locked for 30 years. Paperwork can move through Helm in about a week.`,
          `If this still feels right, click below to e-sign. If you want to talk anything through first, just hit reply.`,
          PRODUCER,
        ])),
    ],
  };
}

Object.assign(window, { CP_buildCampaign: buildCampaign, CP_PRODUCER: PRODUCER });
