"use client";
import { useEffect, useRef, useState } from 'react';
import MidiPlayer from 'midi-player-js';
import Soundfont from 'soundfont-player';

export default function Home() {
  const audioCtx = useRef(new (window.AudioContext || (window as any).webkitAudioContext)());
  const instrument = useRef<any>(null);
  const player = useRef<any>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    Soundfont.instrument(audioCtx.current, 'acoustic_grand_piano').then(inst => {
      instrument.current = inst;
      player.current = new MidiPlayer.Player(event => {
        if (event.name === 'Note on' && event.velocity > 0) instrument.current.play(event.noteName);
        if (event.name === 'Note off' || (event.name === 'Note on' && event.velocity === 0)) instrument.current.stop(event.noteName);
      });
      setLoaded(true);
    });
    return () => audioCtx.current.close();
  }, []);

  const loadMidi = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => player.current.loadArrayBuffer(reader.result);
      reader.readAsArrayBuffer(file);
    }
  };

  return (
    <main style={{padding:"2rem",fontFamily:"sans-serif"}}>
      <h1>MIDI Player Lite</h1>
      {loaded ? <input type="file" accept=".mid,.midi" onChange={loadMidi}/> : "Loading..."}
      <button onClick={() => player.current.play()} disabled={!loaded}>Play</button>
      <button onClick={() => player.current.stop()} disabled={!loaded}>Stop</button>
    </main>
  );
}
