/* global React, Icon, Button, ScreenHeader, Panel, AgentAvatar, TONES, TrajectoryChart */
const { useState: useSum } = React;

// ============================================================
//  Where you stand — a read of everything in your memory:
//  where you are now, the SWOT, and the branching paths ahead.
//  Two personas (driven by the `stage` tweak) prove the page
//  adapts from a seasoned candidate to a brand-new grad.
// ============================================================

const PERSONAS = {
  // ----- Seasoned candidate (Maya) -----
  experienced: {
    hero: {
      warm: {
        title: "You're in good shape, Maya",
        read: "You're in a stronger spot than you think. Your numbers do the talking; the work now is making sure the right people see them.",
      },
      direct: {
        title: "Here's the honest read, Maya",
        read: "You sit at the top of the Senior PM band for payments. Your evidence clears the bar for a step up; the only question is which direction.",
      },
    },
    chart: {
      levels: ["Associate PM", "Product Manager", "Senior PM", "Group / Principal", "Director", "VP Product"],
      currentLevel: 2,
      tStart: -6,
      past: [
        { t: -6, lvl: 0, label: "Associate PM", year: 2020 },
        { t: -3, lvl: 1, label: "Product Manager", year: 2023 },
        { t: 0, lvl: 2, label: "Senior PM", year: 2026, now: true, co: "Plaid" },
      ],
    },
    paths: [
      {
        key: "deepen", name: "Deepen", tone: "sage", tagline: "Go deeper as an IC",
        when: "Principal in ~24 mo", fitNote: "Within reach now",
        unlock: "Your payments depth and experimentation rigor map straight onto a Principal scope. No management required.",
        nodes: [
          { t: 2, lvl: 3, label: "Principal PM, Payments", milestone: true },
          { t: 4.5, lvl: 3.7, label: "Distinguished PM", aspirational: true, dy: -10 },
        ],
        roles: [
          { title: "Principal PM, Payments", co: "Adyen · Marqeta", fit: 0.90 },
          { title: "Staff PM, Checkout", co: "Shopify", fit: 0.82 },
        ],
      },
      {
        key: "lead", name: "Lead", tone: "slate", tagline: "Build and run a team",
        when: "Group PM in ~18 mo", fitNote: "One gap to close",
        unlock: "One thing stands between you and this: direct reports. Take on one or two, and most senior management bars open up.",
        nodes: [
          { t: 1.5, lvl: 3, label: "Group PM, Payments", milestone: true, dy: 22 },
          { t: 4, lvl: 4, label: "Director of Product", aspirational: true },
        ],
        roles: [
          { title: "Group PM, Payments", co: "Stripe · Block", fit: 0.84 },
          { title: "Director of Product", co: "later, with a team", fit: 0.71 },
        ],
      },
      {
        key: "build", name: "Build", tone: "cardinal", tagline: "Own product 0 to 1",
        when: "Head of Product in ~12 mo", fitNote: "Biggest swing",
        unlock: "The fastest jump in scope and the largest risk. Trades a known ladder for full ownership at an early-stage company.",
        nodes: [
          { t: 1, lvl: 3.4, label: "Head of Product", sub: "seed-stage fintech", milestone: true },
          { t: 3.5, lvl: 4.5, label: "VP / Co-founder", aspirational: true },
        ],
        roles: [
          { title: "Head of Product", co: "seed-stage fintech", fit: 0.74 },
          { title: "Founding PM", co: "pre-seed", fit: 0.69 },
        ],
      },
    ],
    swot: {
      strengths: [
        "Six years of measurable checkout-conversion wins, with the numbers to prove them.",
        "A rare pairing: deep payments domain plus genuine experimentation rigor.",
        "You scale through tooling, a platform nine teams chose to adopt.",
      ],
      opportunities: [
        "Payments hiring is up, and fintechs want exactly your PLG-plus-experimentation profile.",
        "Your CMU and Plaid networks already reach four of your six target companies.",
        "Two target roles sit in higher comp bands. Real negotiating room.",
      ],
      growth: [
        "Add a direct report or two. It's the one box most senior roles still check.",
        "Show range beyond one logo. Your work is broader than your résumé reads.",
        "Lead with the visa early. Framed right, authorization to 2027 is a non-issue for most.",
      ],
      watch: [
        "Some senior roles expect people management up front. Target the ones that don't, for now.",
        "Sponsorship filters out roughly a third of postings. We surface the two-thirds that fit.",
        "Off-cycle timing means smaller cohorts at the big names. Warm intros matter more.",
      ],
    },
  },

  // ----- New grad (Sam) -----
  newgrad: {
    hero: {
      warm: {
        title: "You've got a real shot, Sam",
        read: "Being early is the advantage. Two shipped internships and a side project with real users already put genuine product signal on the table.",
      },
      direct: {
        title: "Here's the honest read, Sam",
        read: "You don't have a track record yet, you have signals, and they're good ones. Enough to aim at three different entry paths.",
      },
    },
    chart: {
      levels: ["Intern", "APM / New grad", "Product Manager", "Senior PM", "Group PM"],
      currentLevel: 1,
      tStart: -2,
      past: [
        { t: -2, lvl: 0, label: "PM Intern", year: 2024 },
        { t: -1, lvl: 0.45, label: "PM Intern, 2nd", year: 2025 },
        { t: 0, lvl: 1, label: "New grad", year: 2026, now: true, co: "graduating" },
      ],
    },
    paths: [
      {
        key: "scale", name: "Scale", tone: "slate", tagline: "Learn the craft at scale",
        when: "APM offer in ~3 mo", fitNote: "Built for you",
        unlock: "Rotational APM programs are designed for new grads. Structured mentorship, wide surface area, a brand that travels.",
        nodes: [
          { t: 0.4, lvl: 1.25, label: "APM, rotational", milestone: true, dy: 22 },
          { t: 3, lvl: 2, label: "Product Manager", aspirational: true },
        ],
        roles: [
          { title: "APM (rotational)", co: "Google · Uber · Atlassian", fit: 0.81 },
          { title: "Associate PM", co: "LinkedIn", fit: 0.78 },
        ],
      },
      {
        key: "build", name: "Build", tone: "cardinal", tagline: "Own a surface fast",
        when: "First PM seat in ~2 mo", fitNote: "Most reps, most risk",
        unlock: "A Series-A team will hand you real ownership on day one. Higher risk, far more reps, faster growth if it works.",
        nodes: [
          { t: 0.3, lvl: 1.5, label: "Founding-team PM", milestone: true },
          { t: 2.5, lvl: 2.4, label: "Senior PM", aspirational: true },
        ],
        roles: [
          { title: "Product Manager", co: "Series A startup", fit: 0.76 },
          { title: "Founding PM", co: "pre-seed", fit: 0.70 },
        ],
      },
      {
        key: "specialize", name: "Specialize", tone: "sage", tagline: "Lean on your domain",
        when: "Technical APM in ~3 mo", fitNote: "Plays your strength",
        unlock: "Your CS and data background opens technical PM tracks (AI, platform, payments) where the bar rewards depth over tenure.",
        nodes: [
          { t: 0.45, lvl: 1.35, label: "Technical APM", milestone: true, dy: -10 },
          { t: 3, lvl: 2.1, label: "PM, Platform", aspirational: true },
        ],
        roles: [
          { title: "Technical PM", co: "AI infra", fit: 0.79 },
          { title: "APM, Platform", co: "fintech", fit: 0.74 },
        ],
      },
    ],
    swot: {
      strengths: [
        "Two internships that actually shipped, not just shadowed.",
        "A strong technical base most PMs pick up years later.",
        "A side project with real users. Proof you can go 0 to 1.",
      ],
      opportunities: [
        "Rotational APM programs are actively hiring your exact profile.",
        "Your campus and intern networks reach hiring managers directly.",
        "Technical PM tracks reward your background over years of tenure.",
      ],
      growth: [
        "Translate projects into outcomes. Lead with the metric, not the task.",
        "Name a focus area. 'Generalist' is harder to place than 'AI' or 'payments'.",
        "Build one more shipped story you can walk through in an interview.",
      ],
      watch: [
        "New-grad PM roles are competitive. Warm intros beat cold applications.",
        "Titles vary wildly. Check the scope, not just the word 'PM'.",
        "Hiring is seasonal. Most APM programs open in the fall.",
      ],
    },
  },
};

