/* ============================================================
   ROOY · 06 课程
   ───────────────────────────────────────────────────────────
   需求：关卡式学习路径。主干一条 + 少量分支。给用户的感受是
   "这棵树是 ROOY 给我画的学习地图"。

   结构：NavBar + Segmented (复盘/课程/成就) → 路径卡 horizontal
   swipe (5 条 path) → 当前选中 path 的 node tree 纵向展开 → 节点
   点击进入该阶段详情（06b course-detail），locked 节点不可点；
   current 节点「试一试」→ 04 ROOY 对话。

   path 4 态：
     done    → ink-filled rail + check
     current → ROOY 绿左边 + "ROOY 推荐" badge + 当前节点
     next    → muted outline + "下一个"
     locked  → dashed faded

   accent budget：ROOY 绿（current path 标识 + 推荐 pill）+ gold
   （下一步动作建议）。
   ============================================================ */

function CourseScreen({ onNav }) {
  const [tab, setTab] = React.useState('course');
  const [active, setActive] = React.useState(1); // index of carving (current)
  const scrollerRef = React.useRef(null);

  const paths = [
    { id: 'parallel', name: '平行式',    st: 'done',    nodes: 3, doneCount: 3, desc: '基础站位与平行下滑' },
    { id: 'carving',  name: '刃滑路径',  st: 'current', nodes: 5, doneCount: 2, desc: '把立刃从想着做变成本能', currentNode: '立刃 · 40°' },
    { id: 'short',    name: '短弯节奏',  st: 'next',    nodes: 4, doneCount: 0, desc: '高频小幅转弯' },
    { id: 'mogul',    name: '雪沟地形',  st: 'locked',  nodes: 6, doneCount: 0, desc: '不规则地形适应' },
    { id: 'powder',   name: '粉雪适应',  st: 'locked',  nodes: 4, doneCount: 0, desc: '在松软雪面上的浮感' },
  ];

  const treesByPath = {
    parallel: [
      { st: 'done', name: '平地站位',    desc: '建立中立站位与触感', boosts: ['平衡'] },
      { st: 'done', name: '平行下滑',    desc: '直线下滑保持平行',   boosts: ['平衡', '压力'] },
      { st: 'done', name: '左右弯转换', desc: '把平行的感觉串起来', boosts: ['节奏'] },
    ],
    carving: [
      { st: 'done',    name: '平行式',     desc: '基础站位与平行下滑', boosts: ['平衡', '压力'] },
      { st: 'done',    name: '转弯衔接',   desc: '左右弯之间的过渡',    boosts: ['节奏', '协调'] },
      { st: 'current', name: '立刃 · 40°', desc: '把刃角变成本能',     boosts: ['立刃', '压力'],
        tasks: [
          { l: '转换时轻跳一下', done: true },
          { l: '右弯入弯踩脚趾', done: false, hi: true },
          { l: '完整连接 5 趟',  done: false },
        ],
      },
      { st: 'next',    name: '短弯节奏',   desc: '高频小幅转弯',       boosts: ['节奏', '旋转'] },
      { st: 'locked',  name: '雪沟地形',   desc: '不规则地形适应',     boosts: ['平衡', '协调'] },
    ],
    short: [
      { st: 'current', name: '上半身预转',   desc: '上体领转的基础动作',   boosts: ['旋转'] },
      { st: 'next',    name: '高频短弯',     desc: '把节奏压到 1.2s 内',   boosts: ['节奏', '旋转'] },
      { st: 'locked',  name: '原地短弯',     desc: '小坡度高密度练习',     boosts: ['节奏'] },
      { st: 'locked',  name: '随心切换',     desc: '长短弯自由切换',       boosts: ['节奏', '协调'] },
    ],
    mogul: [
      { st: 'locked', name: '雪沟入门',   desc: '在雪沟里站稳',   boosts: ['平衡'] },
      { st: 'locked', name: '雪沟节奏',   desc: '随雪沟起伏',     boosts: ['节奏', '协调'] },
      { st: 'locked', name: '吸吐控制',   desc: '主动吸收冲击',   boosts: ['压力'] },
      { st: 'locked', name: '雪沟刃滑',   desc: '不规则地形划弧', boosts: ['立刃', '协调'] },
      { st: 'locked', name: '全雪道穿越', desc: '在杂乱地形稳定', boosts: ['协调'] },
      { st: 'locked', name: '随心而行',   desc: '不再思考雪沟',   boosts: ['协调'] },
    ],
    powder: [
      { st: 'locked', name: '粉雪站位',   desc: '更靠后的重心',   boosts: ['平衡'] },
      { st: 'locked', name: '浮起来',     desc: '保持板尖朝上',   boosts: ['压力'] },
      { st: 'locked', name: '粉雪转弯',   desc: '在浮感里转动',   boosts: ['旋转', '压力'] },
      { st: 'locked', name: '深粉适应',   desc: '过膝雪深里行进', boosts: ['平衡', '协调'] },
    ],
  };

  const activePath = paths[active];
  const tree = treesByPath[activePath.id] || [];

  const onScroll = () => {
    const sc = scrollerRef.current;
    if (!sc) return;
    const cards = sc.querySelectorAll('[data-path-card]');
    if (!cards.length) return;
    const center = sc.scrollLeft + sc.clientWidth / 2;
    let best = 0, bestDist = Infinity;
    cards.forEach((c, i) => {
      const cardCenter = c.offsetLeft + c.offsetWidth / 2;
      const d = Math.abs(cardCenter - center);
      if (d < bestDist) { bestDist = d; best = i; }
    });
    if (best !== active) setActive(best);
  };

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

      <NavBar onBack={() => onNav && onNav('home')} title="滑雪学院"/>

      <div style={{ padding: '0 16px 6px', position: 'relative', zIndex: 1 }}>
        <Segmented value={tab} items={ACADEMY_TABS} onChange={(v) => {
          setTab(v);
          if (v === 'review') onNav && onNav('review');
          if (v === 'medals') onNav && onNav('achievement');
        }}/>
      </div>

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

        {/* ── Horizontal path pager — full-width, no card, snap-center ── */}
        <div
          ref={scrollerRef}
          onScroll={onScroll}
          style={{
            marginTop: 16,
            display: 'flex', overflowX: 'auto',
            scrollSnapType: 'x mandatory',
          }}>
          {paths.map((p, i) => (
            <div key={p.id} data-path-card style={{
              flexShrink: 0, width: '100%',
              scrollSnapAlign: 'center',
              padding: '4px 28px',
            }}>
              <PathRow p={p} active={i === active} onTap={() => setActive(i)}/>
            </div>
          ))}
        </div>

        {/* ── pager removed entirely (the strip-with-count read too tech)
            Path switching is the swipe gesture; the active path's
            title appears in the row above as its own anchor. */}
        <div style={{ height: 12 }}/>

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

        {/* ── Node tree ── */}
        <div style={{ padding: '0 22px', position: 'relative' }}>
          {tree.map((n, i) => (
            <PathNode
              key={`${activePath.id}-${i}`}
              node={n}
              isLast={i === tree.length - 1}
              onOpen={n.st === 'locked' ? undefined : () => onNav && onNav('course-detail')}
              onTry={() => onNav && onNav('rooy')}
            />
          ))}
        </div>

      </div>
    </div>
  );
}

