/* global window */
// Channel resolver — minimal. The action stays the same; only the
// communication channel varies. Resolver picks one channel and returns up
// to two alternatives the user can switch to. UI does the rest.

const CHANNEL_LABEL = {
  whatsapp: "WhatsApp",
  slack:    "Slack",
  linkedin: "LinkedIn",
  email:    "Email",
  calendar: "Calendar",
  phone:    "Phone",
  crm:      "CRM",
};

const CHANNEL_ICON = {
  whatsapp: "chat",
  slack:    "hash",
  linkedin: "users",
  email:    "mail",
  calendar: "calendar",
  phone:    "phone",
  crm:      "note",
};

// Rules are first-match-wins over an ordered candidate list. Each candidate
// is added only if it's connected and the relationship/action shape supports
// it. Email is the floor.
function recommendChannel(ctx) {
  const a = ctx.action || {};
  const c = ctx.contact || {};
  const active = ctx.activeChannels || {};
  const f = (ch) => (c.communicationFrequencyByChannel || {})[ch] || "none";
  const strong = c.relationshipStrength === "strong" || c.relationshipStrength === "medium";

  const ranked = [];
  const add = (ch) => { if (active[ch] && !ranked.includes(ch)) ranked.push(ch); };

  // Calendar wins outright when the missing proof is a dated next step.
  if (a.missingEvidence === "next_step") add("calendar");

  // Champion / influencer with high WhatsApp use → WhatsApp leads.
  if (["champion", "influencer"].includes(c.role) && strong && f("whatsapp") !== "none" &&
      (a.formality !== "formal")) {
    add("whatsapp");
  }
  // Champion / technical evaluator with active Slack → Slack leads.
  if (["champion", "technical_evaluator", "influencer"].includes(c.role) && f("slack") !== "none" &&
      (a.formality !== "formal")) {
    add("slack");
  }
  // Weak / unknown ties or stakeholder mapping → LinkedIn early touch.
  if ((c.relationshipStrength === "weak" || c.relationshipStrength === "unknown" || a.missingEvidence === "stakeholder_map") &&
      a.formality !== "formal") {
    add("linkedin");
  }
  // Email is always available as a fallback / formal path.
  add("email");
  // CRM as final floor.
  add("crm");

  const primary = ranked[0] || "email";
  // Surface up to two distinct alternatives that make sense as a switch.
  const alternatives = ranked.filter((ch) => ch !== primary).slice(0, 2);
  return { primary, alternatives };
}

// Adapt a long-form (email-style) body to a shorter channel. The action
// stays — only length and tone change. Subject is dropped for chat-style
// channels; the body is collapsed to the first 1–2 substantive sentences.
function adaptDraftToChannel(channel, draft, contact) {
  if (!draft) return draft;
  if (channel === "email" || channel === "calendar") return draft;

  const first = (contact && contact.name && contact.name.split(" ")[0]) || "there";
  const lines = (draft.body || "").split("\n").map((l) => l.trim()).filter(Boolean);
  // Skip greeting + sign-off lines; keep the substantive middle.
  const middle = lines.filter((l) =>
    !/^Hi\b/i.test(l) &&
    !/^Thanks?\b/i.test(l) &&
    !/^Cheers\b/i.test(l) &&
    !/^Ridha$/i.test(l)
  );
  const sentences = middle.join(" ").split(/(?<=[.?!])\s+/).filter(Boolean);
  const keep = channel === "whatsapp" ? 1 : 2;
  const core = sentences.slice(0, keep).join(" ");

  let body;
  if (channel === "whatsapp") {
    body = `Hey ${first} — ${core}`;
  } else if (channel === "slack") {
    body = `Quick one — ${core}`;
  } else if (channel === "linkedin") {
    body = `Hi ${first} — ${core}`;
  } else if (channel === "phone") {
    body = `Talking points: ${core}`;
  } else if (channel === "crm") {
    body = `Internal task: ${core}`;
  } else {
    body = core;
  }

  return { ...draft, channel, subject: "", body };
}

// Convenience: build a resolver context from a deal + nudge index using the
// EXECUTION_CONTEXT mock layer. nudgeIdx may be a number or "diag".
function executionContextFor(deal, nudgeIdx) {
  const ec = (window.EXECUTION_CONTEXT || {})[deal.id] || {};
  const attrs = nudgeIdx === "diag"
    ? (ec.diagAttrs || {})
    : ((ec.nudgeAttrs || [])[nudgeIdx] || ec.diagAttrs || {});
  const contactName = attrs.contact || deal.champion;
  const contactMeta = (ec.contacts && ec.contacts[contactName]) || {};
  return {
    activeChannels: window.ACTIVE_CHANNELS || {},
    contact: {
      name: contactName,
      role: contactMeta.role || "unknown",
      relationshipStrength: contactMeta.relationshipStrength || "unknown",
      communicationFrequencyByChannel: contactMeta.channelFrequency || {},
    },
    action: {
      missingEvidence: attrs.missingEvidence || "next_step",
      formality:       attrs.formality       || "neutral",
    },
  };
}

window.recommendChannel = recommendChannel;
window.adaptDraftToChannel = adaptDraftToChannel;
window.executionContextFor = executionContextFor;
window.CHANNEL_LABEL = CHANNEL_LABEL;
window.CHANNEL_ICON = CHANNEL_ICON;
