// SourcePanel.jsx — pick a source: demo · upload · mic · play/pause.

function SourcePanel({ state, trackName, onDemo, onPickFile, onMic, onPlayPause }) {
  const fileRef = React.useRef(null);
  const playing = state === 'live' || state === 'listening';
  const canPlay = state === 'listening' || (!!trackName && state !== 'standby' && state !== 'decoding' && state !== 'analysing');
  const [dragOver, setDragOver] = React.useState(false);
  const statusCopy = {
    standby: 'Nothing leaves your browser. Try the demo, upload an audio file, or open the mic.',
    decoding: 'Reading the file locally…',
    analysing: 'Measuring waveform, pulse and loudness locally…',
    ready: 'Measured and ready. Press play to see it move.',
    live: 'Playing locally. The stage is reading the signal now.',
    paused: 'Paused. Press play to resume the local signal.',
    listening: 'Mic is live locally. Stop mic when finished.',
    error: 'Could not read that source. Try another audio file or check microphone permission.',
  };

  const handleDrop = (e) => {
    e.preventDefault(); setDragOver(false);
    const f = e.dataTransfer.files?.[0];
    if (f) onPickFile(f);
  };

  return (
    <div
      className={"mm-panel mm-source " + (dragOver ? "mm-source--over" : "")}
      onDragOver={e => { e.preventDefault(); setDragOver(true); }}
      onDragLeave={e => { e.preventDefault(); setDragOver(false); }}
      onDrop={handleDrop}
    >
      <div className="mm-label">Listen</div>
      <div className="mm-bigline mm-source__name">
        {trackName || 'Drop a track or open the mic'}
      </div>

      <div className="mm-btn-row">
        <button className="mm-btn" onClick={onDemo} aria-label="Play the built-in demo signal">Demo</button>
        <button className="mm-btn mm-btn--alt" onClick={() => fileRef.current?.click()} aria-label="Upload an audio file for local analysis">Upload</button>
        <button className="mm-btn mm-btn--alt" onClick={onMic} aria-label="Use microphone for local live signal">Mic</button>
        <button className="mm-btn" disabled={!canPlay} onClick={onPlayPause} aria-label={state === 'listening' ? 'Stop microphone' : playing ? 'Pause audio' : 'Play audio'}>
          {state === 'listening' ? 'Stop mic' : playing ? 'Pause' : 'Play'}
        </button>
        <input ref={fileRef} type="file" accept="audio/*" style={{ display: 'none' }}
               onChange={e => e.target.files?.[0] && onPickFile(e.target.files[0])} />
      </div>

      <p className="mm-source__note">{statusCopy[state] || statusCopy.standby}</p>
    </div>
  );
}

Object.assign(window, { SourcePanel });
