// Toolbar mit Werkzeugen + Phrasierungs-Einzeichnungen + Optionen-Popover

const { useState: useStateTb, useRef: useRefTb, useEffect: useEffectTb } = React;

// Phrasierungs-Stempel: werden per Klick auf die Noten gesetzt
const STAMPS = [
  { id: 'stamp-phrase-bow',    label: 'Phrasierungsbogen mit Ziel',  icon: 'phrase-bow' },
  { id: 'stamp-breath',        label: 'Atemzeichen (V)',             icon: 'breath' },
  { id: 'stamp-caesura',       label: 'Zäsur ohne Atem',            icon: 'caesura' },
  { id: 'stamp-accent',        label: 'Stark betonte Silbe',        icon: 'accent' },
  { id: 'stamp-attack-decay',  label: 'Betonter Einsatz + Abschwingen', icon: 'attack-decay' },
  { id: 'stamp-staccato',      label: 'Schwach betonte Silbe',      icon: 'staccato' },
  { id: 'stamp-not-stressed',  label: 'Nicht betonte Silbe',        icon: 'not-stressed' },
  { id: 'stamp-fermata',       label: 'Fermata',                    icon: 'fermata' },
  { id: 'stamp-tenuto',        label: 'Deutlich sprechen',          icon: 'tenuto' },
  { id: 'stamp-separator',     label: 'Trennstrich',                icon: 'separator' },
  { id: 'stamp-tie',           label: 'Verbindungsbogen',           icon: 'tie' },
];

const BEAT_STAMPS = [
  { id: 'stamp-beat-1', label: '1er Schlagbild', icon: 'beat-1' },
  { id: 'stamp-beat-2', label: '2er Schlagbild', icon: 'beat-2' },
  { id: 'stamp-beat-3', label: '3er Schlagbild', icon: 'beat-3' },
  { id: 'stamp-beat-4', label: '4er Schlagbild', icon: 'beat-4' },
];

window.STAMPS = STAMPS;

