// GPX Viewer — drop a .gpx file, see a privacy-first SVG map, elevation profile
// and stats. Nothing leaves the browser.

window.TOOL_HANDLERS['gpx-viewer'] = function GpxViewerTool() {
  const G = window.MMGpx;
  const S = window.MMSports;
  const [filename, setFilename] = React.useState('');
  const [tracks, setTracks] = React.useState(null);
  const [error, setError] = React.useState('');

  const onFile = async (file) => {
    if (!file) return;
    setError('');
    try {
      const text = await file.text();
      const parsed = G.parseGPX(text);
      if (!parsed.length) throw new Error('No tracks or routes found in this GPX file.');
      setTracks(parsed);
      setFilename(file.name);
      window.mmTrackComplete?.('gpx-viewer', { success: true });
    } catch (e) {
      setError(e.message || String(e));
      setTracks(null);
    }
  };

  const points = React.useMemo(() => tracks ? G.flattenPoints(tracks) : [], [tracks]);
  const stats = React.useMemo(() => G.computeStats(points), [points]);
  const distKm = stats.distanceM / 1000;
  const pace = stats.durationS && distKm ? stats.durationS / distKm : 0;

  if (error && !tracks) {
    return (
      <div className="mini-tool sport-tool">
        <S.SportsToolHeader title="GPX Viewer" sub="Drop your run, ride or hike — see the route and elevation." icon="map" accent="#16a34a" />
        <window.ToolError error={error} onRetry={() => setError('')} />
        <window.Dropzone onFile={onFile} title="Drop a .gpx file" hint=".gpx export from Strava, Garmin, Komoot, etc." accept=".gpx,application/gpx+xml,application/xml" />
      </div>
    );
  }

  if (!tracks) {
    return (
      <div className="mini-tool sport-tool">
        <S.SportsToolHeader title="GPX Viewer" sub="Drop your run, ride or hike — see the route and elevation." icon="map" accent="#16a34a" />
        <window.Dropzone onFile={onFile} title="Drop a .gpx file" hint=".gpx export from Strava, Garmin, Komoot, etc." accept=".gpx,application/gpx+xml,application/xml" />
        <div className="sport-helper" style={{ marginTop: 16 }}>
          Files are parsed entirely in your browser — your route never leaves this device.
        </div>
      </div>
    );
  }

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="GPX Viewer" sub={filename} icon="map" accent="#16a34a" />

      <G.GpxMap points={points} height={320} title={tracks[0]?.name || 'Track'} />

      <div className="gpx-stats">
        <G.StatTile label="Distance"  value={`${distKm.toFixed(2)} km`} sub={`${(distKm * 0.621371).toFixed(2)} mi`} />
        {stats.durationS > 0 && <G.StatTile label="Duration" value={S.formatHMS(stats.durationS, { alwaysHours: true })} />}
        {pace > 0 && <G.StatTile label="Avg pace" value={`${S.formatPace(pace)} /km`} sub={`${S.formatPace(S.paceKmToMile(pace))} /mi`} />}
        <G.StatTile label="Elev gain" value={`${stats.gainM.toFixed(0)} m`} sub={`Loss ${stats.lossM.toFixed(0)} m`} />
        {stats.minEle != null && <G.StatTile label="Elevation" value={`${stats.minEle.toFixed(0)}–${stats.maxEle.toFixed(0)} m`} />}
        <G.StatTile label="Points" value={stats.pointCount.toLocaleString()} />
      </div>

      <G.ElevationChart points={points} height={180} title="Elevation profile" />

      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setTracks(null); setFilename(''); }}>
          <window.Icon name="upload" size={16} /> Load another
        </button>
      </div>
    </div>
  );
};
