// GPX → GeoJSON converter. Produces a FeatureCollection with one LineString
// per track segment, preserving elevation as the Z coordinate.

window.TOOL_HANDLERS['gpx-to-geojson'] = function GpxToGeoJsonTool() {
  const G = window.MMGpx;
  const S = window.MMSports;
  const [filename, setFilename] = React.useState('');
  const [tracks, setTracks] = React.useState(null);
  const [pretty, setPretty] = React.useState(true);

  const onFile = async (f) => {
    if (!f) return;
    try {
      const text = await f.text();
      const parsed = G.parseGPX(text);
      if (!parsed.length) throw new Error('No tracks found.');
      setTracks(parsed); setFilename(f.name);
    } catch (e) { alert(e.message); }
  };

  const geojson = React.useMemo(() => {
    if (!tracks) return null;
    const features = [];
    for (const t of tracks) {
      for (const seg of t.segments) {
        features.push({
          type: 'Feature',
          properties: { name: t.name },
          geometry: {
            type: 'LineString',
            coordinates: seg.map((p) => Number.isFinite(p.ele) ? [p.lon, p.lat, p.ele] : [p.lon, p.lat]),
          },
        });
      }
    }
    return { type: 'FeatureCollection', features };
  }, [tracks]);

  const text = React.useMemo(() => {
    if (!geojson) return '';
    return pretty ? JSON.stringify(geojson, null, 2) : JSON.stringify(geojson);
  }, [geojson, pretty]);

  const download = () => {
    const blob = new Blob([text], { type: 'application/geo+json' });
    window.downloadBlob(blob, (filename.replace(/\.gpx$/i, '') || 'track') + '.geojson');
  };

  if (!tracks) {
    return (
      <div className="mini-tool sport-tool">
        <S.SportsToolHeader title="GPX to GeoJSON" sub="Convert GPS tracks to GeoJSON for QGIS, Mapbox, geopandas." icon="swap" accent="#2563eb" />
        <window.Dropzone onFile={onFile} title="Drop a .gpx file" hint="output: .geojson FeatureCollection" accept=".gpx" />
      </div>
    );
  }

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="GPX to GeoJSON" sub={filename} icon="swap" accent="#2563eb" />

      <div className="gpx-stats">
        <window.MMGpx.StatTile label="Tracks" value={tracks.length} />
        <window.MMGpx.StatTile label="Segments" value={tracks.reduce((a, t) => a + t.segments.length, 0)} />
        <window.MMGpx.StatTile label="Features" value={geojson.features.length} />
        <window.MMGpx.StatTile label="JSON size" value={window.fmtBytes(new Blob([text]).size)} />
      </div>

      <label className="pw-opt" style={{ marginTop: 12 }}>
        <input type="checkbox" checked={pretty} onChange={(e) => setPretty(e.target.checked)} />
        Pretty-print (2-space indent)
      </label>

      <textarea className="mini-input mini-textarea" style={{ minHeight: 240, fontFamily: 'monospace', fontSize: 12, marginTop: 12 }}
                readOnly value={text.slice(0, 30000) + (text.length > 30000 ? '\n…\n' : '')} />

      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => setTracks(null)}>Another file</button>
        <button className="btn btn-primary" onClick={download}>
          <window.Icon name="download" size={16} /> Download .geojson
        </button>
      </div>
    </div>
  );
};
