import { VisQuill, Attach, Animate, EasingFunctions, Svg, Reactive, Circles, Rectangles, Pins, Symbols, type Real, type RvgGroup, type Circle } from "@visquill/visquill-gdk";
import { categories, shapes, points } from "./data";
import "./styles.css";

// Part 9: count colors and shapes, with one chart each.
export function run(div: HTMLDivElement) {
  const rvg = VisQuill.create(div, "lens-");
  const canvas = rvg.canvas;
  canvas.handles.defaultZIndex = 1;

  // Each point is drawn as its shape, in the color of its category.
  const dots = canvas.layer();
  for (const p of points) {
    const style = `dot ${categories[p.category]}`;
    const shape = shapes[p.shape];
    if (shape === "circle") Symbols.circle(p, 4, dots.visuals.circle(style));
    if (shape === "square") Symbols.square(p, 7, dots.visuals.rectangle(style));
    if (shape === "triangle") Symbols.triangle(p, 9, "up", dots.visuals.triangle(style));
    if (shape === "diamond") Symbols.diamond(p, 5, dots.visuals.rectangle(style));
  }

  const handle = canvas.handles.disk("handle", { x: 280, y: 170 });

  const cover = canvas.layer();
  cover.visuals.box("shade", [-2000, -2000], [3000, 3000]);
  cover.mask.box("white", [-2000, -2000], [3000, 3000]);

  const lens = canvas.layer();
  Attach.pointToPoint(lens.anchor, handle);
  const radius = lens.values.real(70);
  const ring = lens.visuals.circle("ring");
  Attach.circleRadiusToValue(ring, radius);

  const hole = cover.mask.circle("black");
  Reactive.do([handle, radius], () => {
    Circles.circleAt(handle, radius, hole);
  }, true);

  // Two sets of counts, filled in the same loop.
  const byColor = categories.map(() => lens.values.real(0));
  const byShape = shapes.map(() => lens.values.real(0));
  Reactive.do([handle, radius], () => {
    const colors = categories.map(() => 0);
    const kinds = shapes.map(() => 0);
    for (const p of points) {
      if (Math.hypot(p.x - handle.x, p.y - handle.y) < radius.value) {
        colors[p.category] += 1;
        kinds[p.shape] += 1;
      }
    }
    colors.forEach((n, i) => (byColor[i].value = n));
    kinds.forEach((n, i) => (byShape[i].value = n));
  }, true);

  // The chart code of parts 6 to 8 as a function, called once per chart.
  barChart(lens, ring, byColor, -Math.PI / 2, categories, (i) => String(byColor[i].value));
  barChart(lens, ring, byShape, Math.PI / 2, shapes.map(() => "shape"), (i) =>
    `${["●", "■", "▲", "◆"][i]} ${byShape[i].value}`);

  const sizes = [70, 100, 50];
  let next = 0;
  Svg.get(ring).addEventListener("click", () => {
    next = (next + 1) % sizes.length;
    Animate.real.eased(radius, sizes[next], 600, { easing: EasingFunctions.easeOutCubic });
  });
}

// Bars along a quarter of the ring, centered at `angle`, one bar per count, each
// with a label. `styles` are the bar classes, `label` returns the label texts.
function barChart(
  group: RvgGroup, ring: Circle, counts: Real[], angle: number,
  styles: string[], label: (i: number) => string,
) {
  const baseline = group.visuals.polyline("baseline", counts.length + 1);
  Attach.polylineToCircle(baseline, ring, Math.PI / 2, { angle, distance: 4 });

  const heights = counts.map(() => group.values.real(0));
  Reactive.do(counts, () => {
    const total = Math.max(1, counts.reduce((sum, count) => sum + count.value, 0));
    counts.forEach((count, i) => Animate.real.follow(heights[i], (count.value / total) * 60));
  }, true);

  counts.forEach((count, i) => {
    const bar = group.visuals.rectangle(`bar ${styles[i]}`);
    Reactive.do([baseline, heights[i]], () => {
      Rectangles.alongPaddedSegment(baseline.at(i), baseline.at(i + 1), heights[i], true, 0, 2, 2, bar);
    }, true);

    const text = group.text.label("", true, 0, 0, true, "value");
    Reactive.do([baseline, heights[i]], () => {
      Pins.placeAndAlignBesideSegment(
        baseline.at(i), baseline.at(i + 1), 0.5, heights[i].value + 10, true, text);
    }, true);
    Reactive.do([count], () => {
      text.value = label(i);
    }, true);
  });
}
// The data the lens explores: 240 points in four categories. Each category
// is distributed around its own center, so the mix differs across the canvas.
// The random numbers are seeded, so the points are the same on every load.

