'use strict';
// ═══════════════════════════════════════════════
// js/photos.js — Canvas-based photo rendering with watermark + right-click/drag block
// ═══════════════════════════════════════════════

// Returns HTML for a canvas that will be rendered asynchronously by the observer.
// opts: { classes, style, watermarkName, lightbox (bool, default true) }
function photoCanvas(key, opts = {}) {
  const dataAttrs = [`data-img-key="${key}"`];
  if (opts.watermarkName) dataAttrs.push(`data-wm-name="${opts.watermarkName.replace(/"/g, '&quot;')}"`);
  if (opts.lightbox !== false) dataAttrs.push('data-lightbox="1"');
  const cls   = 'photo-canvas' + (opts.classes ? ' ' + opts.classes : '');
  const style = opts.style || 'width:100%;border-radius:7px;cursor:pointer;display:block';
  return `<canvas class="${cls}" style="${style}" ${dataAttrs.join(' ')}></canvas>`;
}

// ── Watermark ──
const _WM_OPACITY = { low: 0.10, medium: 0.20, high: 0.36 };

function _drawWatermark(ctx, text, w, h, wm) {
  const alpha = _WM_OPACITY[wm.opacity || 'medium'] ?? 0.20;
  const style = wm.style || 'none';
  if (style === 'none') return;

  ctx.save();
  ctx.globalAlpha = alpha;
  ctx.fillStyle   = '#ffffff';
  ctx.strokeStyle = '#000000';
  ctx.lineWidth   = 3;
  ctx.textAlign   = 'center';
  ctx.textBaseline = 'middle';
  const size = Math.max(11, Math.min(w, h) * 0.04);
  ctx.font = `bold ${size}px monospace`;

  const _draw = (x, y) => { ctx.strokeText(text, x, y); ctx.fillText(text, x, y); };

  if (style === 'center' || style === 'combined') {
    _draw(w / 2, h / 2);
  }

  if (style === 'corner' || style === 'combined') {
    const pad = size;
    ctx.textAlign = 'right'; ctx.textBaseline = 'bottom';
    _draw(w - pad, h - pad);
    ctx.textAlign = 'left';  ctx.textBaseline = 'top';
    _draw(pad, pad);
    ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  }

  if (style === 'tiled' || style === 'combined') {
    ctx.save();
    ctx.rotate(-Math.PI / 6);
    const step = Math.min(w, h) * 0.5;
    for (let x = -h; x < w + h; x += step) {
      for (let y = -h; y < h + h; y += step) {
        _draw(x, y);
      }
    }
    ctx.restore();
  }

  ctx.restore();
}

// ── Core render ──
async function _drawPhotoCanvas(canvas) {
  const key = canvas.dataset.imgKey;
  if (!key) return;
  canvas.dataset.rendered = '1';

  const src = (typeof imgCache !== 'undefined' && imgCache[key]) ? imgCache[key] : null;
  if (!src) {
    // Placeholder sized box — trigger lazy load so it re-renders when the blob arrives
    canvas.style.aspectRatio = '3/4';
    canvas.style.background  = 'var(--surface2, #1e1e1e)';
    if (typeof imgURL === 'function') imgURL(key);
    return;
  }

  const img = new Image();
  img.src = src;
  try {
    await new Promise((res, rej) => { img.onload = res; img.onerror = rej; });
  } catch(e) {
    return;
  }

  const dpr    = window.devicePixelRatio || 1;
  const dispW  = Math.min(canvas.parentElement?.offsetWidth || 320, 520);
  const aspect = img.naturalHeight / (img.naturalWidth || 1);
  const dispH  = Math.round(dispW * aspect);

  canvas.width  = dispW * dpr;
  canvas.height = dispH * dpr;
  canvas.style.width  = '100%';
  canvas.style.height = 'auto';

  const ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr);
  ctx.drawImage(img, 0, 0, dispW, dispH);

  // Watermark (buddy photos only)
  const wmName = canvas.dataset.wmName;
  if (wmName) {
    const wm = (typeof getWatermarkSettings === 'function' ? getWatermarkSettings() : null) || { style: 'none' };
    if (wm.style !== 'none') _drawWatermark(ctx, wmName, dispW, dispH, wm);
  }

  // Lightbox click — use canvas content so watermark is included
  if (canvas.dataset.lightbox && !canvas._clickSet) {
    canvas._clickSet = true;
    canvas.addEventListener('click', () => {
      if (typeof openLb === 'function') openLb(canvas.toDataURL('image/jpeg', 0.92));
    });
  }
}

// Called by p2p.js / storage.js after imgCache[key] is populated — re-renders live canvases
function rerenderPhotoCanvases(key) {
  document.querySelectorAll('canvas[data-img-key]').forEach(c => {
    if (c.dataset.imgKey === key) {
      delete c.dataset.rendered;
      _drawPhotoCanvas(c);
    }
  });
}

// MutationObserver: render any canvas[data-img-key]:not([data-rendered]) entering the DOM
(function _initPhotoObserver() {
  function _scan(root) {
    if (root.nodeType !== 1) return;
    if (root.matches?.('canvas[data-img-key]:not([data-rendered])')) _drawPhotoCanvas(root);
    root.querySelectorAll?.('canvas[data-img-key]:not([data-rendered])').forEach(_drawPhotoCanvas);
  }
  const obs = new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(_scan)));
  const start = () => obs.observe(document.body, { childList: true, subtree: true });
  document.body ? start() : document.addEventListener('DOMContentLoaded', start);
})();
