import { VisQuill, Animate, Boxes, Curves, EasingFunctions, Pins, Points, Polylines, Reactive, Segments, Svg } from "@visquill/visquill-gdk";
import { KM_PER_PIXEL, climbBetween, heightAt, places, trail } from "./data";
import "./styles.css";

// The profile: 1 meter of height is 0.06 pixels.
const PX_PER_METER = 0.06;

// Part 7: labels for the peaks.
export function run(div: HTMLDivElement) {
  const rvg = VisQuill.create(div, "trail-");
  const canvas = rvg.canvas;
  canvas.handles.defaultZIndex = 1;

  const path = canvas.visuals.polyline("path", trail);
  const section = canvas.visuals.polyline("section");

  const distances: { km: number; value: number }[] = [];
  for (let km = 10; km < trail[trail.length - 1].km; km += 10) {
    distances.push({ km, value: km / KM_PER_PIXEL });
  }
  Polylines.pinsAtDistances(path, distances).forEach((pin, i) => {
    canvas.visuals.segment("marker", Pins.moveLeft(pin, 6), Pins.moveRight(pin, 6));
    const label = canvas.text.label(`${distances[i].km} km`, "marker-label");
    Points.copy(Pins.moveRight(pin, 16), label);
  });

  for (const place of places) {
    const point = trail[place.index];
    canvas.visuals.point("place", point);
    const label = canvas.text.label(place.name, "place-name");
    Points.moveUp(point, 12, label);
  }

  const band = canvas.visuals.box("band");

  // The profile: baseline at sea level, height lines, curve and area.
  const baseline = canvas.visuals.polyline("baseline", [[60, 315], [520, 315]]);
  const width = 460;

  for (const meters of [500, 1000, 1500]) {
    const y = 315 - meters * PX_PER_METER;
    canvas.visuals.segment("grid", [60, y], [520, y]);
    const label = canvas.text.label(`${meters} m`, "grid-label");
    Points.copy([54, y], label);
  }

  const total = trail[trail.length - 1].km;
  const positions = trail.map((p) => ({ value: (p.km / total) * width }));
  const values = trail.map((p) => ({ value: p.height * PX_PER_METER }));

  const curve = Curves.alongPolyline(baseline, positions, values, 0, true);
  canvas.visuals.polygon("area", [...curve.elements, { x: 520, y: 315 }, { x: 60, y: 315 }]);
  canvas.visuals.polyline("profile", curve);

  const from = canvas.handles.disk("range", [290, 315]);
  const to = canvas.handles.disk("range", [405, 315]);
  const sectionLabel = canvas.text.label("", "section-label");
  Points.copy([520, 190], sectionLabel);

  Reactive.do([from, to], () => {
    Polylines.closestPoint(baseline, from, from);
    Polylines.closestPoint(baseline, to, to);
    const left = Math.min(from.x, to.x);
    const right = Math.max(from.x, to.x);
    const start = (left - 60) / width;
    const end = (right - 60) / width;

    Polylines.slice(path, start, end, section);
    Boxes.box([left, 215], right - left, 100, band);

    const km = (end - start) * total;
    const climb = climbBetween(start * total, end * total);
    sectionLabel.value = `Section: ${km.toFixed(1)} km, ↑ ${Math.round(climb)} m`;
  });

  // The place on the trail as a reactive value: a ratio from 0 (start) to 1 (end).
  const ratio = canvas.values.real(0.3);

  const drop = canvas.visuals.segment("drop");
  const readout = canvas.text.label("", "readout");

  // The probe and the walker are points, drawn from the ratio.
  const probe = canvas.visuals.point("probe");
  const walker = canvas.visuals.point("walker");

  // One invisible handle does the dragging for both.
  const drag = canvas.handles.disk("drag");
  let dragging: "probe" | "walker" = "probe";
  Svg.get(probe).addEventListener("pointerdown", () => {
    dragging = "probe";
    drag.active.value = true;
  });
  Svg.get(walker).addEventListener("pointerdown", () => {
    dragging = "walker";
    drag.active.value = true;
  });

  Reactive.do([drag], () => {
    if (!drag.active.value) return;
    ratio.value = dragging === "probe"
      ? Math.min(1, Math.max(0, (drag.x - 60) / width))
      : Polylines.closestPosition(path, drag).value;
  });

  // The ratio places both points, the drop line and the readout.
  Reactive.do([ratio], () => {
    const km = ratio.value * total;
    const height = heightAt(km);
    Points.copy([60 + ratio.value * width, 315 - height * PX_PER_METER], probe);
    Polylines.pointAt(path, ratio, walker);
    Segments.segment(probe, [probe.x, 315], drop);
    readout.value = `${km.toFixed(1)} km · ${Math.round(height)} m`;
    const right = ratio.value < 0.5;
    Points.copy([probe.x + (right ? 6 : -6), 309], readout);
    Svg.get(readout).style.textAnchor = right ? "start" : "end";
  });

  // A label above each peak on the profile: the places between start and end.
  for (const place of places.slice(1, -1)) {
    const point = trail[place.index];
    const x = 60 + (point.km / total) * width;
    const y = 315 - point.height * PX_PER_METER;
    const label = canvas.text.label(place.name, "peak region-peaks");
    Points.copy([x, y - 8], label);

    // A click on the label animates the ratio to the peak. The ratio's
    // reaction moves the probe, the walker and the readout along with it.
    Svg.get(label).addEventListener("click", () => {
      Animate.real.eased(ratio, point.km / total, 800, {
        easing: EasingFunctions.easeInOutCubic,
      });
    });
  }
}
// A made-up trail, as if it came from a GPS track that has already been
// projected to the screen: x and y in pixels, the height in meters.
// One pixel along the trail is 100 meters.
export const KM_PER_PIXEL = 0.1;

