// screens-detail.jsx — DetailScreen + NavigateScreen + WatchScreen + VideoDrawer

const { useState, useRef, useEffect } = React;
const Icon2 = window.Icon;
const PatchBadge = window.PatchBadge;

// ============================================================ DETAIL
function DetailScreen({ stop, userPos, onNavigate, onWatch, onBack, claimed = new Set(), onClaim, isNearby = false }) {
  const scrollRef = useRef(null);
  const [atBottom, setAtBottom] = useState(false);

  const onScroll = (e) => {
    const el = e.currentTarget;
    setAtBottom(el.scrollTop + el.clientHeight >= el.scrollHeight - 4);
  };

  useEffect(() => {
    const el = scrollRef.current;
    if (el) setAtBottom(el.scrollHeight <= el.clientHeight + 4);
  }, [stop]);

  const hasVideos = stop.videos.some((v) => v.src);
  const nav = window.computeNav ? window.computeNav(stop, userPos) : null;
  const isClaimed = claimed.has(stop.id);

  return (
    <div className="screen detail" style={{ padding: "34px 38px 26px" }} data-back-on-left-edge data-right-next>
      <div className="bloom" style={{ width: 260, height: 150, top: -50, left: 160, opacity: 0.7, zIndex: 0 }} />

      <div className="dt-hero">
        <div className="dt-meta">
          <div className="dt-subtitle">{stop.subtitle}</div>
          <div className="dt-name">{stop.name}</div>
          <div className="dt-addr">{stop.address}</div>
        </div>
      </div>

      {/* Navigate button */}
      {nav && (
        <button
          className="navigate-btn focusable"
          data-autofocus
          onClick={() => onNavigate(stop)}
        >
          <span className="nb-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="9"/>
              <polygon points="12 7 15 16 12 14 9 16 12 7" fill="currentColor" stroke="none"/>
            </svg>
          </span>
          <span className="nb-text">
            <span className="nb-label">Navigate</span>
            <span className="nb-sub">{nav.distLabel} · {nav.etaLabel} · turn-by-turn</span>
          </span>
          <span className="nb-chev">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="9 6 15 12 9 18"/>
            </svg>
          </span>
        </button>
      )}

      <div className="dt-scroll-wrap">
        <div
          className="dt-scroll focusable"
          data-autofocus={nav ? undefined : true}
          data-scroll
          ref={scrollRef}
          onScroll={onScroll}
        >
          <p className="lede">{stop.lede}</p>
          <p className="hpar">{stop.story}</p>

          {stop.landmarks.length > 0 && (
            <>
              <div className="section-label">Landmarks</div>
              {stop.landmarks.map((lm) => (
                <div key={lm.name} className="landmark-item">
                  <div className="lm-year">{lm.year}</div>
                  <div className="lm-name">{lm.name}</div>
                  <div className="lm-fact">{lm.fact}</div>
                </div>
              ))}
            </>
          )}

          {stop.keyFacts.length > 0 && (
            <>
              <div className="section-label">Key Dates</div>
              {stop.keyFacts.map((kf) => (
                <div key={kf.year + kf.text} className="keyfact-row">
                  <span className="kf-year">{kf.year}</span>
                  <span className="kf-text">{kf.text}</span>
                </div>
              ))}
            </>
          )}

          {stop.keyMoment && (
            <div className="key-moment-callout">
              <div className="km-date">{stop.keyMoment.date}</div>
              <div className="km-headline">{stop.keyMoment.headline}</div>
              <div className="km-detail">{stop.keyMoment.detail}</div>
            </div>
          )}

          {stop.promoCode && (
            <div className="promo-callout">
              <div className="promo-label">Admission Discount</div>
              <div className="promo-code">{stop.promoCode}</div>
              <div className="promo-detail">Use this code for 20% off admission</div>
            </div>
          )}

          <div style={{ height: 14 }} />
        </div>
        <div className={"scroll-cue" + (atBottom ? " hidden" : "")} aria-hidden="true">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: "rotate(90deg)" }}>
            <polyline points="9 6 15 12 9 18"/>
          </svg>
        </div>
      </div>

      {hasVideos && stop.videos.filter((v) => v.src).map((v) => (
        <button key={v.src} className="watch-bar focusable" onClick={() => onWatch(v, stop.name)}>
          <span className="wb-play"><Icon2 name="play" size={13} /></span>
          <span className="wb-text">
            <span className="wb-title">{v.title}</span>
            <span className="wb-meta">{v.channel} · {v.year}</span>
          </span>
        </button>
      ))}

      <div className="detail-foot">
        <button className="btn focusable" data-back onClick={onBack}>
          <Icon2 name="back" size={14} /> Back
        </button>
        {isClaimed ? (
          <div className="patch-earned">
            <PatchBadge stop={stop} size={34} claimed={true} />
            <span className="pe-label">Claimed</span>
          </div>
        ) : isNearby ? (
          <button className="btn focusable" onClick={() => {
            window.playCollectSound && window.playCollectSound();
            onClaim && onClaim(stop.id);
          }}>
            <PatchBadge stop={stop} size={22} claimed={false} />
            Claim Patch
          </button>
        ) : null}
      </div>
    </div>
  );
}