function Toolbar({ tool, setTool, toolOptions, setToolOptions, onUndo, canUndo, zoom = 1, setZoom }) {
  const [popover, setPopover] = useStateTb(null);
  const ref = useRefTb(null);

  useEffectTb(() => {
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setPopover(null);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const penColors = ['#1c1917', '#dc2626', '#2563eb', '#16a34a', '#7C3AED'];
  const highlightColors = ['#fbbf24', '#fb7185', '#a3e635', '#60a5fa', '#c084fc'];

  const baseTools = [
    { id: 'select', label: 'Auswahl', icon: 'cursor', shortcut: 'V' },
    { id: 'pin', label: 'Pin / Kommentar', icon: 'pin', shortcut: 'C' },
  ];

  const drawTools = [
    { id: 'pen', label: 'Stift', icon: 'pen', shortcut: 'P', hasOptions: true },
    { id: 'highlight', label: 'Highlighter', icon: 'highlight', shortcut: 'H', hasOptions: true },
    { id: 'eraser', label: 'Radiergummi', icon: 'eraser', shortcut: 'E' },
  ];

  const isBeat = tool.startsWith('stamp-beat-');
  const isPhrasingStamp = tool.startsWith('stamp-') && !isBeat;

  const renderToolBtn = (t) => (
    <button
      key={t.id}
      className={`tool-btn ${tool === t.id ? 'active' : ''}`}
      onClick={() => {
        setTool(t.id);
        if (t.hasOptions && tool === t.id) {
          setPopover(popover === t.id ? null : t.id);
        } else if (t.hasOptions) {
          setPopover(t.id);
        } else {
          setPopover(null);
        }
      }}
      title={`${t.label}${t.shortcut ? ` (${t.shortcut})` : ''}`}
    >
      <Icon name={t.icon} size={18} />
    </button>
  );

  return (
    <div className="toolbar" ref={ref}>
      {/* Undo */}
      <button
        className="tool-btn"
        onClick={onUndo}
        disabled={!canUndo}
        title="Rückgängig (Strg+Z)"
        style={!canUndo ? { opacity: 0.3, cursor: 'default' } : {}}
      >
        <Icon name="undo" size={18} />
      </button>

      <div className="tool-divider" />

      {/* Basis-Werkzeuge */}
      {baseTools.map(renderToolBtn)}

      <div className="tool-divider" />

      {/* Zeichen-Werkzeuge */}
      {drawTools.map(renderToolBtn)}

      <div className="tool-divider" />

      {/* Phrasierung-Gruppe mit Aufklapp-Popover */}
      <div style={{ position: 'relative' }}>
        <button
          className={`tool-btn ${isPhrasingStamp ? 'active' : ''}`}
          onClick={() => {
            if (isPhrasingStamp) {
              setPopover(popover === 'stamps' ? null : 'stamps');
            } else {
              setTool(STAMPS[0].id);
              setPopover('stamps');
            }
          }}
          title="Phrasierungs-Einzeichnungen"
          style={{ gap: 3, width: 'auto', padding: '0 8px' }}
        >
          <Icon name={isPhrasingStamp ? STAMPS.find(s => s.id === tool)?.icon || 'phrase-bow' : 'phrase-bow'} size={18} />
          <svg width="8" height="8" viewBox="0 0 8 8" fill="none" stroke="currentColor" strokeWidth="1.5">
            <polyline points="1 3 4 6 7 3" />
          </svg>
        </button>

        {popover === 'stamps' && (
          <div className="tool-popover stamps-popover">
            <div className="popover-label" style={{ width: 'auto', marginBottom: 4 }}>Phrasierung</div>
            <div className="stamps-grid">
              {STAMPS.map(s => (
                <button
                  key={s.id}
                  className={`stamp-pick ${tool === s.id ? 'active' : ''}`}
                  onClick={() => { setTool(s.id); }}
                  title={s.label}
                >
                  <Icon name={s.icon} size={20} />
                  <span className="stamp-pick-label">{s.label.split('/')[0].split('(')[0].trim()}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      <div className="tool-divider" />

      {/* Schlagbilder — direkt in der Toolbar */}
      {BEAT_STAMPS.map(b => (
        <button
          key={b.id}
          className={`tool-btn ${tool === b.id ? 'active' : ''}`}
          onClick={() => { setTool(b.id); setPopover(null); }}
          title={b.label}
        >
          <Icon name={b.icon} size={18} />
        </button>
      ))}

      <div className="tool-divider" />

      {/* Zoom */}
      <button
        className="tool-btn"
        onClick={() => setZoom(z => Math.max(0.3, z - 0.1))}
        title="Verkleinern (Strg+Mausrad)"
        style={zoom <= 0.3 ? { opacity: 0.3, cursor: 'default' } : {}}
        disabled={zoom <= 0.3}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/>
        </svg>
      </button>
      <button
        className="zoom-label"
        onClick={() => setZoom(1)}
        title="Zoom zurücksetzen"
      >
        {Math.round(zoom * 100)}%
      </button>
      <button
        className="tool-btn"
        onClick={() => setZoom(z => Math.min(3, z + 0.1))}
        title="Vergrößern (Strg+Mausrad)"
        style={zoom >= 3 ? { opacity: 0.3, cursor: 'default' } : {}}
        disabled={zoom >= 3}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/>
        </svg>
      </button>

      {/* Popover: Stift-Optionen */}
      {popover === 'pen' && (
        <div className="tool-popover">
          <div className="popover-row">
            <span className="popover-label">Farbe</span>
            <div style={{ display: 'flex', gap: 6 }}>
              {penColors.map(c => (
                <div
                  key={c}
                  className={`color-swatch ${toolOptions.penColor === c ? 'active' : ''}`}
                  style={{ background: c }}
                  onClick={() => setToolOptions({ ...toolOptions, penColor: c })}
                />
              ))}
            </div>
          </div>
          <div className="popover-row">
            <span className="popover-label">Stärke</span>
            <input type="range" className="size-slider" min={1} max={8} step={1}
              value={toolOptions.penSize}
              onChange={e => setToolOptions({ ...toolOptions, penSize: Number(e.target.value) })}
            />
            <span style={{ fontSize: 12, color: 'var(--text-soft)', width: 20, textAlign: 'right' }}>{toolOptions.penSize}</span>
          </div>
        </div>
      )}

      {/* Popover: Highlighter-Optionen */}
      {popover === 'highlight' && (
        <div className="tool-popover">
          <div className="popover-row">
            <span className="popover-label">Farbe</span>
            <div style={{ display: 'flex', gap: 6 }}>
              {highlightColors.map(c => (
                <div
                  key={c}
                  className={`color-swatch ${toolOptions.highlightColor === c ? 'active' : ''}`}
                  style={{ background: c }}
                  onClick={() => setToolOptions({ ...toolOptions, highlightColor: c })}
                />
              ))}
            </div>
          </div>
          <div className="popover-row">
            <span className="popover-label">Stärke</span>
            <input type="range" className="size-slider" min={6} max={28} step={2}
              value={toolOptions.highlightSize}
              onChange={e => setToolOptions({ ...toolOptions, highlightSize: Number(e.target.value) })}
            />
            <span style={{ fontSize: 12, color: 'var(--text-soft)', width: 20, textAlign: 'right' }}>{toolOptions.highlightSize}</span>
          </div>
        </div>
      )}
    </div>
  );
}

window.Toolbar = Toolbar;
