/* src/components/diagram.jsx — guitar chord diagram (data-driven grid SVG) */
function ChordDiagram({ name, shape, accent }) {
  if (!shape) {
    return (
      <div className="diag diag--missing">
        <div className="diag__name">{name}</div>
        <div className="diag__box diag__box--empty">—</div>
      </div>
    );
  }
  const frets = shape.frets;
  const played = frets.filter(f => f > 0);
  const minF = played.length ? Math.min(...played) : 1;
  const maxF = played.length ? Math.max(...played) : 1;
  const span = 4;
  const baseFret = maxF <= span ? 1 : minF; // shift window if high up the neck
  const W = 56, H = 70;
  const padX = 8, padTop = 16, padBot = 8;
  const gridW = W - padX * 2;
  const gridH = H - padTop - padBot;
  const strings = 6;
  const colGap = gridW / (strings - 1);
  const rowGap = gridH / span;
  const ink = '#1c1c22';

  return (
    <div className="diag">
      <div className="diag__name" style={{ color: accent }}>{name}</div>
      <svg viewBox={`0 0 ${W} ${H}`} className="diag__box" width={W} height={H}>
        {/* nut or base-fret marker */}
        {baseFret === 1
          ? <rect x={padX} y={padTop - 3} width={gridW} height={3} fill={ink} />
          : <text x={padX - 4} y={padTop + rowGap * 0.7} fontSize="7" textAnchor="end" fill={ink}>{baseFret}fr</text>}
        {/* vertical strings */}
        {Array.from({ length: strings }).map((_, s) => (
          <line key={'v' + s} x1={padX + s * colGap} y1={padTop} x2={padX + s * colGap} y2={padTop + gridH} stroke={ink} strokeWidth="0.6" />
        ))}
        {/* horizontal frets */}
        {Array.from({ length: span + 1 }).map((_, f) => (
          <line key={'h' + f} x1={padX} y1={padTop + f * rowGap} x2={padX + gridW} y2={padTop + f * rowGap} stroke={ink} strokeWidth="0.6" />
        ))}
        {/* barre */}
        {shape.barre && shape.barre.fret >= baseFret && (
          <rect
            x={padX + shape.barre.from * colGap - 2.5}
            y={padTop + (shape.barre.fret - baseFret) * rowGap + rowGap / 2 - 2.5}
            width={(shape.barre.to - shape.barre.from) * colGap + 5}
            height="5" rx="2.5" fill={accent || ink} />
        )}
        {/* open / muted markers + dots */}
        {frets.map((f, s) => {
          const x = padX + s * colGap;
          if (f === -1) return <text key={'m' + s} x={x} y={padTop - 6} fontSize="7" textAnchor="middle" fill={ink}>×</text>;
          if (f === 0) return <circle key={'o' + s} cx={x} cy={padTop - 8} r="2.6" fill="none" stroke={ink} strokeWidth="0.8" />;
          const isBarreNote = shape.barre && shape.barre.fret === f && s >= shape.barre.from && s <= shape.barre.to;
          if (isBarreNote) return null;
          const cy = padTop + (f - baseFret) * rowGap + rowGap / 2;
          return <circle key={'d' + s} cx={x} cy={cy} r="3.4" fill={accent || ink} />;
        })}
      </svg>
    </div>
  );
}
window.ChordDiagram = ChordDiagram;
