/* The "what are you looking for?" evidence matcher. Each pick scores every
   project/experience card below it (the grid), and those scores are turned
   into percentages that add up to 100% (the bars under the grid). */

const MATCH_QUALS = [
  { key: "tech", label: "technical skills" },
  { key: "results", label: "results" },
  { key: "analysis", label: "analysis and research" },
  { key: "clients", label: "working with clients" },
  { key: "resp", label: "responsibility" },
  { key: "creds", label: "credentials" },
  { key: "init", label: "initiative" },
  { key: "writing", label: "writing" },
];

const MATCH_WORKS = [
  { key: "uk", label: "uk-market", full: "uk-market-entry-screen", swatch: "var(--k-style)", href: "#projects" },
  { key: "wc", label: "world-cup", full: "world-cup-2026-predictor", swatch: "var(--k-font)", href: "#projects" },
  { key: "post", label: "blog post", full: "Before the Model", swatch: "var(--k-style)", href: "blog.html?post=before-the-model" },
  { key: "msft", label: "Insight Day", full: "Microsoft Insight Day", swatch: "var(--k-script)", href: "#experience" },
  { key: "eraadi", label: "eRaadi", full: "eRaadi, S4S × SIT Climate Hackathon", swatch: "var(--k-rose)", href: "#experience" },
  { key: "access", label: "Access", full: "Access to HE Diploma", swatch: "var(--k-doc)", href: "#education" },
  { key: "kcl", label: "KCL", full: "BSc Computer Science, King's College London", swatch: "var(--k-doc)", href: "#education" },
];

const MATCH_EVIDENCE = {
  tech: {
    uk: [2, "Python, SQL and DuckDB over a 5.7-million-row Companies House CSV, with pytest checks."],
    wc: [2, "A drag-and-drop bracket for all 48 teams, written in vanilla JavaScript."],
    post: [1, "Walks through the GROUP BY and the test_dates.py checks behind the project."],
    access: [1, "Access to HE Diploma in Computer Science and Mathematics."],
    kcl: [1, "Studying BSc Computer Science at King's College London."],
  },
  results: {
    uk: [1, "Reached an answer: IT companies are more popular in London, with confidence stated as medium."],
    wc: [1, "Finished and playable: the Play button runs it."],
    msft: [2, "One of 41 King's College London students selected from over 200 applicants."],
    eraadi: [2, "Won the S4S × SIT Climate Hackathon."],
    access: [2, "45 Distinctions out of 45."],
  },
  analysis: {
    uk: [2, "Compared two mismatched data sources and found company status had 14 values, not the 3 first assumed."],
    post: [2, "Weighs its own caveats: different years, sole traders, postcode boundaries."],
    msft: [1, "Defined the client's core problem for the Account Team Unit."],
    eraadi: [1, "Helped scope the service around pastoralists in drought."],
  },
  clients: {
    msft: [2, "Represented the Account Team Unit (ATU), defining the client's core problem."],
    eraadi: [1, "Built around real users: Somali pastoralists looking for working wells."],
  },
  resp: {
    uk: [1, "Tested its own data: no duplicate company numbers, no null or future dates."],
    msft: [1, "Represented the Account Team Unit in the team's pitch to a panel of judges."],
    eraadi: [1, "Presented a third of the winning pitch: the insight, the solution and how it works."],
  },
  creds: {
    msft: [1, "Selected for Microsoft's Insight Day."],
    access: [2, "Access to HE Diploma: 45 Distinctions out of 45."],
    kcl: [2, "BSc Computer Science, King's College London, graduating 2029."],
  },
  init: {
    uk: [2, "Self-started: its own question, public data and its own tests."],
    wc: [1, "Built and published on GitHub."],
    post: [1, "Written up and published as a blog post."],
    msft: [1, "Applied for a place on Microsoft's Insight Day."],
    eraadi: [2, "Proposed the team's starting idea."],
  },
  writing: {
    post: [2, "Before the Model: a four-minute write-up of the project."],
    uk: [1, "Comes with a full write-up, linked from the project."],
  },
};

const MATCH_W = MATCH_QUALS.map((q) => MATCH_WORKS.map((w) => ((MATCH_EVIDENCE[q.key] || {})[w.key] || [0])[0]));
const MATCH_T = MATCH_QUALS.map((q) => MATCH_WORKS.map((w) => ((MATCH_EVIDENCE[q.key] || {})[w.key] || [0, ""])[1]));

