/* ============================================================
   B1 — Bảng trắng (whiteboard overlay)
   Host bật/tắt. Nét CỐ ĐỊNH. Quyền vẽ = quyền nói:
   tới lượt (mic mở) thì vẽ; hết lượt → nét đông thành 1 OVERLAY
   mang tên người đó, host bật/tắt từng lớp như layer.
   Toạ độ chuẩn hoá 0..1 để co giãn theo màn.
   ============================================================ */
const DrawLayer = forwardRef(function DrawLayer({ active, color, overlays, liveStrokes, onChange, zIndex = 3 }, ref) {
  const wrapRef = useRef(null);
  const canvasRef = useRef(null);
  const drawingRef = useRef(false);
  const curRef = useRef(null);
  const liveRef = useRef(liveStrokes);
  liveRef.current = liveStrokes;

  const redraw = useCallback(() => {
    const c = canvasRef.current; if (!c) return;
    const ctx = c.getContext('2d');
    const w = c.clientWidth, h = c.clientHeight;
    ctx.clearRect(0, 0, w, h);
    const paint = (strokes) => strokes.forEach(s => {
      if (!s.points.length) return;
      ctx.strokeStyle = s.color; ctx.lineWidth = s.w || 3.2;
      ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      ctx.shadowColor = 'rgba(0,0,0,.35)'; ctx.shadowBlur = 2;
      ctx.beginPath();
      s.points.forEach((p, i) => { const x = p.x * w, y = p.y * h; i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
      if (s.points.length === 1) { ctx.lineTo(s.points[0].x * w + 0.1, s.points[0].y * h + 0.1); }
      ctx.stroke();
    });
    overlays.filter(o => o.visible).forEach(o => paint(o.strokes));
    paint(liveStrokes);
    if (curRef.current) paint([curRef.current]);
  }, [overlays, liveStrokes]);

  const sizeCanvas = useCallback(() => {
    const c = canvasRef.current, wrap = wrapRef.current;
    if (!c || !wrap) return;
    const r = wrap.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    c.width = Math.round(r.width * dpr); c.height = Math.round(r.height * dpr);
    c.style.width = r.width + 'px'; c.style.height = r.height + 'px';
    c.getContext('2d').setTransform(dpr, 0, 0, dpr, 0, 0);
    redraw();
  }, [redraw]);

  useEffect(() => { sizeCanvas(); window.addEventListener('resize', sizeCanvas); return () => window.removeEventListener('resize', sizeCanvas); }, [sizeCanvas]);
  useEffect(() => { redraw(); }, [redraw]);

  const pt = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: (t.clientX - r.left) / r.width, y: (t.clientY - r.top) / r.height };
  };
  const down = (e) => { if (!active) return; e.preventDefault(); drawingRef.current = true; curRef.current = { color, points: [pt(e)] }; redraw(); };
  const move = (e) => { if (!active || !drawingRef.current) return; e.preventDefault(); curRef.current.points.push(pt(e)); redraw(); };
  const up = () => {
    if (!drawingRef.current) return;
    drawingRef.current = false;
    const s = curRef.current; curRef.current = null;
    if (s && s.points.length) onChange([...liveRef.current, s]);
  };

  useImperativeHandle(ref, () => ({ redraw }), [redraw]);

  return (
    <div ref={wrapRef} style={{ position: 'absolute', inset: 0, zIndex, pointerEvents: active ? 'auto' : 'none', touchAction: active ? 'none' : 'auto' }}>
      <canvas ref={canvasRef}
        onMouseDown={down} onMouseMove={move} onMouseUp={up} onMouseLeave={up}
        onTouchStart={down} onTouchMove={move} onTouchEnd={up}
        style={{ display: 'block', width: '100%', height: '100%' }} />
    </div>
  );
});

/* ---- pen toolbar (hiện khi bảng trắng bật) ---- */
const PEN_COLORS = ['#A8413A', '#B89968', '#EDE5D3', '#5C6E54'];
function PenBar({ pen, setPen, onUndo, onCommit, liveCount }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 9, marginBottom: 11, padding: '9px 11px',
      background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', border: '1px solid var(--gold-dim)', borderRadius: 14,
    }}>
      <span className="b1-mono" style={{ fontSize: 8.5, color: 'var(--gold)', letterSpacing: '.1em', flexShrink: 0 }}>BÚT</span>
      <div style={{ display: 'flex', gap: 7 }}>
        {PEN_COLORS.map(c => (
          <button key={c} onClick={() => setPen(c)} style={{
            width: 22, height: 22, borderRadius: '50%', cursor: 'pointer', background: c, flexShrink: 0,
            border: pen === c ? '2px solid var(--cream)' : '2px solid transparent',
            boxShadow: pen === c ? '0 0 0 1px var(--gold)' : 'inset 0 0 0 1px rgba(0,0,0,.25)',
          }} />
        ))}
      </div>
      <div style={{ flex: 1 }} />
      <button onClick={onUndo} disabled={!liveCount} title="Hoàn tác nét" style={{
        width: 34, height: 34, borderRadius: 10, cursor: liveCount ? 'pointer' : 'not-allowed', flexShrink: 0,
        background: 'transparent', border: '1px solid var(--ink-line)', color: 'var(--cream)', opacity: liveCount ? 1 : .4,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6 4L3 7l3 3M3 7h7a3 3 0 0 1 0 6H7" stroke="var(--cream)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      <button onClick={onCommit} disabled={!liveCount} style={{
        flexShrink: 0, padding: '0 14px', height: 34, borderRadius: 10, cursor: liveCount ? 'pointer' : 'not-allowed',
        border: 'none', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13,
        background: liveCount ? 'var(--gold)' : 'var(--ink-soft)', color: liveCount ? '#15100A' : 'var(--cream-dim)',
      }}>Chốt lớp</button>
    </div>
  );
}

Object.assign(window, { DrawLayer, PenBar, PEN_COLORS });
