/* CLAY SWEEP - the "Enrichment sweep" Version A, packaged as a single
   component for the main ABM page (section 03). Renders only the pinned
   Clay table + run animation; the section heading is supplied by main.jsx.
   Depends on window.CK (clay-kit) + window.CLAY (clay-data). → window.ClaySweep */
(function () {
  const { PersonCell, FrameBar, HeaderRow, StatusCell, SignalCell, ScoreCell, TierChip, RouteCell, useScrollProgress } = window.CK;
  const { COLUMNS, PEOPLE, C4 } = window.CLAY;

  const FILL = COLUMNS.slice(1);
  const NR = PEOPLE.length, NF = FILL.length;

  function BodyCell({ col, person, phase }) {
    switch (col.kind) {
      case "status": return <StatusCell col={col} person={person} phase={phase} />;
      case "signal": return <SignalCell person={person} phase={phase} />;
      case "score":  return <ScoreCell fit={person.fit} phase={phase} />;
      case "stage":  return <TierChip tier={person.tier} phase={phase} />;
      case "route":  return <RouteCell route={person.route} pending={phase !== "done"} lock={phase === "done"} />;
      default:       return <div className="clay2-cell" />;
    }
  }

  /* columns trigger near-simultaneously, tiny staggered lag, non-linear order */
  const COL_PRIORITY = [0, 2, 4, 1, 5, 3, 6];
  const A_BEGIN = 0.10, A_COLGAP = 0.045, A_ROWSPAN = 0.16, A_CELLDUR = 0.05;
  const colWindow = (colIdx) => {
    const oc = COL_PRIORITY.indexOf(colIdx);
    const start = A_BEGIN + oc * A_COLGAP;
    return { start, end: start + A_ROWSPAN + A_CELLDUR };
  };

  /* natural width used only to derive column percentages */
  const TOTAL_W = COLUMNS.reduce((a, c) => a + c.w, 0);

  /* matchMedia hook - true on phones */
  function useIsMobile(q = "(max-width: 640px)") {
    const get = () => (typeof window !== "undefined" && window.matchMedia ? window.matchMedia(q).matches : false);
    const [m, setM] = React.useState(get);
    React.useEffect(() => {
      const mq = window.matchMedia(q);
      const on = () => setM(mq.matches);
      on();
      mq.addEventListener ? mq.addEventListener("change", on) : mq.addListener(on);
      return () => { mq.removeEventListener ? mq.removeEventListener("change", on) : mq.removeListener(on); };
    }, [q]);
    return m;
  }

  /* MOBILE - the pinned scroll-to-run choreography doesn't fit a phone, so we
     present the table already fully enriched (the end state of the run) and
     let it scroll horizontally inside the frame at authentic column widths.
     One clean swipe shows every real Clay column instead of 8 crushed ones. */
  function ClaySweepMobile() {
    return (
      <div className="clay2 clay2-a clay2-embed clay2-mob">
        <div className="clay2-fitwrap">
          <div className="clay2-frame">
            <FrameBar rows={NR} />
            <div className="clay2-mscroll">
              <table className="clay2-tbl">
                <HeaderRow colState={() => "done"} accent={C4[0]} />
                <tbody>
                  {PEOPLE.map((person, ri) => (
                    <tr className="clay2-row" key={person.domain}>
                      <td><PersonCell person={person} /></td>
                      {FILL.map((col) => (
                        <td key={col.key}><BodyCell col={col} person={person} phase="done" /></td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="clay2-prog">
              <span className="ptxt">Enrichment complete · every account routed</span>
              <span className="ptrack"><span className="pfill" style={{ width: "100%" }} /></span>
              <span className="ppct">100%</span>
            </div>
          </div>
          <div className="clay2-cap">
            <span className="clay2-swipe">Swipe across to see every column →</span>
          </div>
        </div>
      </div>
    );
  }

  function ClaySweep() {
    const mobile = useIsMobile("(max-width: 760px)");
    const [ref, p] = useScrollProgress();
    if (mobile) return <ClaySweepMobile />;
    const accent = C4[0];
    const phaseFor = (rowIdx, colIdx) => {
      const { start } = colWindow(colIdx);
      const rowOffset = ((rowIdx * 3 + 1) % NR) / NR;
      const cellStart = start + rowOffset * A_ROWSPAN;
      if (p >= cellStart + A_CELLDUR) return "done";
      if (p >= cellStart) return "run";
      return "empty";
    };
    const colState = (colKey) => {
      const colIdx = FILL.findIndex((c) => c.key === colKey);
      if (colIdx < 0) return "idle";
      const { start, end } = colWindow(colIdx);
      if (p >= end) return "done";
      if (p >= start) return "run";
      return "idle";
    };
    const pct = Math.round(Math.min(100, (p / 0.78) * 100));

    return (
      <div className="clay2 clay2-a clay2-embed">
        <div className="clay2-pin" ref={ref} style={{ height: "240vh" }}>
          <div className="clay2-stick clay2-stage">
            <div className="clay2-fitwrap">
              <div className="clay2-frame">
                <FrameBar rows={NR} />
                <table className="clay2-tbl clay2-tbl--full" style={{ width: "100%", minWidth: 0, tableLayout: "fixed" }}>
                  <HeaderRow colState={colState} accent={accent} widthTotal={TOTAL_W} />
                  <tbody>
                    {PEOPLE.map((person, ri) => (
                      <tr className="clay2-row" key={person.domain}>
                        <td><PersonCell person={person} /></td>
                        {FILL.map((col, ci) => (
                          <td key={col.key}><BodyCell col={col} person={person} phase={phaseFor(ri, ci)} /></td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
                <div className="clay2-prog">
                  <span className="ptxt">{pct >= 100 ? "Enrichment complete · every account routed" : `Running ${NF} columns across ${NR} accounts`}</span>
                  <span className="ptrack"><span className="pfill" style={{ width: pct + "%" }} /></span>
                  <span className="ppct">{pct}%</span>
                </div>
              </div>
              <div className="clay2-cap">
                <span>{pct >= 100 ? "Every account routed" : "Scroll to run the table"}</span>
                <span className="pgline"><i style={{ width: pct + "%", background: accent }} /></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.ClaySweep = ClaySweep;
})();