export const categories = ["red", "green", "blue", "orange"];

// A second property, used in part 9: each point also has a shape.
export const shapes = ["circle", "square", "triangle", "diamond"];

export interface DataPoint {
  x: number;
  y: number;
  category: number; // index into categories
  shape: number;    // index into shapes
}

const centers = [
  { x: 170, y: 120 },
  { x: 390, y: 110 },
  { x: 210, y: 250 },
  { x: 400, y: 240 },
];

export const points: DataPoint[] = [];

const random = seededRandom(7);
centers.forEach((center, category) => {
  for (let i = 0; i < 60; i++) {
    // Normally distributed around the center (Box–Muller), kept on the canvas.
    const length = 65 * Math.sqrt(-2 * Math.log(1 - random()));
    const angle = 2 * Math.PI * random();
    points.push({
      x: clamp(center.x + length * Math.cos(angle), 12, 548),
      y: clamp(center.y + length * Math.sin(angle), 12, 328),
      category,
      shape: 0,
    });
  }
});

// Each shape is most frequent near one corner.
const corners = [
  { x: 0, y: 0 },
  { x: 560, y: 0 },
  { x: 0, y: 340 },
  { x: 560, y: 340 },
];
const randomShape = seededRandom(11);
for (const p of points) {
  const weights = corners.map((c) => Math.exp(-((p.x - c.x) ** 2 + (p.y - c.y) ** 2) / 90000));
  let pick = randomShape() * weights.reduce((sum, w) => sum + w, 0);
  p.shape = weights.findIndex((w) => (pick -= w) < 0);
  if (p.shape < 0) p.shape = weights.length - 1;
}

function clamp(value: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, value));
}

// A small seeded generator (mulberry32): the same seed gives the same numbers.
function seededRandom(seed: number): () => number {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
/* Each class is the prefix "lens-" plus the name used in demo.ts. */

/* Data points: one class for all dots, one per category. */
.lens-dot { r: 4px; }
.lens-red    { fill: #c0503f; }
.lens-green  { fill: #3f7a5b; }
.lens-blue   { fill: #3d6fa8; }
.lens-orange { fill: #d8913a; }

/* The handle is transparent and about as large as the lens. */
.lens-handle {
  r: 45px;
  fill: transparent;
  cursor: grab;
}
.lens-handle:active { cursor: grabbing; }

.lens-ring {
  fill: none;
  stroke: #1c1a17;
  stroke-width: 2px;
  pointer-events: stroke;
  cursor: pointer;
}

/* The cover darkens the canvas outside the lens. */
.lens-shade { fill: rgb(28 26 23 / 0.55); }

.lens-readout {
  fill: #1c1a17;
  font: 500 14px "JetBrains Mono", ui-monospace, monospace;
  dominant-baseline: hanging;
}

.lens-baseline { fill: none; stroke: none; }

.lens-bar { stroke: #faf6ef; stroke-width: 1.5px; }

.lens-value {
  fill: #faf6ef;
  font: 600 12px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: middle;
  dominant-baseline: middle;
}

/* Part 9: bars of the shape chart; the label shows the shape. */
.lens-shape { fill: #e7decb; }

Build a data lens · Part 9 of 9

A second dimension

Each point also has a shape. The lens counts colors and shapes and shows the shapes in a second chart.

01

Shapes

Each data point now also has a shape. Each shape is most frequent near one corner of the canvas, independent of the categories.

02

Drawing the shapes

Symbols creates a circle, square, triangle or diamond around a point. The color still comes from the category class.

03

Counting both

The counting block now has a second tally. One loop over the points fills both sets of values, by color and by shape.

04

A function for the chart

The code for baseline, heights, bars and labels from parts 6 to 8 is moved into the function barChart. Its parameters are the group to draw on, the ring, the counts, the position on the rim, the bar styles and the label texts.

05

Two charts

The function is called twice: for the colors at the top of the ring and for the shapes at the bottom. Both charts are attached to the same ring and move with the lens.