/* PathRow — flat on paper, state-differentiated。
   ⚠ Do not add a left-edge ROOY green accent bar —— that's the
   tropey ai-slop "accent stripe" pattern. State 由 badge fill +
   正在练/下一步 pill + progress-strip 颜色承担。 */
function PathRow({ p, active, onTap }) {
  const isLocked = p.st === 'locked';
  const isCurrent = p.st === 'current';
  const isDone = p.st === 'done';
  const isNext = p.st === 'next';

  return (
    <div onClick={onTap} style={{
      paddingTop: 14, paddingBottom: 14, paddingRight: 6,
      opacity: isLocked ? 0.55 : 1,
      cursor: 'pointer',
      transition: 'opacity .2s',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{
              ...T.h1, color: isLocked ? R.ink3 : R.ink,
              letterSpacing: '-0.015em',
            }}>{p.name}</span>
            {isCurrent && <StatusBadge tone="rooy">正在练</StatusBadge>}
            {isNext && <StatusBadge>下一步</StatusBadge>}
          </div>
          <p style={{ ...T.body, color: R.ink3, marginTop: 6 }}>
            {isCurrent && p.currentNode
              ? <>当前 · <span style={{ color: R.ink, fontWeight: 600 }}>{p.currentNode}</span></>
              : p.desc}
          </p>
        </div>

        <span style={{
          ...N.reg, ...T.footnote,
          color: isDone ? R.ink : isLocked ? R.ink4 : R.ink3,
          fontWeight: 600, flexShrink: 0,
          alignSelf: 'flex-start', paddingTop: 6,
        }}>
          {p.doneCount} / {p.nodes}
        </span>
      </div>

      <div style={{ marginTop: 14 }}>
        <ProgressStrip p={p}/>
      </div>
    </div>
  );
}

function ProgressStrip({ p }) {
  if (p.st === 'locked') {
    // no bars, just a faint hairline to suggest structure
    return (
      <div style={{ marginTop: 16, height: 2, borderTop: `1px dashed ${R.hair2}` }}/>
    );
  }
  return (
    <div style={{ marginTop: 14, display: 'flex', gap: 5 }}>
      {Array.from({ length: p.nodes }).map((_, i) => {
        const done = i < p.doneCount;
        const cur = i === p.doneCount && p.st === 'current';
        let bg = R.hair;
        let h = 4;
        if (done) bg = R.ink;
        if (cur) { bg = R.rooy; h = 6; }
        return (
          <div key={i} style={{
            flex: 1, height: h, borderRadius: h / 2,
            background: bg,
            alignSelf: 'center',
            transition: 'all .2s',
          }}/>
        );
      })}
    </div>
  );
}

/* ── Path node ─────────────────────────────────────────── */
function PathNode({ node, isLast, onOpen, onTry }) {
  const meta = {
    done:    { color: R.ink,  ring: R.ink,  fill: R.ink,  label: '已掌握',    faded: false },
    current: { color: R.rooy, ring: R.rooy, fill: R.rooy, label: 'ROOY 推荐', faded: false },
    next:    { color: R.ink2, ring: R.ink2, fill: 'transparent', label: '下一步', faded: false },
    locked:  { color: R.ink3, ring: R.hair2, fill: 'transparent', label: '未解锁', faded: true },
  }[node.st];

  return (
    <div style={{ display: 'flex', gap: 16, position: 'relative', opacity: meta.faded ? 0.5 : 1 }}>
      <div style={{ width: 30, flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
        <div style={{
          width: 30, height: 30, borderRadius: '50%', border: `2px solid ${meta.ring}`,
          background: meta.fill, display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 1, marginTop: 2,
        }}>
          {node.st === 'done' && (
            <svg width="13" height="10" viewBox="0 0 13 10"><path d="M1 5l4 4 7-8" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          )}
          {node.st === 'current' && (
            <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#fff' }}/>
          )}
          {node.st === 'locked' && (
            <svg width="11" height="11" viewBox="0 0 11 11"><rect x="2" y="5" width="7" height="5" rx="0.7" stroke={R.ink3} strokeWidth="1.3" fill="none"/><path d="M3.5 5V3.4a2 2 0 014 0V5" stroke={R.ink3} strokeWidth="1.3" fill="none"/></svg>
          )}
        </div>

        {!isLast && (
          <div style={{
            position: 'absolute', top: 32, bottom: -6, left: '50%', transform: 'translateX(-50%)',
            width: 2, background: node.st === 'done' ? R.ink : R.hair2,
            borderRadius: 2,
          }}/>
        )}
      </div>

      <div
        onClick={onOpen}
        style={{ flex: 1, paddingBottom: 24, cursor: onOpen ? 'pointer' : 'default' }}
      >
        <div style={{
          padding: node.st === 'current' ? '16px 16px 16px' : '6px 0',
          background: node.st === 'current' ? R.card : 'transparent',
          borderRadius: B.card,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <span style={{ ...T.eyebrow, color: meta.color }}>{meta.label}</span>
            {node.st === 'current' && <StatusBadge tone="rooy">进行中</StatusBadge>}
          </div>

          <p style={{ ...T.h2, color: R.ink }}>{node.name}</p>
          <p style={{ ...T.footnote, color: R.ink3, marginTop: 4 }}>{node.desc}</p>

          {node.boosts && (
            <div style={{ marginTop: 10 }}>
              <StatusBadge size="md">+ {node.boosts.join(' · ')}</StatusBadge>
            </div>
          )}

          {node.st === 'current' && node.tasks && (
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: `0.5px solid ${R.hair}` }}>
              <p style={{ ...T.eyebrow, color: R.ink3, marginBottom: 10 }}>任务 · {node.tasks.length} 项</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {node.tasks.map((tk, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                    <span style={{
                      width: 18, height: 18, borderRadius: '50%',
                      border: tk.done ? 'none' : `1.5px solid ${tk.hi ? R.rooy : R.hair2}`,
                      background: tk.done ? R.ink : (tk.hi ? '#fff' : 'transparent'),
                      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                    }}>
                      {tk.done && <svg width="10" height="8" viewBox="0 0 10 8"><path d="M1 4l2.5 2.5 5-5" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                      {tk.hi && !tk.done && <span style={{ width: 6, height: 6, borderRadius: '50%', background: R.rooy }}/>}
                    </span>
                    <span style={{
                      ...T.body, color: tk.done ? R.ink3 : R.ink,
                      textDecoration: tk.done ? 'line-through' : 'none',
                      flex: 1,
                    }}>{tk.l}</span>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                <InlineCTA onClick={(e) => { e.stopPropagation(); onTry && onTry(); }}>试一试</InlineCTA>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CourseScreen });
