/* global React, PERSONA_DEFS, NET_COMPANIES */
// ============================================================
// Get introduced — UNIFIED NETWORK MAP data.
// One map overlays the warmest paths across the user's ENTIRE target list.
// Everything is grouped BY COMPANY: a company is a cluster (sub-graph) of the
// PEOPLE you can reach there. A specifically-targeted individual is just a
// company cluster that happens to hold one person. So the outer ring is
// company clusters; people live INSIDE them. The goal is to surface
// SUPER-CONNECTORS: the few contacts whose one intro unlocks the most.
//
// Reach is individual-only (no team networks), 1st or 2nd degree:
//   1st (direct): you already know them.
//   2nd (warm intro): one contact you know introduces you.
// ============================================================

const MAP_UPDATED = "2 hours ago";

// ---- Your 1st-degree contacts (the people you actually know) ----
const MAP_INTRODUCERS = [
  { id: "jordan", name: "Jordan Mehta", title: "PM at Ramp · ex-Plaid", tone: "slate", hero: true },
  { id: "nadia",  name: "Nadia Rahman", title: "Your ex-manager at Plaid", tone: "slate" },
  { id: "devin",  name: "Devin Ross",   title: "Group PM, Shopify", tone: "sage" },
  { id: "theo",   name: "Theo Marsh",   title: "PM, Linear", tone: "ochre" },
  { id: "sam",    name: "Sam Lee",      title: "Designer, ex-colleague", tone: "slate" },
  { id: "tara",   name: "Tara Singh",   title: "PM Payments, Ramp", tone: "sage" },
  { id: "elena",  name: "Elena Park",   title: "Recruiter, ex-Plaid", tone: "ochre" },
  { id: "marcus", name: "Marcus Webb",  title: "PM Payments, Stripe", tone: "sage" },
  { id: "omar",   name: "Omar Haddad",  title: "From the fintech PM meetup", tone: "neutral" },
];
const introById = Object.fromEntries(MAP_INTRODUCERS.map(i => [i.id, i]));
const contactNode = (id) => { const i = introById[id]; return i ? { name: i.name, title: i.title } : null; };

// A path's chain = the individuals BETWEEN you and the target (entry contact
// first). 0 = direct, 1 = warm intro, 2 = 3rd degree.
const chainFor = (via, degree) => {
  if (via === "direct" || degree <= 1) return [];
  const c = contactNode(via); return c ? [c] : [];
};

// ---- Target companies (broad targets, each a cluster of 4 personas) ----
const MAP_COMPANIES = [
  { id: "stripe",  name: "Stripe",          role: "Senior PM, Payments",   loc: "SF · Hybrid", tone: "slate",  count: 9, best: 94, degree: 2, via: "jordan", hero: "stripe" },
  { id: "ramp",    name: "Ramp",            role: "Group PM, Payments",    loc: "NYC · Hybrid", tone: "sage",  count: 6, best: 90, degree: 2, via: "jordan", hero: "ramp" },
  { id: "brex",    name: "Brex",            role: "Senior PM, Spend",      loc: "SF",          tone: "ochre",  count: 4, best: 86, degree: 2, via: "jordan" },
  { id: "linear",  name: "Linear",          role: "Senior PM",             loc: "Remote",      tone: "slate",  count: 5, best: 83, degree: 2, via: "sam", hero: "linear" },
  { id: "shopify", name: "Shopify",         role: "Group PM, Checkout",    loc: "Remote",      tone: "sage",   count: 3, best: 81, degree: 2, via: "devin" },
  { id: "deel",    name: "Deel",            role: "Senior PM, Payments",   loc: "Remote",      tone: "sage",   count: 2, best: 88, degree: 1, via: "direct" },
  { id: "gusto",   name: "Gusto",           role: "Senior PM, Payroll",    loc: "SF",          tone: "ochre",  count: 3, best: 76, degree: 2, via: "marcus" },
  { id: "vercel",  name: "Vercel",          role: "Director, Product",     loc: "Remote",      tone: "slate",  count: 3, best: 74, degree: 2, via: "theo" },
  { id: "block",   name: "Block",           role: "Group PM, Cash App",    loc: "SF · Hybrid", tone: "sage",   count: 3, best: 72, degree: 2, via: "nadia" },
  { id: "modtreas",name: "Modern Treasury", role: "PM, Payment Ops",       loc: "SF",          tone: "ochre",  count: 2, best: 70, degree: 2, via: "tara" },
  { id: "marqeta", name: "Marqeta",         role: "Principal PM, Issuing", loc: "Oakland",     tone: "slate",  count: 2, best: 66, degree: 2, via: "elena" },
  { id: "adyen",   name: "Adyen",           role: "Principal PM, Money",   loc: "SF",          tone: "ochre",  count: 2, best: 64, degree: 2, via: "nadia" },
  { id: "wise",    name: "Wise",            role: "Senior PM, Transfers",  loc: "Austin",      tone: "sage",   count: 2, best: 60, degree: 2, via: "theo" },
  { id: "checkout",name: "Checkout.com",    role: "PM, Acceptance",        loc: "Remote",      tone: "slate",  count: 2, best: 68, degree: 2, via: "devin" },
  { id: "mercury", name: "Mercury",         role: "Senior PM, Risk",       loc: "SF",          tone: "neutral",count: 1, best: 52, degree: 2, via: "omar", isolated: true },
];

