// tutorials/scenes.jsx
// Per-step scenes for the Skyward import tutorial (no key chords — drag selection).

// ── Selection rect (visible drag highlight) ─────────────────────────────────
function SelectionRect({ x1, y1, x2, y2, opacity = 1 }) {
  const left = Math.min(x1, x2), top = Math.min(y1, y2);
  const w = Math.abs(x2 - x1), h = Math.abs(y2 - y1);
  return (
    <div style={{
      position: 'absolute', left, top, width: w, height: h,
      background: 'rgba(47,111,216,0.18)', border: '1px solid rgba(47,111,216,0.6)',
      pointerEvents: 'none', zIndex: 70, opacity,
    }} />
  );
}

// ── Scene 1: open Grades, click the B in CHEMISTRY/S2 cell ──────────────────
function Scene1({ start, end }) {
  // Read the rendered position of the highlighted B cell from the DOM each frame.
  const [target, setTarget] = React.useState({ x: 1450, y: 400 });
  React.useEffect(() => {
    let raf;
    const tick = () => {
      const cell = document.querySelector('[data-target="grade-cell"]');
      if (cell) {
        // Find the Stage's scaled inner element to get the inverse scale
        const stageInner = document.querySelector('[data-stage-canvas]') || cell.closest('[style*="transform"]')?.parentElement || null;
        const r = cell.getBoundingClientRect();
        // Convert viewport coords back into canvas coords by undoing scale.
        // The Stage wrapper sets transform: scale(s); we read the matrix.
        let scale = 1, originLeft = 0, originTop = 0;
        const canvas = document.querySelector('[data-stage-canvas]');
        if (canvas) {
          const cr = canvas.getBoundingClientRect();
          scale = cr.width / 1920;
          originLeft = cr.left;
          originTop = cr.top;
        }
        const cx = (r.left + r.width / 2 - originLeft) / scale;
        const cy = (r.top + r.height / 2 - originTop) / scale;
        setTarget({ x: cx, y: cy });
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <Sprite start={start} end={end} key="s1">
      {({ localTime }) => {
        const tx = interpolate([0, 1.5, 2.5, 3.2], [100, target.x, target.x, target.x], Easing.easeInOutCubic)(localTime);
        const ty = interpolate([0, 1.5, 2.5, 3.2], [700, target.y, target.y, target.y], Easing.easeInOutCubic)(localTime);
        const clicking = localTime > 2.8 && localTime < 3.1;
        const fade = localTime < 0.3 ? localTime / 0.3 : 1;
        return (
          <div style={{ position: 'absolute', inset: 0, opacity: fade }}>
            <SkyGrades />
            <StepChip step={1} total={5} label="Open your Grades — click a grade" />
            {localTime > 1.8 && localTime < 3.3 && (
              <Tooltip x={target.x - 80} y={target.y - 56} text="Click your grade" arrow="down" />
            )}
            <FakeCursor x={tx} y={ty} clicking={clicking} />
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Scene 2: flyout opens, click Calculations ───────────────────────────────
function Scene2({ start, end }) {
  return (
    <Sprite start={start} end={end} key="s2">
      {({ localTime }) => {
        const flyT = Easing.easeOutCubic(clamp(localTime / 0.6, 0, 1));
        const flyX = 660 + (1 - flyT) * 100;

        // Calculations button center ≈ (1055, 170)
        const tx = interpolate([0, 1.2, 2.0, 2.6], [900, 900, 1055, 1055], Easing.easeInOutCubic)(localTime);
        const ty = interpolate([0, 1.2, 2.0, 2.6], [420, 420, 170, 170], Easing.easeInOutCubic)(localTime);
        const clicking = localTime > 2.3 && localTime < 2.55;

        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <SkyGrades />
            <div style={{ position: 'absolute', left: flyX, top: 130, opacity: flyT }}>
              <SkyFlyout />
            </div>
            <StepChip step={2} total={5} label="Open Calculations (weights)" />
            {localTime > 1.5 && localTime < 2.7 && (
              <Tooltip x={985} y={108} text="Click Calculations" arrow="down" />
            )}
            <FakeCursor x={tx} y={ty} clicking={clicking} />
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Scene 3: Calculations dialog, drag-select all rows + headers, copy ──────
function Scene3({ start, end }) {
  return (
    <Sprite start={start} end={end} key="s3">
      {({ localTime }) => {
        // Dialog: positioned at left=350, top=240; width=640. Inside content padding ≈ 22+18=40.
        // Top of class title row ≈ y=290; bottom of last row (Summative) ≈ y=540.
        // Drag from top-left of class header to bottom-right of last row's last cell.
        const dialogT = Easing.easeOutCubic(clamp(localTime / 0.5, 0, 1));

        // Drag timing: cursor lands at start point ~0.8s, drags to end point by ~2.4s
        const dragStart = { x: 380, y: 295 };
        const dragEnd   = { x: 970, y: 555 };

        const cursorX = interpolate(
          [0, 0.8, 2.4, 3.2],
          [200, dragStart.x, dragEnd.x, dragEnd.x],
          Easing.easeInOutCubic
        )(localTime);
        const cursorY = interpolate(
          [0, 0.8, 2.4, 3.2],
          [800, dragStart.y, dragEnd.y, dragEnd.y],
          Easing.easeInOutCubic
        )(localTime);

        // Selection rectangle grows as cursor moves
        const dragT = clamp((localTime - 0.8) / 1.6, 0, 1);
        const showRect = localTime > 0.85 && localTime < 3.0;
        const rectX = dragStart.x + (dragEnd.x - dragStart.x) * Easing.easeInOutCubic(dragT);
        const rectY = dragStart.y + (dragEnd.y - dragStart.y) * Easing.easeInOutCubic(dragT);

        // Once drag completes, mark cells as selected
        const selectAll = localTime > 2.3;

        // Right-click → "Copy" appears
        const showMenu = localTime > 2.8 && localTime < 4.0;
        const copied = localTime > 3.5;

        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <SkyGrades />
            <div style={{
              position: 'absolute', left: 350, top: 240,
              opacity: dialogT, transform: `scale(${0.96 + 0.04 * dialogT})`, transformOrigin: 'center',
            }}>
              <SkyCalculations selectedAll={selectAll} />
            </div>

            {showRect && <SelectionRect x1={dragStart.x} y1={dragStart.y} x2={rectX} y2={rectY} />}

            <StepChip step={3} total={5} label="Drag to select all weights" />
            {localTime > 0.4 && localTime < 1.8 && (
              <Tooltip x={dragStart.x + 16} y={dragStart.y - 50} text="Click & drag from here…" arrow="down" />
            )}
            {showMenu && <ContextMenu x={dragEnd.x + 4} y={dragEnd.y + 4} highlighted={localTime > 3.2} />}
            {copied && <CopiedToast x={1400} y={60} label="Weights copied" />}

            <FakeCursor x={cursorX} y={cursorY} clicking={(localTime > 0.78 && localTime < 0.92) || (localTime > 2.85 && localTime < 3.0)} />
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Scene 4: paste weights into lock in. import dialog ──────────────────────
function Scene4({ start, end }) {
  return (
    <Sprite start={start} end={end} key="s4">
      {({ localTime }) => {
        const fadeT = Easing.easeInOutCubic(clamp(localTime / 0.6, 0, 1));
        const filled = localTime > 1.8 ? 1 : 0;
        const highlightPaste = localTime > 0.8 && localTime < 2.0;
        const showMenu = localTime > 1.0 && localTime < 2.0;
        const cursorX = interpolate([0, 0.7, 1.5, 2.5], [1500, 800, 800, 800], Easing.easeInOutCubic)(localTime);
        const cursorY = interpolate([0, 0.7, 1.5, 2.5], [800, 540, 540, 540], Easing.easeInOutCubic)(localTime);

        return (
          <div style={{ position: 'absolute', inset: 0, background: '#0b1326' }}>
            <div style={{ position: 'absolute', inset: 0, opacity: 0.08, filter: 'blur(4px)' }}>
              <SkyGrades />
            </div>
            <div style={{
              position: 'absolute', left: '50%', top: '50%',
              transform: `translate(-50%, -50%) scale(${0.96 + 0.04 * fadeT})`,
              opacity: fadeT,
            }}>
              <LockInImportDialog filled={filled} highlightPaste={highlightPaste} />
            </div>
            <StepChip step={4} total={5} label="Paste weights into lock in." />
            {showMenu && <ContextMenu x={cursorX + 8} y={cursorY + 8} pasteMode highlighted={localTime > 1.4} />}
            <FakeCursor x={cursorX} y={cursorY} clicking={localTime > 1.1 && localTime < 1.3} />
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Scene 5: back to flyout, drag-select assignments, copy, paste ──────────
function Scene5({ start, end }) {
  return (
    <Sprite start={start} end={end} key="s5">
      {({ localTime }) => {
        // Phase A: Skyward flyout, drag-select header through bottom row (0 - 3.5)
        // Phase B: transition to lock in. and paste (3.5 - end)
        const phaseA = localTime < 3.6;

        // Drag covers the WHOLE flyout including the CHEMISTRY header row.
        // Flyout: left=660, top=130, width=560.
        const dragStart = { x: 665, y: 135 };
        const dragEnd   = { x: 1210, y: 720 };

        const cursorAX = interpolate([0, 0.6, 2.4, 3.2], [200, dragStart.x, dragEnd.x, dragEnd.x], Easing.easeInOutCubic)(localTime);
        const cursorAY = interpolate([0, 0.6, 2.4, 3.2], [800, dragStart.y, dragEnd.y, dragEnd.y], Easing.easeInOutCubic)(localTime);
        const dragT = clamp((localTime - 0.6) / 1.8, 0, 1);
        const showRect = localTime > 0.65 && localTime < 3.4;
        const rectX = dragStart.x + (dragEnd.x - dragStart.x) * Easing.easeInOutCubic(dragT);
        const rectY = dragStart.y + (dragEnd.y - dragStart.y) * Easing.easeInOutCubic(dragT);
        const selectAll = localTime > 2.4 && localTime < 3.6;
        const showMenuA = localTime > 2.7 && localTime < 3.5;

        const transT = Easing.easeInOutCubic(clamp((localTime - 3.5) / 0.6, 0, 1));
        const filled = localTime > 4.6 ? 2 : 0;
        const highlightPaste = localTime > 4.2 && localTime < 5.2;
        const showMenuB = localTime > 4.4 && localTime < 5.2;
        const cursorBX = 800;
        const cursorBY = 600;
        const done = localTime > 5.4;

        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            {phaseA ? (
              <>
                <SkyGrades />
                <div style={{ position: 'absolute', left: 660, top: 130 }}>
                  <SkyFlyout selectedAll={selectAll} />
                </div>
                {showRect && <SelectionRect x1={dragStart.x} y1={dragStart.y} x2={rectX} y2={rectY} />}
                <StepChip step={5} total={5} label="Drag to select assignments" />
                {localTime > 0.3 && localTime < 1.4 && (
                  <Tooltip x={dragStart.x + 16} y={dragStart.y - 50} text="Click & drag from here…" arrow="down" />
                )}
                {showMenuA && <ContextMenu x={dragEnd.x + 4} y={dragEnd.y - 80} highlighted={localTime > 3.0} />}
                <FakeCursor x={cursorAX} y={cursorAY} clicking={(localTime > 0.55 && localTime < 0.7) || (localTime > 2.75 && localTime < 2.9)} />
              </>
            ) : (
              <div style={{ position: 'absolute', inset: 0, background: '#0b1326' }}>
                <div style={{ position: 'absolute', inset: 0, opacity: 0.08, filter: 'blur(4px)' }}><SkyGrades /></div>
                <div style={{
                  position: 'absolute', left: '50%', top: '50%',
                  transform: `translate(-50%, -50%) scale(${0.96 + 0.04 * transT})`,
                  opacity: transT,
                }}>
                  <LockInImportDialog filled={filled} highlightPaste={highlightPaste} />
                </div>
                <StepChip step={5} total={5} label="Paste grades — done." />
                {showMenuB && <ContextMenu x={cursorBX + 8} y={cursorBY + 8} pasteMode highlighted={localTime > 4.7} />}
                <FakeCursor x={cursorBX} y={cursorBY} clicking={localTime > 4.5 && localTime < 4.7} />
                {done && <SuccessBadge x={960} y={870} />}
              </div>
            )}
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Helpers ─────────────────────────────────────────────────────────────────

function Tooltip({ x, y, text, arrow = 'down' }) {
  return (
    <div style={{ position: 'absolute', left: x, top: y, zIndex: 85 }}>
      <div style={{
        background: '#171f33', color: '#dae2fd',
        padding: '8px 14px', borderRadius: 8,
        fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 13,
        border: '1px solid rgba(142,213,255,0.3)',
        boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
        whiteSpace: 'nowrap',
      }}>{text}</div>
      {arrow === 'down' && (
        <div style={{
          position: 'absolute', left: 20, top: 32,
          width: 0, height: 0,
          borderLeft: '6px solid transparent', borderRight: '6px solid transparent',
          borderTop: '8px solid #171f33',
        }} />
      )}
    </div>
  );
}

// Native-OS-style right-click context menu showing Copy/Paste highlighted
function ContextMenu({ x, y, pasteMode = false, highlighted = false }) {
  const items = pasteMode
    ? [{ label: 'Cut',   active: false }, { label: 'Copy',  active: false }, { label: 'Paste', active: true }, { label: 'Select All', active: false }]
    : [{ label: 'Cut',   active: false }, { label: 'Copy',  active: true  }, { label: 'Paste', active: false }, { label: 'Select All', active: false }];

  return (
    <div style={{
      position: 'absolute', left: x, top: y, zIndex: 95,
      background: '#fff', border: '1px solid #b6c4d9',
      boxShadow: '0 16px 40px rgba(0,0,0,0.25)',
      borderRadius: 6, padding: 4, minWidth: 160,
      fontFamily: 'Inter, sans-serif',
    }}>
      {items.map((item, i) => (
        <div key={item.label} style={{
          padding: '7px 14px', fontSize: 13,
          color: item.active && highlighted ? '#fff' : '#1b2636',
          background: item.active && highlighted ? '#2f6fd8' : 'transparent',
          borderRadius: 4, fontWeight: item.active ? 600 : 500,
          display: 'flex', justifyContent: 'space-between', gap: 24,
        }}>
          <span>{item.label}</span>
          <span style={{ fontSize: 11, opacity: 0.55 }}>
            {item.label === 'Copy' ? '⌘C' : item.label === 'Paste' ? '⌘V' : item.label === 'Cut' ? '⌘X' : '⌘A'}
          </span>
        </div>
      ))}
    </div>
  );
}

function CopiedToast({ x, y, label }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      background: 'rgba(142,213,255,0.12)', color: '#8ed5ff',
      padding: '8px 16px', borderRadius: 9999,
      fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 12,
      border: '1px solid rgba(142,213,255,0.4)', display: 'flex', alignItems: 'center', gap: 8,
      zIndex: 90,
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12" />
      </svg>
      {label}
    </div>
  );
}

function SuccessBadge({ x, y }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, transform: 'translateX(-50%)',
      background: 'rgba(142,213,255,0.15)', color: '#8ed5ff',
      padding: '10px 20px', borderRadius: 9999,
      fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14,
      border: '1px solid rgba(142,213,255,0.4)',
      boxShadow: '0 0 30px rgba(142,213,255,0.3)',
      display: 'flex', alignItems: 'center', gap: 10,
      zIndex: 90,
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12" />
      </svg>
      Class imported — weights + grades ready
    </div>
  );
}

Object.assign(window, { Scene1, Scene2, Scene3, Scene4, Scene5 });
