/* eslint-disable */
// Walkthrough timeline — drives ManagerApp through scenes,
// renders an animated cursor, and exposes <Walkthrough/>.

(function () {
const { ManagerApp, ONBOARDINGS, buildCsv } = window;
const { useState, useEffect } = React;

// ------------------------------------------------------------------
// Cursor
// ------------------------------------------------------------------
function Cursor({ x, y, clicking }) {
  return (
    <div style={{
      position: "absolute",
      left: 0, top: 0,
      transform: `translate(${x}px, ${y}px)`,
      transition: "transform 0.5s cubic-bezier(0.5, 0, 0.2, 1)",
      pointerEvents: "none",
      zIndex: 200,
    }}>
      {clicking && (
        <div style={{
          position: "absolute", left: -6, top: -6,
          width: 32, height: 32, borderRadius: 999,
          background: "rgba(73,62,216,0.18)",
          border: "2px solid rgba(73,62,216,0.7)",
        }} />
      )}
      <svg width="22" height="22" viewBox="0 0 22 22" style={{ filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.3))" }}>
        <path d="M3 1 L3 16 L7.5 12 L10 18 L13 16.8 L10.5 11 L16 11 Z"
          fill="#141414" stroke="#FFF" strokeWidth="1.2" strokeLinejoin="round" />
      </svg>
    </div>
  );
}

// ------------------------------------------------------------------
// Flag badge
// ------------------------------------------------------------------
function FlagBadge({ label }) {
  if (!label) return null;
  return (
    <div style={{
      position: "absolute",
      top: 16, right: 18,
      display: "flex", alignItems: "center", gap: 8,
      padding: "6px 12px",
      borderRadius: 999,
      background: "#141414", color: "#FFF",
      fontFamily: "var(--font-body)",
      fontSize: 12, fontWeight: 600,
      boxShadow: "3px 3px 0 0 #493ED8",
      zIndex: 150,
    }}>
      <span style={{
        width: 8, height: 8, borderRadius: 999, background: "#0DD57B",
        boxShadow: "0 0 6px #0DD57B",
      }} />
      <span style={{ fontSize: 11, color: "#A6A0E0", fontWeight: 500 }}>FLAG</span>
      <span style={{ fontFamily: "ui-monospace, monospace", fontSize: 11.5 }}>{label}</span>
    </div>
  );
}

// ------------------------------------------------------------------
// Coordinates
// ------------------------------------------------------------------
const C = {
  searchPill:   { x: 510,  y: 30 },
  searchClose:  { x: 884,  y: 168 },
  pageSearch:   { x: 320,  y: 254 },
  dateStart:    { x: 1010, y: 254 },
  columnsField: { x: 460,  y: 376 },
  downloadCsv:  { x: 1140, y: 364 },
  dropdownLocation: { x: 460, y: 588 },
  dropdownCriminal: { x: 460, y: 624 },
  dropdownMVR:      { x: 460, y: 660 },
  dropdownDrug:     { x: 460, y: 696 },
  dateMay11:        { x: 990,  y: 482 },
  dateMay13:        { x: 1042, y: 482 },
  csvDownload:      { x: 870,  y: 462 },
  centerNeutral:    { x: 640,  y: 460 },
};

// ------------------------------------------------------------------
// Compute filtered csv (May 11–13, 2026) with extras
// ------------------------------------------------------------------
function computeCsv() {
  const start = new Date("May 11, 2026");
  const end   = new Date("May 13, 2026");
  const rows = ONBOARDINGS.filter(r => {
    const t = new Date(r.start);
    return t >= start && t <= end;
  });
  return buildCsv(rows, true);
}

// ------------------------------------------------------------------
// Type letters helper
// ------------------------------------------------------------------
function typeLetters(text, startT, perChar, flag) {
  const out = [];
  for (let i = 1; i <= text.length; i++) {
    const t = startT + i * perChar;
    const q = text.slice(0, i);
    out.push({ t, build: () => ({
      cursor: { x: 540, y: 130 },
      flag,
      search: { visible: true, query: q },
    })});
  }
  return out;
}

// ------------------------------------------------------------------
// Scene timeline (~90s)
// ------------------------------------------------------------------
const SCENES = [
  // 0–4s : intro on onboarding index
  { t: 0, build: () => ({
    cursor: { ...C.centerNeutral }, flag: null,
    page:   { selectedExtras: [] },
  })},
  { t: 1.0, build: () => ({
    cursor: { ...C.searchPill }, flag: "manager_layout_v2",
  })},
  // open search
  { t: 3.5, build: () => ({
    cursor: { ...C.searchPill, click: true }, flag: "manager_layout_v2",
  })},
  { t: 4.0, build: () => ({
    cursor: { ...C.searchPill }, flag: "manager_layout_v2",
    search: { visible: true, query: "" },
  })},
  // type "Ariel Barcley"
  ...typeLetters("Ariel Barcley", 5.5, 0.18, "manager_layout_v2"),
  // pause showing results
  { t: 13.5, build: () => ({
    cursor: { x: 540, y: 130 }, flag: "manager_layout_v2",
    search: { visible: true, query: "Ariel Barcley" },
  })},
  // close
  { t: 15.0, build: () => ({
    cursor: { ...C.searchClose, click: true }, flag: "manager_layout_v2",
    search: { visible: true, query: "Ariel Barcley" },
  })},
  { t: 15.4, build: () => ({
    cursor: { ...C.searchClose }, flag: null,
    search: { visible: false, query: "" },
  })},
  // reopen
  { t: 16.6, build: () => ({
    cursor: { ...C.searchPill, click: true }, flag: "manager_layout_v2",
  })},
  { t: 17.0, build: () => ({
    cursor: { ...C.searchPill }, flag: "manager_layout_v2",
    search: { visible: true, query: "" },
  })},
  ...typeLetters("Esther", 17.6, 0.16, "manager_layout_v2"),
  // pause
  { t: 22.5, build: () => ({
    cursor: { x: 540, y: 130 }, flag: "manager_layout_v2",
    search: { visible: true, query: "Esther" },
  })},
  // close
  { t: 24.5, build: () => ({
    cursor: { ...C.searchClose, click: true }, flag: "manager_layout_v2",
    search: { visible: true, query: "Esther" },
  })},
  { t: 24.9, build: () => ({
    cursor: { x: 600, y: 240 }, flag: null,
    search: { visible: false, query: "" },
  })},
  // onboarding index
  { t: 26.0, build: () => ({
    cursor: { x: 360, y: 178 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: [] },
  })},
  // open columns dropdown
  { t: 28.0, build: () => ({
    cursor: { ...C.columnsField, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: [], columnsOpen: false },
  })},
  { t: 28.4, build: () => ({
    cursor: { ...C.columnsField }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: [], columnsOpen: true },
  })},
  // tick Location
  { t: 30.2, build: () => ({
    cursor: { ...C.dropdownLocation, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: [], columnsOpen: true },
  })},
  { t: 30.6, build: () => ({
    cursor: { ...C.dropdownLocation }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location"], columnsOpen: true },
  })},
  // Criminal
  { t: 31.5, build: () => ({
    cursor: { ...C.dropdownCriminal, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location"], columnsOpen: true },
  })},
  { t: 31.9, build: () => ({
    cursor: { ...C.dropdownCriminal }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal"], columnsOpen: true },
  })},
  // MVR
  { t: 32.8, build: () => ({
    cursor: { ...C.dropdownMVR, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal"], columnsOpen: true },
  })},
  { t: 33.2, build: () => ({
    cursor: { ...C.dropdownMVR }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR"], columnsOpen: true },
  })},
  // Drug Test
  { t: 34.0, build: () => ({
    cursor: { ...C.dropdownDrug, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR"], columnsOpen: true },
  })},
  { t: 34.4, build: () => ({
    cursor: { ...C.dropdownDrug }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"], columnsOpen: true },
  })},
  // close dropdown
  { t: 36.0, build: () => ({
    cursor: { x: 700, y: 180 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"], columnsOpen: false },
  })},
  // look at columns
  { t: 38.0, build: () => ({
    cursor: { x: 980, y: 460 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"] },
  })},
  { t: 41.5, build: () => ({
    cursor: { x: 1100, y: 600 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"] },
  })},
  // open date picker
  { t: 44.0, build: () => ({
    cursor: { ...C.dateStart, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"] },
  })},
  { t: 44.4, build: () => ({
    cursor: { ...C.dateStart }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"], datePickerOpen: true },
  })},
  // click May 11
  { t: 46.0, build: () => ({
    cursor: { ...C.dateMay11, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"], datePickerOpen: true },
  })},
  { t: 46.4, build: () => ({
    cursor: { ...C.dateMay11 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            datePickerOpen: true, dateStart: "May 11, 2026", dateHighlightStart: 11 },
  })},
  // hover May 12
  { t: 47.2, build: () => ({
    cursor: { x: 1015, y: 482 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            datePickerOpen: true, dateStart: "May 11, 2026",
            dateHighlightStart: 11, dateHoverDay: 12 },
  })},
  // click May 13 (end)
  { t: 48.4, build: () => ({
    cursor: { ...C.dateMay13, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            datePickerOpen: true, dateStart: "May 11, 2026",
            dateHighlightStart: 11, dateHoverDay: 13 },
  })},
  { t: 48.9, build: () => ({
    cursor: { ...C.dateMay13 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            datePickerOpen: false,
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
  })},
  // show filtered rows
  { t: 50.5, build: () => ({
    cursor: { x: 700, y: 360 }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
  })},
  // move to Download CSV
  { t: 55.0, build: () => ({
    cursor: { ...C.downloadCsv }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
  })},
  { t: 56.5, build: () => ({
    cursor: { ...C.downloadCsv, click: true }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
  })},
  { t: 57.0, build: () => ({
    cursor: { ...C.downloadCsv }, flag: "onboarding_index_manager_ui",
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
    csv: { phase: "preparing", rowCount: 2,
           fileName: "northwind-onboardings-may-11-13-2026.csv" },
  })},
  // ready
  { t: 60.0, build: () => ({
    cursor: { x: 740, y: 460 }, flag: "onboarding_index_manager_ui",
    csv: { phase: "ready", rowCount: 2,
           fileName: "northwind-onboardings-may-11-13-2026.csv" },
  })},
  { t: 62.5, build: () => ({
    cursor: { ...C.csvDownload, click: true }, flag: "onboarding_index_manager_ui",
    csv: { phase: "ready", rowCount: 2,
           fileName: "northwind-onboardings-may-11-13-2026.csv" },
  })},
  // open csv preview
  { t: 63.5, build: () => ({
    cursor: { x: 200, y: 200 }, flag: null,
    csv: { phase: "hidden" },
    csvPreview: { visible: true,
                  fileName: "northwind-onboardings-may-11-13-2026.csv",
                  csvText: computeCsv() },
  })},
  { t: 78.0, build: () => ({
    cursor: { x: 800, y: 300 }, flag: null,
    csvPreview: { visible: true,
                  fileName: "northwind-onboardings-may-11-13-2026.csv",
                  csvText: computeCsv() },
  })},
  // back to page
  { t: 82.0, build: () => ({
    cursor: { x: 700, y: 200 }, flag: null,
    csvPreview: { visible: false, csvText: "" },
    page: { selectedExtras: ["Location","Criminal","MVR","Drug Test"],
            dateStart: "May 11, 2026", dateEnd: "May 13, 2026" },
  })},
  { t: 90.0, build: () => ({
    cursor: { x: 700, y: 200 }, flag: null,
  })},
];

// merge scenes — page state is sticky, overlays use most-recent explicit value
function sceneAt(t) {
  let acc = { page: {}, search: null, csv: null, csvPreview: null, cursor: { x: 0, y: 0 }, flag: null };
  for (const s of SCENES) {
    if (s.t > t) break;
    const b = s.build();
    acc = {
      page:       { ...(acc.page || {}), ...(b.page || {}) },
      search:     b.search       !== undefined ? b.search       : acc.search,
      csv:        b.csv          !== undefined ? b.csv          : acc.csv,
      csvPreview: b.csvPreview   !== undefined ? b.csvPreview   : acc.csvPreview,
      cursor:     b.cursor       !== undefined ? b.cursor       : acc.cursor,
      flag:       b.flag         !== undefined ? b.flag         : acc.flag,
    };
  }
  return acc;
}

// ------------------------------------------------------------------
// Scrubber
// ------------------------------------------------------------------
const CHAPTERS = [
  { t: 0,  label: "New manager UI" },
  { t: 4,  label: "Global search" },
  { t: 16, label: "Search jobs & workers" },
  { t: 26, label: "Onboarding index" },
  { t: 28, label: "Add columns" },
  { t: 44, label: "Filter by date" },
  { t: 56, label: "Export CSV" },
  { t: 64, label: "Open downloaded file" },
];

function fmtTime(s) {
  const m = Math.floor(s / 60);
  const ss = Math.floor(s % 60).toString().padStart(2, "0");
  return `${m}:${ss}`;
}
function currentChapter(t) {
  let c = CHAPTERS[0];
  for (const x of CHAPTERS) if (x.t <= t) c = x;
  return c.label;
}

function Scrubber({ t, dur, playing, onPlayToggle, onSeek }) {
  const pct = Math.min(1, t / dur);
  return (
    <div style={{
      position: "absolute",
      left: 0, right: 0, bottom: 0,
      padding: "10px 16px 14px",
      background: "linear-gradient(0deg, rgba(0,0,0,0.92) 0%, rgba(0,0,0,0.0) 100%)",
      fontFamily: "var(--font-body)",
      zIndex: 300,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <button onClick={onPlayToggle} style={{
          width: 36, height: 36, borderRadius: 999,
          background: "#FFF", border: 0, cursor: "pointer",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>
          <img src={`assets/icons/${playing ? "pause" : "play"}.svg`} width={14} height={14} />
        </button>
        <div style={{
          fontSize: 12, color: "#FFF", fontVariantNumeric: "tabular-nums", minWidth: 80,
        }}>{fmtTime(t)} / {fmtTime(dur)}</div>
        <div style={{ flex: 1, position: "relative", height: 22, display: "flex", alignItems: "center", cursor: "pointer" }}
          onClick={(e) => {
            const rect = e.currentTarget.getBoundingClientRect();
            const x = (e.clientX - rect.left) / rect.width;
            onSeek(Math.max(0, Math.min(1, x)) * dur);
          }}>
          <div style={{ position: "absolute", left: 0, right: 0, height: 4, borderRadius: 999,
            background: "rgba(255,255,255,0.22)" }} />
          <div style={{ position: "absolute", left: 0, width: `${pct * 100}%`,
            height: 4, borderRadius: 999, background: "#493ED8" }} />
          {CHAPTERS.map((c, i) => (
            <div key={i} title={c.label} style={{
              position: "absolute", left: `${(c.t / dur) * 100}%`,
              width: 2, height: 10, marginLeft: -1,
              background: "#FFF", opacity: 0.6, borderRadius: 1,
            }} />
          ))}
          <div style={{ position: "absolute", left: `${pct * 100}%`,
            width: 12, height: 12, marginLeft: -6,
            borderRadius: 999, background: "#FFF",
            border: "2px solid #493ED8" }} />
        </div>
        <div style={{
          fontSize: 12, color: "#FFF", fontWeight: 600, opacity: 0.85,
          minWidth: 180, textAlign: "right",
        }}>{currentChapter(t)}</div>
      </div>
    </div>
  );
}

// ------------------------------------------------------------------
// Walkthrough host
// ------------------------------------------------------------------
function Walkthrough() {
  const DUR = 90;
  const [t, setT] = useState(() => {
    const v = parseFloat(localStorage.getItem("walkthrough_t"));
    return isNaN(v) ? 0 : Math.max(0, Math.min(DUR, v));
  });
  const [playing, setPlaying] = useState(true);

  useEffect(() => {
    localStorage.setItem("walkthrough_t", String(t));
  }, [t]);

  useEffect(() => {
    if (!playing) return;
    let raf, last = performance.now();
    function tick(now) {
      const dt = (now - last) / 1000;
      last = now;
      setT(prev => {
        const nxt = prev + dt;
        if (nxt >= DUR) { setPlaying(false); return DUR; }
        return nxt;
      });
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  // notify parent (for speaker notes — chapter index)
  useEffect(() => {
    const idx = (() => {
      let i = 0;
      for (let j = 0; j < CHAPTERS.length; j++) if (CHAPTERS[j].t <= t) i = j;
      return i;
    })();
    try { window.parent.postMessage({ slideIndexChanged: idx }, "*"); } catch (e) {}
  }, [t]);

  const scene = sceneAt(t);

  return (
    <div style={{
      position: "relative",
      width: "100%", height: "100%",
      background: "#FFF", overflow: "hidden",
    }}>
      <ManagerApp scene={scene} />
      <Cursor x={scene.cursor.x} y={scene.cursor.y} clicking={!!scene.cursor.click} />
      <FlagBadge label={scene.flag} />
      <Scrubber t={t} dur={DUR} playing={playing}
        onPlayToggle={() => {
          if (t >= DUR) { setT(0); setPlaying(true); }
          else setPlaying(p => !p);
        }}
        onSeek={(nt) => { setT(nt); }} />
    </div>
  );
}

Object.assign(window, { Walkthrough });
})();