// ---- Specifically-targeted individuals. Each becomes a 1-person company
// cluster so people are always grouped under their company. ----
const MAP_PEOPLE = [
  { id: "renata", name: "Renata Cole",  title: "Director of Product",   co: "Plaid",     tone: "cardinal", degree: 2, score: 80, via: "jordan", flagship: true,
    proof: { type: "connection", text: "Jordan and Renata have been 1st-degree since 2019" } },
  { id: "diego",  name: "Diego Santos", title: "Group PM, Payments",    co: "Coinbase",  tone: "slate",    degree: 2, score: 75, via: "devin",
    proof: { type: "overlap", text: "Devin and Diego shipped Shop Pay together at Shopify" } },
  { id: "yuki",   name: "Yuki Tanaka",  title: "Principal PM",          co: "Datadog",   tone: "sage",     degree: 2, score: 72, via: "theo",
    proof: { type: "connection", text: "Theo and Yuki are 1st-degree" } },
  { id: "sofia",  name: "Sofia Mensah", title: "Director of Product",   co: "Robinhood", tone: "ochre",    degree: 2, score: 67, via: "marcus",
    proof: { type: "meetings", text: "Marcus and Sofia met on a payments panel in March" } },
  { id: "omarR",  name: "Omar Reed",    title: "Technical Recruiter",   co: "Reddit",    tone: "ochre",    degree: 2, score: 64, via: "elena",
    proof: { type: "connection", text: "Elena and Omar worked recruiting at Plaid" } },
  { id: "liang",  name: "Liang Wu",     title: "Senior PM, Growth",     co: "Loom",      tone: "slate",    degree: 2, score: 70, via: "tara",
    proof: { type: "connection", text: "Tara and Liang are 1st-degree" } },
  { id: "grace",  name: "Grace Kim",    title: "Head of Product",       co: "Airbnb",    tone: "slate",    degree: 2, score: 55, via: "sam",
    proof: { type: "connection", text: "Sam can introduce you to Grace" } },
  { id: "hassan", name: "Hassan Ali",   title: "VP Product",            co: "Notion",    tone: "cardinal", degree: 2, score: 58, via: "nadia",
    proof: { type: "alumni", text: "Nadia knows Hassan from Carnegie Mellon" } },
  { id: "ben",    name: "Ben Carter",   title: "Product Manager",       co: "Webflow",   tone: "sage",     degree: 1, score: 92, via: "direct",
    proof: { type: "overlap", text: "You and Ben overlapped at Plaid for 2 years" } },
  { id: "nina",   name: "Nina Patel",   title: "Senior PM, Creators",   co: "Discord",   tone: "sage",     degree: 1, score: 89, via: "direct",
    proof: { type: "meetings", text: "You and Nina have met 3 times, last in January" } },
];

// Resolve each targeted person to a persona-shaped path (with its individual chain).
MAP_PEOPLE.forEach(p => {
  const intro = p.via !== "direct" ? introById[p.via] : null;
  p.path = {
    target: { name: p.name, title: p.title, co: p.co, tone: p.tone },
    degree: p.degree, score: p.score,
    introducer: intro ? { name: intro.name, title: intro.title } : null,
    chain: chainFor(p.via, p.degree),
    proof: [p.proof], alternates: 0,
  };
});

// ---- Persona generator for the broad clusters (expand → 4 people) ----
const PFIRST = ["Ava", "Noah", "Mia", "Leo", "Zoe", "Kai", "Ivy", "Eli", "Nora", "Theo", "Ruby", "Max", "Lena", "Cleo", "Owen", "Maya", "Jude", "Tess", "Cyrus", "Wren", "Hugo", "Iris", "Dean", "Suki"];
const PLAST = ["Cole", "Vance", "Mori", "Reyes", "Hale", "Frost", "Nash", "Okafor", "Bauer", "Sato", "Lund", "Diaz", "Voss", "Penn", "Kerr", "Yang", "Roy", "Tran", "Beck", "Ito"];
const pName = (i, p) => `${PFIRST[(i * 4 + p) % PFIRST.length]} ${PLAST[(i * 3 + p * 5) % PLAST.length]}`;
const clamp100 = (n) => Math.max(8, Math.min(99, Math.round(n)));

