/* ============================================================
   ROOY · 06b 阶段详情（CourseDetailScreenB）
   ───────────────────────────────────────────────────────────
   需求：从 06 课程的节点点进来的单个阶段详情。示例 = carving
   路径 current 节点「立刃 · 40°」（进行中）。

   结构：NavBar → 阶段头部（进行中 + boosts 并排 / 描述）→
   「阶段详情」（intro + 3 要点白卡 InsetGroup，编号中性 ink）→
   「练习视频」（featured hero 海报 + 紧凑列表白卡）→ ROOY 提示
   + 试一试（InlineCTA，随内容滚动）。点 featured / 列表行 →
   应用内全屏播放器（zIndex fullscreen）。

   accent budget：ROOY 绿单一主导（进行中 badge + featured
   「先看这个」pill + RooyLine dot）。无 gold / data。

   跨屏：prototype 路由 'course-detail'（home tab push）。由 06
   course.jsx 的 PathNode 点击进入；试一试 → 'rooy'。

   非显然决定：3 条练习要点是真·3 项相关列表 → 用 InsetGroup
   白卡（符合「3+ 相关项才用白卡」）。featured 海报走 rooy 偏色
   暗渐变（推荐那条带品牌色），列表行缩略走中性 ink 暗渐变。
   ============================================================ */