// ============================================================ NAVIGATE
function NavigateScreen({ stop, userPos, onBack }) {
  const nav = window.computeNav ? window.computeNav(stop, userPos) : null;
  if (!nav) return null;

  // SVG for the maneuver arrow (north-pointing triangle)
  const ManeuverArrow = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <polygon points="12 2 21 21 12 16 3 21 12 2"/>
    </svg>
  );

  // Chevron shape (upward V)
  const ChevSvg = ({ size }) => (
    <svg width={size} height={Math.round(size * 0.625)} viewBox="0 0 32 20" fill="currentColor" stroke="none">
      <polygon points="16 0 32 16 24 16 16 8 8 16 0 16"/>
    </svg>
  );

  // Pin for arrival step
  const PinIcon = () => (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0Z"/>
      <circle cx="12" cy="10" r="2.4" fill="currentColor" stroke="none"/>
    </svg>
  );

  // Small turn arrow for step list
  const TurnArrow = ({ transform }) => (
    <span style={{ display: "flex", transform }}>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="none">
        <polygon points="12 3 19 18 12 14 5 18 12 3"/>
      </svg>
    </span>
  );

  return (
    <div className="screen" style={{ padding: "34px 38px 26px" }}>
      <div className="bloom" style={{ width: 280, height: 240, top: 90, left: "50%", transform: "translateX(-50%)", opacity: 0.7, zIndex: 0 }} />

      {/* Maneuver heading */}
      <div className="nav-maneuver">
        <div className="nav-arrow-wrap">
          <div className="nav-arrow-inner" style={{ transform: nav.maneuverTransform }}>
            <ManeuverArrow />
          </div>
        </div>
        <div className="nav-instr">
          <div className="nav-instr-text">{nav.instruction}</div>
          <div className="nav-instr-sub">
            {nav.nextDist ? `Next in ${nav.nextDist} · ` : ""}Head {nav.compass}
          </div>
        </div>
      </div>

      {/* Animated chevron lane */}
      <div className="nav-lane-wrap">
        <div className="nav-lane" style={nav.laneStyle}>
          <div className="nav-chev" style={{ animationDelay: ".52s" }}><ChevSvg size={26} /></div>
          <div className="nav-chev" style={{ animationDelay: ".26s" }}><ChevSvg size={40} /></div>
          <div className="nav-chev" style={{ animationDelay: "0s"   }}><ChevSvg size={56} /></div>
        </div>
        <div className="nav-street">{nav.currentStreet}</div>
      </div>

      {/* Turn-by-turn list */}
      <div style={{ marginTop: "auto", minHeight: 0, display: "flex", flexDirection: "column", zIndex: 2 }}>
        <div className="nav-steps-hd">
          <span className="label nav-steps-label">Turn-by-turn</span>
          <span className="nav-dist-eta">{nav.distLabel} · {nav.etaLabel}</span>
        </div>
        <div className="nav-steps">
          {nav.steps.map((st, i) => (
            <div key={i} className="nav-step">
              <span className="nav-step-marker">
                {st.arrive
                  ? <PinIcon />
                  : <TurnArrow transform={st.transform} />
                }
              </span>
              <span className="nav-step-text">{st.text}</span>
              <span className="nav-step-dist">{st.dist}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
        <button className="btn focusable" data-autofocus data-back onClick={onBack}>
          <Icon2 name="back" size={14} /> Back
        </button>
      </div>
    </div>
  );
}

// ============================================================ WATCH
// Autoplay policy: play() runs after the async HLS manifest load, outside the
// user-gesture window, so unmuted playback can be rejected — retry muted
// (always allowed) and let the user unmute via the controls.
function useHlsAutoplay(vidRef, src) {
  useEffect(() => {
    const v = vidRef.current;
    if (!v) return;
    const tryPlay = () =>
      v.play().catch(() => {
        v.muted = true;
        v.play().catch(() => {});
      });
    let hls;
    if (window.Hls && window.Hls.isSupported()) {
      hls = new window.Hls();
      hls.loadSource(src);
      hls.attachMedia(v);
      hls.on(window.Hls.Events.MANIFEST_PARSED, tryPlay);
    } else if (v.canPlayType("application/vnd.apple.mpegurl")) {
      v.src = src;
      tryPlay();
    }
    return () => { if (hls) hls.destroy(); };
  }, [src]);
}

function WatchScreen({ video, stopName, onBack }) {
  const vidRef = useRef(null);
  useHlsAutoplay(vidRef, video.src);

  return (
    <div className="screen watch detail" style={{ padding: "36px 40px 28px" }} data-back-on-left>
      <div className="video-frame">
        <video
          ref={vidRef}
          poster={video.poster || undefined}
          playsInline
          controls
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", background: "#000" }}
        />
      </div>
      <div className="video-meta">
        <div className="vm-title">{video.title}</div>
        <div className="vm-sub">{video.channel} · {video.year}</div>
        <div className="vm-src">Source · unchartertrail.org</div>
      </div>
      <div className="detail-foot">
        <button className="btn focusable" data-autofocus data-back onClick={onBack}>
          <Icon2 name="back" size={14} /> Back
        </button>
      </div>
    </div>
  );
}

// ============================================================ VIDEO DRAWER (mobile)
function VideoDrawer({ video, stopName, onClose }) {
  const vidRef = useRef(null);
  useHlsAutoplay(vidRef, video.src);

  return (
    <div className="vd-overlay" onClick={onClose}>
      <div className="vd-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="vd-handle" />
        <div className="video-frame">
          <video
            ref={vidRef}
            poster={video.poster || undefined}
            playsInline
            controls
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", background: "#000" }}
          />
        </div>
        <div className="video-meta">
          <div className="vm-title">{video.title}</div>
          <div className="vm-sub">{video.channel} · {video.year}</div>
        </div>
        <button className="btn vd-close" onClick={onClose}>
          <Icon2 name="back" size={14} /> Close
        </button>
      </div>
    </div>
  );
}

window.DetailScreen   = DetailScreen;
window.NavigateScreen = NavigateScreen;
window.WatchScreen    = WatchScreen;
window.VideoDrawer    = VideoDrawer;
