import { clear } from '../core/dom';
import { openEditor } from '../core/nav';
import { accentRgb, pageHtml } from './markup';

/* ------------------------------------------------------------------ *
 * YeetPDF landing page — Folio-style warm-paper aesthetic.
 * The markup (a pure HTML string) lives in ./markup so the build can
 * prerender it into dist/index.html; this module owns mounting and the
 * interactive layer (click-wiring + the dot-matrix canvas backdrop).
 * ------------------------------------------------------------------ */

export function mountLanding(root: HTMLElement) {
  clear(root);
  const el = document.createElement('div');
  el.className = 'landing-folio';
  el.innerHTML = pageHtml();
  root.appendChild(el);
  wire(el);
  initDots(el);
  window.scrollTo(0, 0);
}

/* ---- interactivity ------------------------------------------------ */

function wire(root: HTMLElement) {
  // Open the editor with a freshly-picked file.
  const picker = root.querySelector<HTMLInputElement>('#lp-file');
  root.querySelectorAll<HTMLElement>('[data-open-file]').forEach((elm) => {
    elm.addEventListener('click', (e) => {
      e.preventDefault();
      picker?.click();
    });
  });
  picker?.addEventListener('change', () => {
    const file = picker.files?.[0];
    if (file) openEditor(file);
    picker.value = '';
  });

  // Open the editor empty.
  root.querySelectorAll<HTMLElement>('[data-open-editor]').forEach((elm) => {
    elm.addEventListener('click', (e) => {
      e.preventDefault();
      openEditor();
    });
  });
}

/** Interactive dot-matrix canvas backdrop (hero, privacy, CTA). */
function initDots(root: HTMLElement) {
  const animate = !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const canvases = [...root.querySelectorAll<HTMLCanvasElement>('canvas[data-dots]')].map((el) => {
    const ctx = el.getContext('2d')!;
    const state = {
      el,
      ctx,
      mx: -9999,
      my: -9999,
      w: 0,
      h: 0,
      dark: el.hasAttribute('data-dark'),
      cta: el.hasAttribute('data-cta'),
    };
    const parent = el.parentElement!;
    parent.addEventListener('mousemove', (e) => {
      const r = el.getBoundingClientRect();
      state.mx = e.clientX - r.left;
      state.my = e.clientY - r.top;
    });
    parent.addEventListener('mouseleave', () => {
      state.mx = -9999;
      state.my = -9999;
    });
    return state;
  });
  if (!canvases.length) return;

  const dpr = Math.min(window.devicePixelRatio || 1, 2);
  const resize = () => {
    canvases.forEach((c) => {
      const r = c.el.getBoundingClientRect();
      c.w = r.width;
      c.h = r.height;
      c.el.width = Math.max(1, Math.round(r.width * dpr));
      c.el.height = Math.max(1, Math.round(r.height * dpr));
      c.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    });
  };
  resize();
  const ro = new ResizeObserver(resize);
  canvases.forEach((c) => {
    ro.observe(c.el);
  });

  const gap = 26;
  const R = 118;
  const draw = () => {
    // Stop (and let GC clean up) once the landing has been unmounted.
    if (!root.isConnected) {
      ro.disconnect();
      return;
    }
    const t = animate ? performance.now() * 0.001 : 0;
    canvases.forEach((c) => {
      if (!c.w) return;
      c.ctx.clearRect(0, 0, c.w, c.h);
      for (let y = gap / 2; y < c.h; y += gap) {
        for (let x = gap / 2; x < c.w; x += gap) {
          const wave = Math.sin((x + y) / 66 - t * 1.15) * 0.5 + 0.5;
          const dx = x - c.mx;
          const dy = y - c.my;
          const d = Math.sqrt(dx * dx + dy * dy);
          let rad = 1.35;
          let col: string;
          if (d < R) {
            const f = 1 - d / R;
            rad = 1.35 + f * 2.2;
            col = `rgba(${accentRgb[0]},${accentRgb[1]},${accentRgb[2]},${0.35 + f * 0.65})`;
          } else if (c.cta) {
            col = `rgba(33,29,24,${0.1 + wave * 0.2})`;
          } else if (c.dark) {
            const a = 0.06 + wave * 0.14;
            col =
              wave > 0.82
                ? `rgba(${accentRgb[0]},${accentRgb[1]},${accentRgb[2]},${0.3 + (wave - 0.82) * 2})`
                : `rgba(255,255,255,${a})`;
          } else {
            const a = 0.06 + wave * 0.13;
            col = wave > 0.86 ? `rgba(${accentRgb[0]},${accentRgb[1]},${accentRgb[2]},0.55)` : `rgba(33,29,24,${a})`;
          }
          c.ctx.beginPath();
          c.ctx.arc(x, y, rad, 0, Math.PI * 2);
          c.ctx.fillStyle = col;
          c.ctx.fill();
        }
      }
    });
    requestAnimationFrame(draw);
  };
  draw();
}