const Match = () => {
  const [pick, setPick] = React.useState([true, false, true, false, false, false, false, false]);
  const [anim, setAnim] = React.useState(null);
  const [hover, setHover] = React.useState(null);
  const timer = React.useRef(null);
  const reduceRef = React.useRef(false);

  React.useEffect(() => {
    reduceRef.current = !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
    return () => clearTimeout(timer.current);
  }, []);

  const toggle = (i) => {
    const next = pick.slice();
    next[i] = !next[i];
    clearTimeout(timer.current);
    const rows = [];
    for (let r = 0; r < next.length; r++) if (next[r]) rows.push(r);
    if (reduceRef.current || !rows.length) { setPick(next); setAnim(null); return; }
    setPick(next);
    setAnim(0);
    const step = (cur) => {
      const n = cur + 1;
      if (n > rows.length) { setAnim(null); return; }
      setAnim(n);
      timer.current = setTimeout(() => step(n), n === rows.length ? 380 : 260);
    };
    timer.current = setTimeout(() => step(0), 200);
  };

  const order = [];
  for (let i = 0; i < pick.length; i++) if (pick[i]) order.push(i);
  const added = anim === null ? order.length : Math.min(anim, order.length);
  const counted = {};
  for (let n = 0; n < added; n++) counted[order[n]] = true;
  const curRow = anim !== null && anim >= 1 && anim <= order.length ? order[anim - 1] : -1;
  const done = anim === null;

  const scores = MATCH_WORKS.map((w, j) => {
    let t = 0;
    for (let i = 0; i < MATCH_QUALS.length; i++) if (counted[i]) t += MATCH_W[i][j];
    return t;
  });
  let probs = MATCH_WORKS.map(() => 0);
  if (order.length) {
    const hi = Math.max.apply(null, scores);
    const ex = scores.map((v) => Math.exp(v - hi));
    const tot = ex.reduce((a, b) => a + b, 0);
    probs = ex.map((v) => v / tot);
  }
  const best = done && order.length ? scores.indexOf(Math.max.apply(null, scores)) : -1;

  let status = "pick what you're looking for";
  if (order.length && !done && curRow >= 0) status = "adding up: " + MATCH_QUALS[curRow].label;
  else if (order.length && done && best >= 0) {
    const top = scores[best];
    const tied = MATCH_WORKS.filter((w, j) => scores[j] === top).map((w) => w.label);
    status = tied.length > 1 ? "joint top: " + tied.join(", ") : "top match: " + MATCH_WORKS[best].full;
  }
  if (hover) {
    const wt = MATCH_W[hover[0]][hover[1]];
    status = MATCH_QUALS[hover[0]].label + " × " + MATCH_WORKS[hover[1]].label + " = " + wt + (wt ? " · " + MATCH_T[hover[0]][hover[1]] : "");
  }

  const results = [];
  if (done && order.length) {
    const idx = MATCH_WORKS.map((w, j) => j).filter((j) => scores[j] > 0);
    idx.sort((a, b) => scores[b] - scores[a] || a - b);
    idx.slice(0, 3).forEach((j, n) => {
      let why = "";
      let bw = -1;
      for (let k = 0; k < order.length; k++) {
        const i = order[k];
        if (MATCH_W[i][j] > bw) { bw = MATCH_W[i][j]; why = MATCH_T[i][j]; }
      }
      results.push({ rank: n + 1, full: MATCH_WORKS[j].full, swatch: MATCH_WORKS[j].swatch, pct: Math.round(probs[j] * 100), why, href: MATCH_WORKS[j].href });
    });
  }

  return (
    <section className="sec2" id="match">
      <div className="sec2-wrap">
        <div className="sec2-label">
          <span className="num">08</span>
          <span className="name">match</span>
          <span className="sub">q · E</span>
        </div>
        <div className="sec2-body">
          <h2>What are you looking for?</h2>
          <p style={{margin: 0, maxWidth: "620px", fontSize: "18px", lineHeight: 1.6, color: "var(--ink-2)"}}>
            Pick what matters to you and this page will point you to the strongest evidence for it.
          </p>
          <div role="group" aria-label="What you are looking for" className="match-chips">
            {MATCH_QUALS.map((q, i) => (
              <button type="button" key={q.key} className="qchip" aria-pressed={pick[i]} onClick={() => toggle(i)}>{q.label}</button>
            ))}
          </div>

          <figure className="match-fig">
            <figcaption>
              <div className="match-fig-top">
                <span className="eq">s = q · E</span>
                <span className="desc">your picks × the evidence on this page</span>
              </div>
              <span className="status">{status}</span>
            </figcaption>
            <div className="match-grid-wrap">
              <div className="match-grid">
                <div className="qrow head-row">
                  <span>q ↓ · E →</span>
                  {MATCH_WORKS.map((w, j) => (
                    <span key={w.key} title={w.full} className="col-head" style={{color: j === best ? "var(--ink)" : "var(--ink-2)"}}>
                      <span className="swatch" style={{background: w.swatch}} aria-hidden="true"></span>{w.label}
                    </span>
                  ))}
                </div>
                {MATCH_QUALS.map((q, i) => {
                  const on = !!pick[i];
                  const isCur = i === curRow;
                  return (
                    <div className="qrow data-row" key={q.key} style={{background: isCur ? "var(--line-2)" : "transparent", opacity: on ? 1 : 0.38}}>
                      <span className="qlabel" style={{color: on ? "var(--ink)" : "var(--ink-3)"}}>
                        <span className="idx">{on ? "1" : "0"}</span>{q.label}
                      </span>
                      {MATCH_WORKS.map((w, j) => {
                        const wt = MATCH_W[i][j];
                        const lit = on && (counted[i] || isCur);
                        return (
                          <span className="qcell" key={w.key} onMouseEnter={() => setHover([i, j])} onMouseLeave={() => setHover(null)}>
                            <span
                              className="qcell-box"
                              role="img"
                              aria-label={`${q.label}, ${w.full}: ${wt}${wt ? ". " + MATCH_T[i][j] : ""}`}
                              style={{
                                borderColor: wt ? "transparent" : "var(--line-2)",
                                outline: isCur && wt ? "2px solid var(--signal)" : "none",
                                outlineOffset: "2px",
                              }}
                            >
                              <span
                                className="qcell-fill"
                                aria-hidden="true"
                                style={{
                                  background: wt ? w.swatch : "transparent",
                                  opacity: wt === 2 ? (lit ? 1 : 0.75) : wt === 1 ? (lit ? 0.5 : 0.35) : 0,
                                }}
                              ></span>
                            </span>
                          </span>
                        );
                      })}
                    </div>
                  );
                })}
                <div className="qrow totals-row">
                  <span className="lbl">q · E</span>
                  {MATCH_WORKS.map((w, j) => (
                    <span className="score" key={w.key} style={{color: j === best ? "var(--signal)" : "var(--ink)"}}>
                      {order.length ? scores[j] : "·"}
                    </span>
                  ))}
                </div>
                <div className="qrow softmax-row">
                  <span className="lbl">% match</span>
                  {MATCH_WORKS.map((w, j) => (
                    <span className="softmax-col" key={w.key}>
                      <span className="pct">{done && order.length ? Math.round(probs[j] * 100) + "%" : ""}</span>
                      <span className="bar" style={{height: `${done && order.length ? Math.max(2, Math.round(probs[j] * 52)) : 2}px`, background: w.swatch}}></span>
                    </span>
                  ))}
                </div>
              </div>
            </div>
          </figure>

          {results.length > 0 ? (
            <ol className="match-results">
              {results.map((t) => (
                <li key={t.full}>
                  <span className="rank">{t.rank}</span>
                  <span className="info">
                    <span className="title-row">
                      <span className="swatch" style={{background: t.swatch}} aria-hidden="true"></span>
                      <span className="name">{t.full}</span>
                      <span className="pct">{t.pct}%</span>
                    </span>
                    <span className="why">{t.why}</span>
                  </span>
                  <a href={t.href} className="btn btn-ghost btn--sm">see it →</a>
                </li>
              ))}
            </ol>
          ) : (
            <p className="match-empty">pick at least one to see a match</p>
          )}

          <p className="match-footnote">
            How this works: each pick you select scores every project and experience below against it, the grid shows those raw scores, and the bars turn them into percentages that add up to 100%. Each score is 0 to 2 and tied to a specific line on this page: hover a tile to read it.
          </p>
        </div>
      </div>
    </section>
  );
};

window.Match = Match;
