/* eslint-disable */
/* Screens 4–6. Scene area is 1380 × 900. */

/* ============================================================
   SCREEN 4 — Use Cases
   ============================================================ */
function Screen4({ onNext, onBack, useCaseIndex, setUseCaseIndex, videoOpen, setVideoOpen }) {
  const useCases = [
    { n: "01", title: "Cross-domain Signalling / Rolling Stock", short: "Signalling × RS" },
    { n: "02", title: "SW / HW evolvability",                   short: "SW/HW evolvability" },
    { n: "03", title: "Resilience / track anomaly / weather",   short: "Resilience" },
    { n: "04", title: "Individualized doors behaviour",         short: "Doors behaviour" },
    { n: "05", title: "Software Upgrade / App Store",           short: "App Store" },
    { n: "06", title: "Improve train performances",             short: "Performance" },
  ];

  const current = useCases[useCaseIndex];

  return (
    <React.Fragment>
      {/* Title */}
      <div style={{ position: "absolute", left: 60, top: 60, width: 760 }}>
        <div className="wf-title" style={{ fontSize: 44 }}>Discover the SDT use cases</div>
        <div className="wf-subtitle" style={{ marginTop: 8 }}>
          Six use cases — click any tile to play its video.
        </div>
      </div>

      {/* 6 tiles aligned at the bottom — title on top, small thumbnail below */}
      <div style={{
        position: "absolute", left: 60, top: 680, width: 1260, height: 170,
        display: "grid", gridTemplateColumns: "repeat(6, 1fr)",
        gap: 12,
      }}>
        {useCases.map((uc, i) => {
          const isActive = videoOpen && i === useCaseIndex;
          return (
            <div
              key={uc.n}
              onClick={() => { setUseCaseIndex(i); setVideoOpen(true); }}
              style={{
                border: isActive ? "1.5px solid var(--accent)" : "1px solid var(--ink)",
                background: isActive ? "var(--accent-soft)" : "var(--paper)",
                padding: 10,
                cursor: "pointer",
                display: "flex",
                flexDirection: "column",
                gap: 8,
                transition: "border-color 0.15s, background 0.15s",
              }}
            >
              {/* Title row above the thumbnail */}
              <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
                <div className="numdot" style={{ width: 22, height: 22, fontSize: 10, flexShrink: 0 }}>{uc.n}</div>
                <div style={{ fontSize: 12, fontWeight: 600, lineHeight: 1.2 }}>{uc.title}</div>
              </div>

              {/* Small thumbnail */}
              <div style={{ position: "relative", flex: 1, minHeight: 70 }}>
                <Placeholder x={0} y={0} w={"100%"} h={"100%"} />
                <div style={{
                  position: "absolute", inset: 0,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 18, color: "var(--ink-2)",
                  pointerEvents: "none",
                }}>▶</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Video popup — immersive: title overlaid on the video, no header band, no prev/next. */}
      {videoOpen && (
        <div style={{
          position: "absolute", left: 240, top: 170, width: 900,
          background: "var(--paper)", border: "1px solid var(--ink)",
          boxShadow: "0 18px 50px rgba(0,0,0,0.18)",
          display: "flex", flexDirection: "column",
          zIndex: 30,
        }}>
          {/* Player */}
          <div style={{ position: "relative", height: 440 }}>
            <Placeholder x={0} y={0} w={"100%"} h={"100%"} label={`Use case ${current.n}`} />

            {/* Title overlay on the video */}
            <div style={{
              position: "absolute", left: 22, top: 22, right: 70,
              fontSize: 22, fontWeight: 600, lineHeight: 1.2,
              color: "var(--ink)",
              background: "rgba(255,255,255,0.88)",
              padding: "8px 14px",
              border: "1px solid var(--ink-2)",
              pointerEvents: "none",
            }}>{current.title}</div>

            {/* Close button overlay */}
            <button
              className="close"
              onClick={() => setVideoOpen(false)}
              style={{ position: "absolute", top: 18, right: 18, background: "rgba(255,255,255,0.92)" }}
            >×</button>
          </div>

          {/* Bottom controls — play/pause + scrubber only */}
          <div className="video-controls">
            <WfBtn icon>▶</WfBtn>
            <div className="scrubber">
              <div className="fill"></div>
              <div className="knob"></div>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", minWidth: 80, textAlign: "right" }}>00:42 / 01:58</div>
          </div>
        </div>
      )}

      <SceneNav />
    </React.Fragment>
  );
}

/* ============================================================
   SCREEN 5 — Value Customer Benefits
   ============================================================ */
function Screen5({ onNext, onBack, activeBenefit, setActiveBenefit }) {
  const benefits = [
    { n: "01", label: "Operators",                    pitch: "Streamlined operations and easier piloting." },
    { n: "02", label: "Maintainers",                  pitch: "Predictive maintenance and reduced downtime." },
    { n: "03", label: "Passengers",                   pitch: "A smoother, more personalised journey." },
    { n: "04", label: "Public authorities / lessors", pitch: "A future-proof, evolvable investment." },
  ];

  return (
    <React.Fragment>
      <div style={{ position: "absolute", left: 60, top: 60, width: 760 }}>
        <div className="wf-title" style={{ fontSize: 44 }}>Value · customer benefits</div>
        <div className="wf-subtitle" style={{ marginTop: 8 }}>
          Four pillars — click a pillar to expand its value.
        </div>
      </div>

      <div style={{
        position: "absolute", left: 60, top: 230, width: 1260, height: 540,
        display: "flex", gap: 16,
      }}>
        {benefits.map((b, i) => {
          const isActive = activeBenefit === i;
          const isDim = activeBenefit !== null && !isActive;
          const flex = isActive ? 2.6 : (activeBenefit !== null ? 0.8 : 1);
          return (
            <div
              key={i}
              className={"pillar" + (isActive ? " active" : "") + (isDim ? " dim" : "")}
              onClick={() => setActiveBenefit(isActive ? null : i)}
              style={{ flex }}
            >
              <div className="pillar-num">{b.n}</div>
              {isActive ? (
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  <div className="pillar-label">{b.label}</div>
                  <div className="wf-body">{b.pitch}</div>
                  <TxtBars x={0} y={0} w={"100%"} lines={4} style={{ position: "relative" }} />
                  <div className="wf-eyebrow" style={{ marginTop: 10 }}>Benefit keywords</div>
                  <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                    <span className="chip">keyword</span>
                    <span className="chip">keyword</span>
                    <span className="chip">keyword</span>
                  </div>
                  <div style={{ marginTop: "auto" }}>
                    <WfBtn ghost onClick={(e) => { e.stopPropagation(); setActiveBenefit(null); }}>← Collapse</WfBtn>
                  </div>
                </div>
              ) : (
                <div className="pillar-label">{b.label}</div>
              )}
            </div>
          );
        })}
      </div>

      <SceneNav onBack={onBack} onNext={onNext} />
    </React.Fragment>
  );
}

/* ============================================================
   SCREEN 6 — Video globale
   ============================================================ */
function Screen6({ playerState, setPlayerState, onBack, onReset }) {
  // "launch" | "playing" | "ended"
  const [progress, setProgress] = useState(0.38);

  // Make the scrubber actually act as the timeline
  const scrubberRef = useRef(null);
  const draggingRef = useRef(false);
  const setFromEvent = (e) => {
    const el = scrubberRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
    const v = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
    setProgress(v);
    if (v >= 0.99) setPlayerState("ended");
    else if (playerState === "ended") setPlayerState("playing");
  };
  const onScrubDown = (e) => {
    draggingRef.current = true;
    setFromEvent(e);
    e.preventDefault();
  };
  useEffect(() => {
    const move = (e) => { if (draggingRef.current) setFromEvent(e); };
    const up = () => { draggingRef.current = false; };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
  });

  // Reset progress when restarting/launching
  useEffect(() => {
    if (playerState === "launch") setProgress(0.38);
  }, [playerState]);

  const totalSec = 102;
  const curSec = Math.round(progress * totalSec);
  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;
  const pct = `${progress * 100}%`;

  return (
    <React.Fragment>
      {playerState === "launch" && (
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 22,
          background: "rgba(255,255,255,0.45)",
        }}>
          <div className="wf-title" style={{ fontSize: 52, textAlign: "center", maxWidth: 900 }}>
            The Software-defined Train — the full story
          </div>
          <div className="wf-subtitle">1–2 minutes · concept video</div>
          <div style={{ height: 10 }}></div>
          <WfBtn primary lg onClick={() => setPlayerState("playing")}>▶ Launch video</WfBtn>
        </div>
      )}

      {(playerState === "playing" || playerState === "ended") && (
        <React.Fragment>
          {/* X close — top-right, returns to launch (and re-shows the menu) */}
          <button
            className="close"
            onClick={() => setPlayerState("launch")}
            style={{
              position: "absolute", top: 24, right: 24,
              width: 40, height: 40, fontSize: 16,
              zIndex: 40,
              background: "rgba(255,255,255,0.9)",
            }}
            title="Exit immersive playback"
          >×</button>

          {/* Bottom controls — play/pause, draggable timeline, restart when ended */}
          <div style={{
            position: "absolute", left: 40, right: 40, bottom: 40,
            background: "var(--paper)", border: "1px solid var(--ink)",
            padding: "18px 22px",
            display: "flex", flexDirection: "column", gap: 14,
            zIndex: 35,
          }}>
            {/* Timeline — explicit standalone element so it's clearly visible */}
            <div
              ref={scrubberRef}
              onMouseDown={onScrubDown}
              onTouchStart={onScrubDown}
              style={{
                position: "relative",
                width: "100%",
                height: 8,
                background: "#c4c4c4",
                border: "1px solid #1a1a1a",
                cursor: "pointer",
              }}
            >
              <div style={{
                position: "absolute",
                left: 0, top: 0, bottom: 0,
                width: pct,
                background: "var(--accent)",
              }}></div>
              <div style={{
                position: "absolute",
                top: "50%",
                left: pct,
                width: 16, height: 16,
                background: "#1a1a1a",
                borderRadius: "50%",
                transform: "translate(-50%, -50%)",
              }}></div>
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <WfBtn icon onClick={() => {
                if (playerState === "ended") { setProgress(0); setPlayerState("playing"); }
              }}>
                {playerState === "ended" ? "▶" : "❚❚"}
              </WfBtn>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                {fmt(curSec)} / {fmt(totalSec)}
              </div>
            </div>
          </div>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { Screen4, Screen5, Screen6 });
