//
// a dot is x, y
// a spot is x, y and represents a filled in area based on the screen render contents
// to test, we'll have some granularity, like 10x10 sections, to keep
// the number of spots low
var unassigned_dots = []; // these just drift
var assigned_dots = []; // (dot, spot)

const xstart = 150;
const ystart = 150;
const text = `Welcome!`

const ex = 0;
const ey = 0;
const fontSize = 50;
const fontFile = "freesansbold.ttf"

var spots = [];

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const result = document.getElementById("result");

ctx.translate(200, 200);

fetch(fontFile)
  .then(response => response.arrayBuffer())
  .then(b => opentype.parse(b))
  .then(font => {
    arr = text.split("\n");
    for (const [i, t] of arr.entries()) {
      var paths = generatePathsFromText(font, t, fontSize);
      for (var path of paths) {
        var path2d = new Path2D(path.p);
        for (var x = -1000; x < 1000; x += 2) {
          for (var y = -1000; y < 1000; y += 2) {
            if (ctx.isPointInPath(path2d, x, y, "nonzero")) {
              spots.push({ x: 100 + x + path.x, y: y + i * fontSize });
            }
          }
        }
      }
    }
  }
  ).then(() => {
    assign_dots(spots);
    window.setInterval(render_assigned, 32);
  }
  );

function add_dots_b() {
  var p = document.createElement("div");
  p.style.position = "absolute";
  p.style.left = "0px";
  p.style.top = "0px";
  p.appendChild(document.createTextNode("."))
  document.body.appendChild(p);
  s = Math.random() * 1;
  ys = Math.random() * 2 * s - s;
  xs = (Math.random() > 0.5 ? -1 : 1) * Math.sqrt(Math.abs(s * s - ys * ys));
  unassigned_dots.push({ x: xstart, y: ystart, v: { x: xs, y: ys }, p })
  return p;
}

function add_dots() {
  var p = document.createElement("div");
  p.style.position = "absolute";
  p.style.left = "0px";
  p.style.top = "0px";
  p.appendChild(document.createTextNode("."))
  document.body.appendChild(p);
  s = Math.random() * 1;
  xs = Math.random() * 2 * s - s;
  ys = (Math.random() > 0.5 ? -1 : 1) * Math.sqrt(Math.abs(s * s - xs * xs));
  unassigned_dots.push({ x: xstart, y: ystart, v: { x: xs, y: ys }, p })
  return p;
}

function rotate_dot(dot, x, y, ang) {
  adj = dot.x - x;
  opp = dot.y - y;
  hypot = (adj < 0 ? -1 : 1) * Math.hypot(adj, opp);
  currang = Math.atan(opp / adj);
  currang += ang;
  newadj = hypot * Math.cos(currang);
  newopp = hypot * Math.sin(currang);
  dot.x = newadj + x;
  dot.y = newopp + y;
}

for (var n = 0; n < 1000; n++) { add_dots_b(); }
for (var n = 0; n < 1000; n++) { add_dots(); }

function dx(spot, dot) {
  return (spot.x - dot.x) ^ 2 + (spot.y - dot.y) ^ 2
}

function dotsync(dot) {
  dot.p.style.left = dot.x + "px";
  dot.p.style.top = dot.y + "px";
}

function recreate_spots(path) {
  unassigned_dots += assigned_dots.map(d => d[0]);
  assigned_dots = [];

  for (var x = 0; x < 1000; x++) {
    for (var y = 0; y < 1000; y++) {
      if (ctx.isPointInPath(path, x, y - 100)) {
        spots.push({ x, y })
      }
    }
  }
}

// give every dot to a filled in area on the screen
// find the closest one
function assign_dots(spots) {
  for (s of spots) {
    sf = function (dotb, dota) {
      return dx(s, dota) - dx(s, dotb)
    }
    unassigned_dots.sort(sf);
    assign = unassigned_dots.pop();
    if (assign != undefined) {
      assigned_dots.push([assign, s]);
    } else {
      break;
    }
  }
}

function assign_unassigned() {
  for (d of unassigned_dots) {
    d.p.innerText = "x";
  }
}

var times = 0;

function render_assigned() {
  for (d of assigned_dots) {
    // move it closer
    d[0].x += (d[1].x - d[0].x) / 10;
    d[0].y += (d[1].y - d[0].y) / 10;
    dotsync(d[0]);
  }
  for (d of unassigned_dots) {
    d.x += d.v.x;
    d.y += d.v.y;
    rotate_dot(d, xstart, ystart, 0.01);
    dotsync(d);
  }
  return true;
}

function generatePathsFromText(font, text, fontSize) {
  // Font metrics: Convert font units (em) to pixels  
  const scale = fontSize / font.unitsPerEm;
  let currentX = 0; // Track horizontal position of glyphs  

  ps = [];

  // Iterate over each character in the text
  for (const char of text) {
    const glyph = font.charToGlyph(char);
    if (!glyph) continue; // Skip unsupported characters  

    // Get glyph path and scale to fontSize  
    const glyphPath = glyph.getPath(0, 0, fontSize, { yScale: scale }, font);
    ps.push({ p: glyphPath.toPathData({ flipY: false }), x: currentX }); // Append SVG path commands  

    // Update horizontal position for next glyph (account for kerning)  
    currentX += glyph.advanceWidth * scale;
  }

  return ps;
}