function genPersonas(co, idx) {
  const intro = introById[co.via];
  const introName = intro ? intro.name : "a contact";
  const peer = pName(idx, 2), peerFirst = peer.split(" ")[0];
  const mk = (key, title, tone, degree, score, proof, opts = {}) => ({
    target: { name: opts.name || pName(idx, key === "hm" ? 0 : key === "recruiter" ? 1 : key === "peer" ? 2 : 3), title, co: co.name, tone },
    degree, score: clamp100(score),
    introducer: degree >= 2 ? (intro ? { name: intro.name, title: intro.title } : null) : null,
    chain: chainFor(co.via, degree),
    proof: [proof], alternates: opts.alternates || 0,
  });
  return {
    hm: mk("hm", "Director of Product", "slate", co.degree, co.best - 6,
      { type: "connection", text: `${introName} can introduce you to the hiring manager` }),
    recruiter: mk("recruiter", "Technical Recruiter", "ochre", 2, co.best - 16,
      { type: "connection", text: `${introName} knows the recruiter for this role` }),
    peer: mk("peer", "Product Manager", "sage", co.degree === 1 ? 1 : 2, co.best,
      { type: co.degree === 1 ? "overlap" : "connection", text: co.degree === 1 ? `You already know ${peerFirst} here` : `${introName} works alongside ${peerFirst}` }, { name: peer }),
    leader: mk("leader", "VP Product", "cardinal", 2, co.best - 26,
      { type: "connection", text: `${introName} can introduce you to the senior leader` }),
  };
}

// Personas for a company: rich hero board if present, else generated.
function personasFor(co) {
  if (co.hero && typeof NET_COMPANIES !== "undefined" && NET_COMPANIES[co.hero]) return NET_COMPANIES[co.hero].personas;
  const idx = MAP_COMPANIES.findIndex(c => c.id === co.id);
  return genPersonas(co, idx < 0 ? 0 : idx);
}

// ---- Unified clusters: every target is a company cluster of people ----
const COMPANY_CLUSTERS = MAP_COMPANIES.map(c => ({ ...c, kind: "company" }));
const PERSON_CLUSTERS = MAP_PEOPLE.map(p => ({
  id: "pt-" + p.id, name: p.co, role: p.title, loc: null, tone: p.tone,
  count: 1, best: p.score, degree: p.degree, via: p.via, kind: "person", person: p, isolated: p.via === "direct" ? false : undefined,
}));
const MAP_CLUSTERS = [...COMPANY_CLUSTERS, ...PERSON_CLUSTERS];
const clusterById = Object.fromEntries(MAP_CLUSTERS.map(c => [c.id, c]));

// The people inside a cluster (the sub-graph): 4 personas for a company, the
// single individual for a person-target. Returns [{ key, def, persona }].
function clusterPeople(cluster) {
  if (cluster.kind === "person") {
    return [{ key: "target", def: { key: "target", label: cluster.person.title, icon: "contacts", blurb: cluster.name }, persona: cluster.person.path }];
  }
  const ps = personasFor(cluster);
  return ["hm", "recruiter", "peer", "leader"].map((k, i) => ({ key: k, def: PERSONA_DEFS[i], persona: ps[k] })).filter(x => x.persona);
}

// ---- Super-connector ranking — across the whole target list ----
function computeConnectors() {
  return MAP_INTRODUCERS.map(intro => {
    const companies = COMPANY_CLUSTERS.filter(c => c.via === intro.id);
    const people = PERSON_CLUSTERS.filter(c => c.via === intro.id);
    const reach = companies.reduce((s, c) => s + c.count, 0) + people.length;
    return { ...intro, companies, people, total: companies.length + people.length, reach };
  }).filter(c => c.total > 0).sort((a, b) => b.total - a.total || b.reach - a.reach);
}
const MAP_CONNECTORS = computeConnectors();
const MAP_MAX_REACH = Math.max(...MAP_CONNECTORS.map(c => c.total));

const MAP_STATS = {
  companies: COMPANY_CLUSTERS.length,
  people: PERSON_CLUSTERS.length,
  targets: MAP_CLUSTERS.length,
  connectors: MAP_CONNECTORS.length,
};

Object.assign(window, {
  MAP_UPDATED, MAP_INTRODUCERS, introById, MAP_COMPANIES, MAP_PEOPLE,
  COMPANY_CLUSTERS, PERSON_CLUSTERS, MAP_CLUSTERS, clusterById, clusterPeople,
  genPersonas, personasFor, MAP_CONNECTORS, MAP_MAX_REACH, MAP_STATS,
});