function CourseDetailScreenB({ onNav }) {
  /* active: null | video —— 当前全屏播放的视频。null = 不在全屏。 */
  const [active, setActive] = React.useState(null);

  const stage = {
    name: '立刃 · 40°',
    path: '刃滑路径 · 第 3 关',
    desc: '把刃角从"想着做"变成本能 —— 入弯就吃住雪，靠身体记住 40° 的体感。',
    boosts: ['立刃', '压力'],
    taskDone: 1,
    taskTotal: 3,
    points: [
      '入弯前先把重心压到外脚，让板刃自然咬住雪面',
      '膝盖随弯倾向山下，上半身保持朝向前进方向',
      '出弯不急着收，让刃走完整条弧线再换刃',
    ],
  };

  const videos = [
    { id: 'v1', t: '立刃的体感是什么', sub: '入门 · 概念', dur: '2:48' },
    { id: 'v2', t: '40° 刃角分解动作', sub: '核心 · 分解', dur: '4:12' },
    { id: 'v3', t: '常见错误：内倾过度', sub: '纠错 · 对比', dur: '3:05' },
    { id: 'v4', t: '完整连接 5 趟示范', sub: '进阶 · 实战', dur: '5:30' },
  ];

  /* featured = v2：RooyLine 点名"先看「40° 刃角分解动作」"，给推荐
     那条一个独立的 hero 落点。 */
  const featured = videos[1];
  const rest = videos.filter(v => v.id !== featured.id);

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background: R.bg, position: 'relative', color: R.ink, ...T.subhead,
    }}>
      <StatusBar/>

      <NavBar
        onBack={() => onNav && onNav('back')}
        kicker={stage.path}
        title={stage.name}
      />

      <div style={{ flex: 1, overflowY: 'auto', position: 'relative', zIndex: 1, paddingBottom: 40 }}>

        {/* ── 阶段头部 ── */}
        <div style={{ padding: '10px 20px 4px' }}>
          {/* 状态 + boosts 并排：进行中 在前 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
            <StatusBadge tone="rooy">进行中</StatusBadge>
            <StatusBadge size="md">+ {stage.boosts.join(' · ')}</StatusBadge>
          </div>
          <p style={{ ...T.para, color: R.ink2 }}>{stage.desc}</p>
        </div>

        <div style={{ height: 28 }}/>

        {/* ── 阶段详情 ── */}
        <SectionTitle>阶段详情</SectionTitle>
        <div style={{ padding: '12px 20px 0' }}>
          <p style={{ ...T.para, color: R.ink2 }}>
            这一关把前两关学会的转弯衔接收进刃滑。目标不是更快，而是让板刃在每个弯里
            都吃住雪 —— 当 40° 的刃角变成不用想的本能，你的弧线会自己变干净。
          </p>
        </div>

        {/* 3 条要点 = 真·3 项相关列表 → InsetGroup 白卡 */}
        <div style={{ margin: '16px 16px 0' }}>
          <InsetGroup>
            {stage.points.map((p, i) => (
              <div key={i} style={{ padding: '14px 16px', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <span style={{
                  ...N.reg, ...T.footnote, fontWeight: 600, color: R.ink3,
                  flexShrink: 0, paddingTop: 3, width: 14,
                }}>{i + 1}</span>
                <p style={{ ...T.body, color: R.ink, flex: 1 }}>{p}</p>
              </div>
            ))}
          </InsetGroup>
        </div>

        <div style={{ height: 30 }}/>

        {/* ── 练习视频：featured + 紧凑列表 ── */}
        <SectionTitle meta={`共 ${videos.length} 个`}>练习视频</SectionTitle>
        <div style={{ padding: '14px 16px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <FeaturedVideo v={featured} onOpen={() => setActive(featured)}/>

          <InsetGroup>
            {rest.map(v => (
              <CompactVideoRow key={v.id} v={v} onOpen={() => setActive(v)}/>
            ))}
          </InsetGroup>
        </div>

        <div style={{ height: 26 }}/>

        {/* ROOY 提示 + 试一试（InlineCTA，随内容滚动） */}
        <div style={{ padding: '0 20px' }}>
          <RooyLine
            text="先看「40° 刃角分解动作」，再去雪道上找一条缓坡专门练入弯吃雪。"
            em="别贪快。"
          />
          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
            <InlineCTA onClick={() => onNav && onNav('rooy')}>试一试</InlineCTA>
          </div>
        </div>

      </div>

      {active && (
        <VideoPlayer video={active} onClose={() => setActive(null)}/>
      )}
    </div>
  );
}

/* ── FeaturedVideo — ROOY 推荐那条的 hero 海报卡 ──────────────
   rooy 偏色暗渐变 + "先看这个" pill + 大播放键 + 时长角标。
   副标题不放时长（角标已承担），每条时长只出现一次。 */
function FeaturedVideo({ v, onOpen }) {
  const [pressed, setPressed] = React.useState(false);
  return (
    <div
      onClick={onOpen}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      style={{ cursor: 'pointer', transform: pressed ? 'scale(0.99)' : 'none', transition: 'transform 0.15s ease' }}
    >
      <Poster tone="rooy" dur={v.dur} height={196} playSize={56} style={{ boxShadow: Shadow.card }}>
        <span style={{
          position: 'absolute', top: 12, left: 12,
          background: R.rooy, color: '#fff',
          ...T.caption1, fontWeight: 600,
          padding: '4px 10px', borderRadius: B.pill,
          display: 'inline-flex', alignItems: 'center', gap: 5,
          boxShadow: Shadow.thumb,
        }}>
          <svg width="6" height="7" viewBox="0 0 6 7"><path d="M0 0l6 3.5L0 7Z" fill="#fff"/></svg>
          先看这个
        </span>
      </Poster>
      <div style={{ padding: '12px 4px 0' }}>
        <p style={{ ...T.headline, color: R.ink }}>{v.t}</p>
        <p style={{ ...T.footnote, color: R.ink3, marginTop: 3 }}>{v.sub}</p>
      </div>
    </div>
  );
}

/* CompactVideoRow — 列表行：小缩略 + 标题/副标题 + chevron。
   时长进副标题（缩略图无角标），每条时长只出现一次。 */
function CompactVideoRow({ v, onOpen }) {
  return (
    <div onClick={onOpen} style={{
      padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'pointer', minHeight: 52,
    }}>
      <div style={{ width: 52, height: 52, flexShrink: 0 }}>
        <Poster tone="ink" playSize={22} radius={10} height={52}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <p style={{ ...T.body, color: R.ink }}>{v.t}</p>
        <p style={{ ...T.caption1, color: R.ink3, marginTop: 2 }}>{v.sub} · {v.dur}</p>
      </div>
      <Chevron/>
    </div>
  );
}

/* Poster — 深色渐变 + 等高线 + 居中播放键；dur 给则右下时长角标；
   children 浮在海报上（featured 的"先看这个"pill）。fill=true 用于
   全屏铺底（inset 0、无圆角）。tone 只 rooy(品牌偏色) / ink(中性)。 */
function Poster({ tone = 'ink', dur, height, fill = false, playSize = 56, playing = false, radius = B.cardL, children, style }) {
  const grad = tone === 'rooy'
    ? 'linear-gradient(135deg, #0b3b44 0%, #0E1116 78%)'
    : 'linear-gradient(135deg, #2a2e36 0%, #0E1116 82%)';

  return (
    <div style={{
      position: fill ? 'absolute' : 'relative',
      inset: fill ? 0 : undefined,
      width: fill ? undefined : '100%',
      height: fill ? undefined : height,
      borderRadius: fill ? 0 : radius, overflow: 'hidden',
      background: grad,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      ...style,
    }}>
      <TopoLines y1={height ? height * 0.42 : 320} y2={height ? height * 0.7 : 520} viewBoxW={360} viewBoxH={height || 800}/>
      <PlayGlyph size={playSize} playing={playing}/>
      {children}
      {dur && (
        <span style={{
          position: 'absolute', right: 10, bottom: 10,
          ...T.caption1, ...N.reg, color: '#fff', fontWeight: 600,
          background: 'rgba(0,0,0,0.55)', padding: '2px 8px',
          borderRadius: B.pill, backdropFilter: 'blur(4px)',
        }}>{dur}</span>
      )}
    </div>
  );
}

/* PlayGlyph — 半透明圆底 + 白色三角。playing=true 画暂停双竖条。 */
function PlayGlyph({ size = 56, playing = false }) {
  const tri = size * 0.34;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: 'rgba(255,255,255,0.16)',
      border: '1.5px solid rgba(255,255,255,0.5)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      {playing ? (
        <div style={{ display: 'flex', gap: size * 0.1 }}>
          <span style={{ width: size * 0.1, height: size * 0.32, background: '#fff', borderRadius: 1 }}/>
          <span style={{ width: size * 0.1, height: size * 0.32, background: '#fff', borderRadius: 1 }}/>
        </div>
      ) : (
        <svg width={tri} height={tri} viewBox="0 0 10 12" style={{ marginLeft: size * 0.04 }}>
          <path d="M0 0 L10 6 L0 12 Z" fill="#fff"/>
        </svg>
      )}
    </div>
  );
}