const DEFAULT_TW = { tone: "warm", stage: "experienced", horizon: 5, detail: 2, plainLabels: false };

// Fit-meter axis (shared with chart fit reads).
const AXIS_MIN = 0.6, AXIS_MAX = 0.95;

function ScrSummary({ tw, onExplore }) {
  const T = { ...DEFAULT_TW, ...(tw || {}) };
  const P = PERSONAS[T.stage] || PERSONAS.experienced;
  const hero = P.hero[T.tone] || P.hero.warm;

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: "8px 0 40px" }}>
      <ScreenHeader
        eyebrow="Step 4 · Where you stand"
        title={hero.title}
        lede="Built from everything in your memory: where you are now, and where you can take it."
      />

      {/* ---- Standing now: a short read from Offerroom ---- */}
      <Panel className="cad-rise" style={{ padding: "17px 22px" }}>
        <div style={{ display: "flex", gap: 13, alignItems: "flex-start" }}>
          <AgentAvatar size={28}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: "var(--fg-2)", marginBottom: 7 }}>
              <b style={{ color: "var(--fg-1)", fontWeight: 600 }}>Offerroom</b> · just now
            </div>
            <p style={{ fontSize: 15, lineHeight: 1.6, color: "var(--fg-1)", margin: 0, textWrap: "pretty" }}>
              {hero.read}
            </p>
          </div>
        </div>
      </Panel>

      <div style={{ display: "flex", flexDirection: "column", gap: 34, marginTop: 30 }}>
        <TrajectorySection key={T.stage} P={P} T={T} onExplore={onExplore}/>
        <SwotSection P={P} T={T}/>
      </div>
    </div>
  );
}