export interface TrailPoint {
  x: number;
  y: number;
  /** Height above sea level, in meters. */
  height: number;
  /** Distance from the start of the trail, in kilometers. */
  km: number;
}

// Three hills and some noise. bump(t, center, width) is a smooth hill.
const bump = (t: number, center: number, width: number) => Math.exp(-(((t - center) / width) ** 2));

const COUNT = 241;
export const trail: TrailPoint[] = [];
for (let i = 0; i < COUNT; i++) {
  const t = i / (COUNT - 1);
  const x = 30 + 500 * t;
  const y = 95 + 45 * Math.sin(t * 3 * Math.PI) + 12 * Math.sin(t * 10 * Math.PI);
  const height = 420 + 850 * bump(t, 0.24, 0.07) + 1150 * bump(t, 0.6, 0.05) + 520 * bump(t, 0.88, 0.06)
    + 40 * Math.sin(t * 47);
  const previous = trail[i - 1];
  const km = previous ? previous.km + Math.hypot(x - previous.x, y - previous.y) * KM_PER_PIXEL : 0;
  trail.push({ x, y, height, km });
}

/** Named places along the trail, by the index of their point. */
export const places = [
  { name: "Ashby", index: 0 },
  { name: "Grey Fell", index: 58 },
  { name: "High Crag", index: 144 },
  { name: "Wether Hill", index: 210 },
  { name: "Lowmoor", index: COUNT - 1 },
];

/** The height at a distance along the trail, between the two nearest points. */
export function heightAt(km: number): number {
  const i = trail.findIndex((p) => p.km >= km);
  if (i === 0) return trail[0].height;
  if (i === -1) return trail[trail.length - 1].height;
  const a = trail[i - 1];
  const b = trail[i];
  return a.height + ((km - a.km) / (b.km - a.km)) * (b.height - a.height);
}

/** The total climb between two distances: all ascents added up, descents left out. */
export function climbBetween(fromKm: number, toKm: number): number {
  let climb = 0;
  let previous = heightAt(fromKm);
  for (const p of trail) {
    if (p.km <= fromKm || p.km >= toKm) continue;
    climb += Math.max(0, p.height - previous);
    previous = p.height;
  }
  return climb + Math.max(0, heightAt(toKm) - previous);
}
/* Each class is the prefix "trail-" plus the name used in demo.ts. */

.trail-path {
  fill: none;
  stroke: #3d6fa8;
  stroke-width: 3px;
  stroke-linejoin: round;
}

.trail-place { r: 4px; fill: #1c1a17; }
.trail-place-name {
  fill: #1c1a17;
  font: 500 12px Inter, system-ui, sans-serif;
  text-anchor: middle;
  user-select: none;
}

.trail-marker { stroke: #1c1a17; stroke-width: 1.5px; }
.trail-marker-label {
  fill: #6b645a;
  font: 500 10px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: middle;
  dominant-baseline: middle;
  user-select: none;
}

.trail-baseline { fill: none; stroke: #1c1a17; stroke-width: 1px; }
.trail-grid { stroke: #e7decb; stroke-width: 1px; }
.trail-grid-label {
  fill: #6b645a;
  font: 500 10px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: end;
  dominant-baseline: middle;
  user-select: none;
}
.trail-profile { fill: none; stroke: #3d6fa8; stroke-width: 2px; stroke-linejoin: round; }
.trail-area { fill: rgb(61 111 168 / 0.15); stroke: none; }

/* Part 4: the probe, its drop line, the spot on the trail and the readout. */
.trail-probe { r: 7px; fill: #d8913a; stroke: #faf6ef; stroke-width: 2px; cursor: grab; }
.trail-probe:active { cursor: grabbing; }
.trail-drop { stroke: #d8913a; stroke-width: 1px; stroke-dasharray: 3 3; }
.trail-spot { r: 6px; fill: #d8913a; stroke: #faf6ef; stroke-width: 2px; }
.trail-readout {
  fill: #1c1a17;
  font: 500 11px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: start;
  user-select: none;
}

/* Part 5: probe and walker are points; the handle that drags them is invisible. */
.trail-probe, .trail-walker {
  r: 7px;
  fill: #d8913a;
  stroke: #faf6ef;
  stroke-width: 2px;
  cursor: grab;
}
.trail-drag { visibility: hidden; }

/* Part 6: the section on the trail and on the profile. */
.trail-section { fill: none; stroke: #c0503f; stroke-width: 5px; stroke-linecap: round; stroke-linejoin: round; }
.trail-band { fill: rgb(192 80 63 / 0.1); }
.trail-range { r: 6px; fill: #c0503f; stroke: #faf6ef; stroke-width: 2px; cursor: ew-resize; }
.trail-section-label {
  fill: #c0503f;
  font: 600 11px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: end;
  user-select: none;
}

/* Part 7: peak labels; they can be clicked. */
.trail-peak {
  fill: #1c1a17;
  font: 600 11px Inter, system-ui, sans-serif;
  text-anchor: middle;
  cursor: pointer;
  user-select: none;
}
.trail-peak:hover { fill: #d8913a; }

A trail elevation profile · Part 7 of 7

Peaks

Labels for the peaks on the profile. A click moves the probe to the peak.

01

Labels on the profile

The places between start and end are the three peaks. Their position on the profile is computed the same way as for the curve: the distance gives x, the height gives y. The label sits 8 pixels above the curve.

02

Going to a peak

A click on a label animates the ratio to the peak's place with Animate.real.eased. Nothing else is needed: the ratio's reaction moves the probe, the walker and the readout on every step of the animation.

This is the reason for keeping the ratio as a reactive value. Every part of the graphic that shows the current place follows it.