/* ── VideoPlayer — 应用内全屏覆盖层（zIndex fullscreen）─────────
   点中央切换播放/暂停，playing 时假进度条推进；✕ 关闭。 */
function VideoPlayer({ video, onClose }) {
  const [playing, setPlaying] = React.useState(true);
  const [progress, setProgress] = React.useState(0);

  const total = React.useMemo(() => {
    const [m, s] = video.dur.split(':').map(Number);
    return m * 60 + s;
  }, [video.dur]);

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProgress(p => {
        const next = p + 1 / (total * 2); // 2 ticks/sec → 双速演示
        if (next >= 1) { return 0; }
        return next;
      });
    }, 500);
    return () => clearInterval(id);
  }, [playing, total]);

  const cur = Math.round(progress * total);
  const fmt = (sec) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: Z.fullscreen,
      background: '#000',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* 视频帧铺底 + 中央播放/暂停命中区 */}
      <div onClick={() => setPlaying(p => !p)} style={{ position: 'absolute', inset: 0, cursor: 'pointer' }}>
        <Poster tone="ink" fill playSize={78} playing={playing}/>
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'linear-gradient(180deg, rgba(0,0,0,0.5) 0%, transparent 22%, transparent 70%, rgba(0,0,0,0.65) 100%)',
        }}/>
      </div>

      {/* 顶部条：✕ + 标题 */}
      <div style={{
        position: 'relative', zIndex: 1,
        padding: '54px 16px 0', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onClose} style={{
          background: 'rgba(255,255,255,0.16)', border: 'none', cursor: 'pointer',
          width: 36, height: 36, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, backdropFilter: 'blur(6px)',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14">
            <path d="M1 1l12 12M13 1L1 13" stroke="#fff" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        </button>
        <div style={{ minWidth: 0 }}>
          <p style={{ ...T.headline, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{video.t}</p>
          <p style={{ ...T.caption1, color: 'rgba(255,255,255,0.65)', marginTop: 1 }}>{video.sub}</p>
        </div>
      </div>

      <div style={{ flex: 1 }}/>

      {/* 底部：进度条 + 时间 */}
      <div style={{
        position: 'relative', zIndex: 1,
        padding: '0 18px',
        paddingBottom: 'max(env(safe-area-inset-bottom, 0px), 30px)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ ...T.caption1, ...N.reg, color: 'rgba(255,255,255,0.85)', width: 38 }}>{fmt(cur)}</span>
          <div style={{ flex: 1, height: 3, borderRadius: 3, background: 'rgba(255,255,255,0.25)', overflow: 'hidden' }}>
            <div style={{ width: `${progress * 100}%`, height: '100%', background: '#fff', transition: 'width .4s linear' }}/>
          </div>
          <span style={{ ...T.caption1, ...N.reg, color: 'rgba(255,255,255,0.55)', width: 38, textAlign: 'right' }}>{fmt(total)}</span>
        </div>
        <p style={{ ...T.caption1, color: 'rgba(255,255,255,0.45)', textAlign: 'center', marginTop: 14 }}>
          {playing ? '点击画面暂停' : '点击画面播放'}
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { CourseDetailScreenB });
