// Tree roadmap — tree / timeline / grid variants

const NODE_W = 200, NODE_H = 72, GAP_X = 48, GAP_Y = 120;
const SEM_LABELS = ['Học kỳ 1', 'Học kỳ 2', 'Học kỳ 3', 'Học kỳ 4'];

const RoadmapTree = ({ onSelect }) => {
  const cols = 3;
  const rows = 4;
  const W = cols * (NODE_W + GAP_X) + GAP_X;
  const H = rows * GAP_Y + 80;

  const coord = (sem, col) => ({
    x: GAP_X + col * (NODE_W + GAP_X),
    y: 40 + (sem - 1) * GAP_Y,
  });

  // Build edges from prereqs
  const nodeById = Object.fromEntries(CURRICULUM.map(n => [n.id, n]));
  const edges = [];
  CURRICULUM.forEach(n => {
    n.prereq.forEach(p => {
      const a = nodeById[p]; const b = n;
      if (!a) return;
      const ac = coord(a.semester, a.col);
      const bc = coord(b.semester, b.col);
      edges.push({ from: ac, to: bc, done: a.status === 'done' && (b.status === 'done' || b.status === 'active' || b.status === 'available') });
    });
  });

  return (
    <div className="tree-wrap paper-grid" style={{ minHeight: H }}>
      <svg className="tree-svg" width={W} height={H} style={{ minWidth: W }}>
        {/* Semester labels */}
        {SEM_LABELS.map((lbl, i) => (
          <g key={i}>
            <text x={16} y={40 + i * GAP_Y + NODE_H/2 + 4} fontSize="11" fill="var(--muted)" fontFamily="var(--mono)" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>HK{i+1}</text>
            <line x1={50} y1={40 + i * GAP_Y + NODE_H/2} x2={W - 20} y2={40 + i * GAP_Y + NODE_H/2} stroke="var(--line)" strokeDasharray="2 4" opacity="0.6"/>
          </g>
        ))}
        {/* Edges */}
        {edges.map((e, i) => {
          const x1 = e.from.x + NODE_W/2;
          const y1 = e.from.y + NODE_H;
          const x2 = e.to.x + NODE_W/2;
          const y2 = e.to.y;
          const mid = (y1 + y2) / 2;
          const d = `M${x1},${y1} C${x1},${mid} ${x2},${mid} ${x2},${y2}`;
          return <path key={i} d={d} fill="none" stroke={e.done ? 'var(--green)' : 'var(--line-2)'} strokeWidth={e.done ? 2 : 1.5} strokeDasharray={e.done ? '' : '4 4'} opacity={e.done ? 0.9 : 0.7} />;
        })}
        {/* Nodes */}
        {CURRICULUM.map(n => {
          const c = coord(n.semester, n.col);
          return (
            <foreignObject key={n.id} x={c.x} y={c.y} width={NODE_W} height={NODE_H} className="tree-node" onClick={() => onSelect && onSelect(n)}>
              <NodeCard node={n} />
            </foreignObject>
          );
        })}
      </svg>
    </div>
  );
};

const NodeCard = ({ node }) => {
  const statusClass = node.status === 'done' ? 'done' : node.status === 'active' ? 'active' : node.status === 'locked' ? 'locked' : '';
  const badge = node.status === 'done' ? <Icon name="check" size={11} /> : node.status === 'active' ? <Icon name="play" size={11} /> : node.status === 'locked' ? <Icon name="lock" size={11} /> : <Icon name="plus" size={11} />;
  return (
    <div className={`node-card ${statusClass}`} style={{ height: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 6 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{node.code}</span>
            {node.required && <span className="chip chip-accent" style={{ padding: '1px 6px', fontSize: 9.5 }}>Bắt buộc</span>}
            {!node.required && <span className="chip chip-outline" style={{ padding: '1px 6px', fontSize: 9.5 }}>Tự chọn</span>}
          </div>
          <div className="node-title" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{node.title}</div>
          <div className="node-meta">
            <span>{node.credits} TC</span>
            {node.status === 'done' && <span style={{ color: 'var(--green)' }}>• {node.grade}/10</span>}
            {node.status === 'active' && <span style={{ color: 'var(--accent)' }}>• {node.progress}%</span>}
            {node.status === 'available' && <span>• Sẵn sàng</span>}
            {node.status === 'locked' && <span>• Chưa mở</span>}
          </div>
        </div>
        <div style={{ width: 22, height: 22, borderRadius: 999, background: node.status === 'done' ? 'var(--green)' : node.status === 'active' ? 'var(--accent)' : node.status === 'locked' ? 'var(--line-2)' : 'var(--bg-2)', color: node.status === 'done' || node.status === 'active' ? '#fff' : 'var(--muted)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          {badge}
        </div>
      </div>
    </div>
  );
};

// Timeline layout (alternative)
const RoadmapTimeline = ({ onSelect }) => {
  const bySem = {};
  CURRICULUM.forEach(n => { (bySem[n.semester] = bySem[n.semester] || []).push(n); });
  return (
    <div style={{ padding: 24 }}>
      {Object.keys(bySem).map(sem => (
        <div key={sem} style={{ marginBottom: 28 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--ink)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 18, fontStyle: 'italic' }}>{sem}</div>
            <div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 20 }}>Học kỳ {sem}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{bySem[sem].length} môn · {bySem[sem].reduce((s,n) => s + n.credits, 0)} tín chỉ</div>
            </div>
            <div style={{ flex: 1, height: 1, background: 'var(--line)', marginLeft: 8 }}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, paddingLeft: 48 }}>
            {bySem[sem].map(n => (
              <div key={n.id} onClick={() => onSelect && onSelect(n)} style={{ cursor: 'pointer' }}>
                <NodeCard node={n} />
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

// Grid layout
const RoadmapGrid = ({ onSelect }) => (
  <div style={{ padding: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
    {CURRICULUM.map(n => (
      <div key={n.id} onClick={() => onSelect && onSelect(n)} style={{ cursor: 'pointer' }}>
        <div className={`node-card ${n.status === 'done' ? 'done' : n.status === 'active' ? 'active' : n.status === 'locked' ? 'locked' : ''}`} style={{ padding: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>{n.code}</span>
            <span className={`chip ${n.required ? 'chip-accent' : 'chip-outline'}`} style={{ padding: '1px 7px', fontSize: 10 }}>{n.required ? 'Bắt buộc' : 'Tự chọn'}</span>
          </div>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>{n.title}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 10 }}>{n.credits} tín chỉ · HK{n.semester}</div>
          {n.status === 'active' && (
            <div>
              <div className="progress-track"><div className="progress-fill accent" style={{ width: `${n.progress}%` }}/></div>
              <div style={{ fontSize: 11, color: 'var(--accent)', marginTop: 4, fontFamily: 'var(--mono)' }}>{n.progress}% hoàn thành</div>
            </div>
          )}
          {n.status === 'done' && <div style={{ fontSize: 12, color: 'var(--green)', fontWeight: 600 }}>✓ Đã qua · {n.grade}/10</div>}
          {n.status === 'locked' && <div style={{ fontSize: 11, color: 'var(--muted)' }}>Cần hoàn thành môn tiên quyết</div>}
          {n.status === 'available' && <div style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>Có thể đăng ký</div>}
        </div>
      </div>
    ))}
  </div>
);

Object.assign(window, { RoadmapTree, RoadmapTimeline, RoadmapGrid, NodeCard });