// ============================================================
//  Trajectory — the line chart + the three paths
// ============================================================
const TrajectorySection = ({ P, T, onExplore }) => {
  const [active, setActive] = useSum(null);
  const [hover, setHover] = useSum(null);
  const cur = hover || active;
  const tee = (k) => setActive((a) => (a === k ? null : k));

  return (
    <section>
      <SectionHead eyebrow="Where you can go"
        title="Your trajectory, and the moves from here"
        sub="One line is the path you've walked. The three ahead are real next moves, each reaching a different milestone. Hover one to trace it." />

      <Panel pad={0} style={{ overflow: "hidden" }}>
        {/* Legend / path selector */}
        <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "10px 8px", padding: "13px 18px", borderBottom: "1px solid var(--ink-50)", background: "var(--paper-elevated)" }}>
          <span style={{ fontSize: 11.5, color: "var(--fg-2)", marginRight: 4 }}>Paths</span>
          {P.paths.map((p) => {
            const tone = TONES[p.tone];
            const on = cur === p.key, pinned = active === p.key;
            return (
              <button key={p.key} onClick={() => tee(p.key)}
                onMouseEnter={() => setHover(p.key)} onMouseLeave={() => setHover(null)}
                style={{
                  display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 11px", borderRadius: 999,
                  cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600,
                  color: on ? "var(--fg-1)" : "var(--fg-2)",
                  background: on ? "var(--paper-sunken)" : "#fff",
                  border: `1px solid ${on ? "var(--ink-300)" : "var(--ink-100)"}`,
                  transition: "all 120ms",
                }}>
                <span style={{ width: 9, height: 9, borderRadius: 999, background: tone.color, opacity: cur && !on ? 0.4 : 1 }}/>
                {p.name}
              </button>
            );
          })}
        </div>

        <div style={{ padding: "10px 14px 4px" }}>
          <TrajectoryChart chart={P.chart} paths={P.paths} horizon={T.horizon} detail={T.detail}
            active={cur} onHover={setHover} onSelect={tee}/>
        </div>
      </Panel>

      {/* Path cards */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, marginTop: 14 }}>
        {P.paths.map((p) => (
          <PathCard key={p.key} p={p} T={T}
            on={cur === p.key} dim={cur && cur !== p.key} pinned={active === p.key}
            onEnter={() => setHover(p.key)} onLeave={() => setHover(null)}
            onClick={() => tee(p.key)} onExplore={onExplore}/>
        ))}
      </div>
    </section>
  );
};

const PathCard = ({ p, T, on, dim, pinned, onEnter, onLeave, onClick, onExplore }) => {
  const tone = TONES[p.tone];
  return (
    <div onMouseEnter={onEnter} onMouseLeave={onLeave} onClick={onClick}
      style={{
        background: "#fff", borderRadius: 10, overflow: "hidden", cursor: "pointer",
        border: `1px solid ${on ? "var(--ink-300)" : "rgba(31,27,22,0.08)"}`,
        boxShadow: on ? "0 8px 24px rgba(31,27,22,0.10)" : "0 1px 2px rgba(31,27,22,0.04)",
        opacity: dim ? 0.62 : 1, transition: "all 160ms cubic-bezier(0.2,0.7,0.1,1)",
        transform: on ? "translateY(-2px)" : "none", position: "relative",
      }}>
      <div style={{ padding: "14px 16px 13px", borderBottom: "1px solid var(--ink-100)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 9, height: 9, borderRadius: 999, background: tone.color }}/>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500, color: "var(--fg-1)" }}>{p.name}</span>
          </span>
          <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--fg-2)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{p.fitNote}</span>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--fg-2)", marginTop: 5 }}>{p.tagline}</div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 11, padding: "3px 9px", borderRadius: 999, background: "var(--paper-sunken)", fontSize: 11.5, fontWeight: 600, color: "var(--fg-1)" }}>
          <Icon name="target" size={12}/>{p.when}
        </div>
      </div>
      <div style={{ padding: "12px 16px 14px" }}>
        {T.detail >= 2 && (
          <div style={{ display: "flex", gap: 8, fontSize: 12, color: "var(--fg-2)", lineHeight: 1.45, marginBottom: 12 }}>
            <span style={{ color: "var(--fg-3)", flexShrink: 0, marginTop: 1 }}><Icon name="zap" size={13}/></span>
            <span><b style={{ color: "var(--fg-1)", fontWeight: 600 }}>What unlocks it. </b>{p.unlock}</span>
          </div>
        )}
        {p.roles.map((r, i) => (
          <div key={i} style={{ padding: "9px 0", borderTop: "1px solid var(--ink-50)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
              <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.25 }}>{r.title}</div>
              <FitMeter value={r.fit}/>
            </div>
            <div style={{ fontSize: 11.5, color: "var(--fg-2)", marginTop: 2 }}>{r.co}</div>
          </div>
        ))}
        <Button variant="ghost" size="sm" icon="arrow"
          onClick={(e) => { e.stopPropagation(); onExplore && onExplore(); }}
          style={{ marginTop: 10, width: "100%", justifyContent: "center" }}>Find these roles</Button>
      </div>
    </div>
  );
};

