// GPX Trimmer — clip the start/end of a track to hide your home address before
// publishing a route. Pure-distance trimming so you can choose, e.g., 200 m from
// each end.

window.TOOL_HANDLERS['gpx-trimmer'] = function GpxTrimmerTool() {
  const G = window.MMGpx;
  const S = window.MMSports;
  const [filename, setFilename] = React.useState('');
  const [tracks, setTracks] = React.useState(null);
  const [trimStart, setTrimStart] = React.useState(200);
  const [trimEnd, setTrimEnd] = React.useState(200);

  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 in this file.');
      setTracks(parsed); setFilename(f.name);
    } catch (e) { alert(e.message); }
  };

  // Build a single point list with cumulative distance.
  const enriched = React.useMemo(() => {
    if (!tracks) return null;
    const pts = G.flattenPoints(tracks);
    const cum = [0];
    for (let i = 1; i < pts.length; i++) {
      cum.push(cum[i - 1] + G.haversine(pts[i - 1].lat, pts[i - 1].lon, pts[i].lat, pts[i].lon));
    }
    return { pts, cum, total: cum[cum.length - 1] || 0 };
  }, [tracks]);

  const trimmedPoints = React.useMemo(() => {
    if (!enriched) return [];
    const { pts, cum, total } = enriched;
    const lo = trimStart;
    const hi = total - trimEnd;
    if (hi <= lo) return [];
    return pts.filter((_, i) => cum[i] >= lo && cum[i] <= hi);
  }, [enriched, trimStart, trimEnd]);

  const stats = enriched ? G.computeStats(trimmedPoints) : null;

  const download = () => {
    if (!trimmedPoints.length) return;
    const xml = G.buildGPX([{ name: tracks[0]?.name || 'Trimmed', segments: [trimmedPoints] }]);
    const blob = new Blob([xml], { type: 'application/gpx+xml' });
    window.downloadBlob(blob, (filename.replace(/\.gpx$/i, '') || 'route') + '-trimmed.gpx');
  };

  if (!tracks) {
    return (
      <div className="mini-tool sport-tool">
        <S.SportsToolHeader title="GPX Trimmer" sub="Clip start/end metres to hide your home address." icon="crop" accent="#dc2626" />
        <window.Dropzone onFile={onFile} title="Drop a .gpx file" hint=".gpx · we'll keep everything in your browser" accept=".gpx" />
      </div>
    );
  }

  const totalKm = enriched ? enriched.total / 1000 : 0;

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="GPX Trimmer" sub={filename} icon="crop" accent="#dc2626" />

      <div className="sport-input-grid">
        <div className="mini-field">
          <label className="mini-label">Trim from start (m)</label>
          <input type="number" min="0" max={Math.floor((enriched?.total || 0) - trimEnd)}
                 className="mini-input"
                 value={trimStart}
                 onChange={(e) => setTrimStart(Math.max(0, Number(e.target.value) || 0))} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Trim from end (m)</label>
          <input type="number" min="0" max={Math.floor((enriched?.total || 0) - trimStart)}
                 className="mini-input"
                 value={trimEnd}
                 onChange={(e) => setTrimEnd(Math.max(0, Number(e.target.value) || 0))} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Total length</label>
          <div className="mini-input" style={{ background: 'var(--id-surface-sunken)' }}>{totalKm.toFixed(2)} km</div>
        </div>
      </div>

      <G.GpxMap points={trimmedPoints} height={280} color="#dc2626" title="Trimmed route" />

      {stats && (
        <div className="gpx-stats">
          <G.StatTile label="Trimmed distance" value={`${(stats.distanceM / 1000).toFixed(2)} km`} sub={`was ${totalKm.toFixed(2)} km`} />
          <G.StatTile label="Removed" value={`${(((enriched.total - stats.distanceM)) / 1000).toFixed(2)} km`} />
          <G.StatTile label="Points kept" value={trimmedPoints.length.toLocaleString()} />
        </div>
      )}

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

      <div className="sport-helper">
        Privacy tip: trim at least 100 m from each end if you start and finish at home — that removes the spot where your route gets densest.
      </div>
    </div>
  );
};