// Compact fit meter — bar + number.
const FitMeter = ({ value }) => {
  const tone = value >= 0.85 ? TONES.sage : value >= 0.75 ? TONES.slate : TONES.ochre;
  const pct = Math.max(8, Math.round(((value - AXIS_MIN) / (AXIS_MAX - AXIS_MIN)) * 100));
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
      <span style={{ width: 44, height: 6, borderRadius: 999, background: "rgba(31,27,22,0.08)", overflow: "hidden", display: "inline-block" }}>
        <span style={{ display: "block", height: "100%", width: `${pct}%`, background: tone.color, borderRadius: 999 }}/>
      </span>
      <b style={{ fontSize: 12, fontWeight: 700, color: tone.text, fontVariantNumeric: "tabular-nums" }}>{value.toFixed(2)}</b>
    </span>
  );
};

// ============================================================
//  SWOT — a positive, scannable 2 x 2
// ============================================================
const QUADS = [
  { key: "strengths", tone: "sage", icon: "zap", swot: "Strengths", plain: "What you lead with", sub: "Play these up" },
  { key: "growth", tone: "ochre", icon: "target", swot: "Watch-outs", plain: "What to get ahead of", sub: "Small, doable moves" },
  { key: "opportunities", tone: "slate", icon: "sparkles", swot: "Opportunities", plain: "Wind at your back", sub: "Timing's with you" },
  { key: "watch", tone: "neutral", icon: "eye", swot: "Tradeoffs", plain: "What to plan around", sub: "Plan around these" },
];

const SwotSection = ({ P, T }) => {
  const count = 2;
  return (
    <section>
      <div style={{ height: 1, background: "var(--ink-100)", margin: "4px 0 30px" }}/>
      <SectionHead eyebrow="The honest read"
        title="Strengths, openings, and what to get ahead of"
        sub="The full picture, framed as moves you can make. Nothing here is a dealbreaker." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        {QUADS.map((q) => (
          <SwotQuad key={q.key} q={q} items={(P.swot[q.key] || []).slice(0, count)} plain={T.plainLabels}/>
        ))}
      </div>
    </section>
  );
};

const SwotQuad = ({ q, items, plain }) => {
  const t = TONES[q.tone];
  return (
    <Panel pad={0} style={{ overflow: "hidden" }}>
      <div style={{ padding: "15px 20px 4px", display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: t.color, flexShrink: 0 }}/>
        <h4 style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500, color: "var(--fg-1)", margin: 0, letterSpacing: "-0.01em" }}>
          {plain ? q.plain : q.swot}
        </h4>
      </div>
      <ul style={{ listStyle: "none", margin: 0, padding: "0 20px 16px" }}>
        {items.map((it, i) => (
          <li key={i} style={{ display: "flex", gap: 11, padding: "11px 0", borderTop: i > 0 ? "1px solid var(--ink-50)" : "none" }}>
            <span style={{ width: 5, height: 5, borderRadius: 999, background: "var(--ink-300)", marginTop: 8, flexShrink: 0 }}/>
            <span style={{ fontSize: 13, lineHeight: 1.5, color: "var(--fg-1)" }}>{it}</span>
          </li>
        ))}
      </ul>
    </Panel>
  );
};

// Shared section header (eyebrow + Fraunces title + sub).
const SectionHead = ({ eyebrow, title, sub }) => (
  <div style={{ marginBottom: 16 }}>
    <div className="cd-eyebrow" style={{ marginBottom: 6 }}>{eyebrow}</div>
    <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 26, letterSpacing: "-0.015em", margin: 0 }}>{title}</h3>
    {sub && <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "7px 0 0", maxWidth: 660, lineHeight: 1.5 }}>{sub}</p>}
  </div>
);

window.ScrSummary = ScrSummary;
