Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

37.5 KB
Raw Blame
/* DesignTaste Branded Share Card & Edition Exporter (100% client-side canvas + zero-dep ZIP) */

const BRAND_DOMAIN = "designtaste.wtf";
const MAX_EDITION_SLIDES = 12;

function hostOf(url) {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return String(url || "").replace(/^https?:\/\//, "").replace(/\/.*$/, "");
  }
}

function pad2(n) {
  return String(n).padStart(2, "0");
}

function slugify(text) {
  return (
    String(text || "edition")
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "")
      .slice(0, 48) || "edition"
  );
}

/* ---------- Image loader with in-memory cache ---------- */
const imgCache = new Map();

function loadImage(src) {
  if (!src) return Promise.reject(new Error("Missing image source"));
  if (imgCache.has(src)) return imgCache.get(src);
  const p = new Promise((resolve, reject) => {
    const img = new Image();
    img.decoding = "async";
    img.crossOrigin = "anonymous";
    img.onload = () => resolve(img);
    img.onerror = () => {
      imgCache.delete(src);
      reject(new Error(`Failed to load ${src}`));
    };
    img.src = src;
  });
  imgCache.set(src, p);
  return p;
}

/* ---------- Canvas geometry & brand drawing helpers ---------- */
function roundRectPath(ctx, x, y, w, h, r) {
  const rad = typeof r === "number" ? { tl: r, tr: r, br: r, bl: r } : r;
  ctx.beginPath();
  ctx.moveTo(x + rad.tl, y);
  ctx.lineTo(x + w - rad.tr, y);
  ctx.quadraticCurveTo(x + w, y, x + w, y + rad.tr);
  ctx.lineTo(x + w, y + h - rad.br);
  ctx.quadraticCurveTo(x + w, y + h, x + w - rad.br, y + h);
  ctx.lineTo(x + rad.bl, y + h);
  ctx.quadraticCurveTo(x, y + h, x, y + h - rad.bl);
  ctx.lineTo(x, y + rad.tl);
  ctx.quadraticCurveTo(x, y, x + rad.tl, y);
  ctx.closePath();
}

function drawBrandMark(ctx, x, y, size) {
  ctx.save();
  ctx.translate(x, y);
  const s = size / 40;
  ctx.scale(s, s);

  const bg = ctx.createLinearGradient(0, 0, 40, 40);
  bg.addColorStop(0, "#23232c");
  bg.addColorStop(1, "#0b0b0e");
  roundRectPath(ctx, 0.75, 0.75, 38.5, 38.5, 10.5);
  ctx.fillStyle = bg;
  ctx.fill();
  ctx.lineWidth = 1.5;
  ctx.strokeStyle = "rgba(255,255,255,0.22)";
  ctx.stroke();

  const fg = ctx.createLinearGradient(13, 11.5, 28, 28.5);
  fg.addColorStop(0, "#ffffff");
  fg.addColorStop(1, "#a5b4fc");
  ctx.fillStyle = fg;

  // Crisp geometric "D" path matching favicon.svg
  ctx.beginPath();
  ctx.moveTo(13, 11.5);
  ctx.lineTo(19.2, 11.5);
  ctx.bezierCurveTo(24.6, 11.5, 28, 14.8, 28, 20);
  ctx.bezierCurveTo(28, 25.2, 24.6, 28.5, 19.2, 28.5);
  ctx.lineTo(13, 28.5);
  ctx.closePath();

  ctx.moveTo(17.2, 15);
  ctx.lineTo(17.2, 25);
  ctx.lineTo(19.1, 25);
  ctx.bezierCurveTo(22.1, 25, 23.7, 23.2, 23.7, 20);
  ctx.bezierCurveTo(23.7, 16.8, 22.1, 15, 19.1, 15);
  ctx.closePath();
  ctx.fill("evenodd");

  // Accent dot
  ctx.beginPath();
  ctx.arc(29.5, 11.5, 2.7, 0, Math.PI * 2);
  ctx.fillStyle = "#ff4d6d";
  ctx.fill();
  ctx.restore();
}

function drawBrandLockupRight(ctx, rightX, centerY, { markSize = 24, fontSize = 18 } = {}) {
  ctx.save();
  ctx.textBaseline = "middle";
  ctx.font = `500 ${fontSize}px "Geist", -apple-system, BlinkMacSystemFont, sans-serif`;
  const w1 = ctx.measureText("designtaste").width;
  const w2 = ctx.measureText(".wtf").width;
  const gap = Math.round(markSize * 0.38);
  const startX = rightX - (markSize + gap + w1 + w2);

  drawBrandMark(ctx, startX, centerY - markSize / 2, markSize);
  ctx.fillStyle = "#c4c6d4";
  ctx.fillText("designtaste", startX + markSize + gap, centerY + 0.5);
  ctx.fillStyle = "#6e7080";
  ctx.fillText(".wtf", startX + markSize + gap + w1, centerY + 0.5);
  ctx.restore();
}

function drawTrackedText(ctx, text, x, y, tracking = 1.4, align = "left") {
  const chars = [...String(text || "")];
  if (!chars.length) return;
  let total = 0;
  const widths = chars.map((ch) => {
    const w = ctx.measureText(ch).width;
    total += w;
    return w;
  });
  total += tracking * Math.max(0, chars.length - 1);
  let cursor = align === "right" ? x - total : align === "center" ? x - total / 2 : x;
  for (let i = 0; i < chars.length; i++) {
    ctx.fillText(chars[i], cursor, y);
    cursor += widths[i] + tracking;
  }
}

function drawWrappedLines(ctx, text, x, y, maxWidth, lineHeight, maxLines = 3) {
  const words = String(text || "").trim().split(/\s+/).filter(Boolean);
  const lines = [];
  let current = "";
  for (const word of words) {
    const test = current ? `${current} ${word}` : word;
    if (ctx.measureText(test).width > maxWidth && current) {
      lines.push(current);
      current = word;
      if (lines.length === maxLines) break;
    } else {
      current = test;
    }
  }
  if (current && lines.length < maxLines) lines.push(current);
  if (lines.length === maxLines && words.length) {
    const joined = lines.join(" ");
    if (joined.length < String(text || "").trim().length) {
      let last = lines[maxLines - 1];
      while (last.length > 4 && ctx.measureText(`${last}…`).width > maxWidth) {
        last = last.slice(0, -1);
      }
      lines[maxLines - 1] = `${last.trimEnd()}…`;
    }
  }
  lines.forEach((line, idx) => ctx.fillText(line, x, y + idx * lineHeight));
  return lines.length;
}

function drawBrowserFrame(
  ctx,
  { x, y, w, h, domain, img, showChrome = true, radius = 14, chromeHeight = 42, cropMode = "top" },
) {
  ctx.save();
  // Soft studio elevation shadow
  ctx.shadowColor = "rgba(0, 0, 0, 0.55)";
  ctx.shadowBlur = 34;
  ctx.shadowOffsetY = 16;
  roundRectPath(ctx, x, y, w, h, radius);
  ctx.fillStyle = "#111114";
  ctx.fill();
  ctx.shadowColor = "transparent";

  // Clip inner content to rounded browser shell
  ctx.save();
  roundRectPath(ctx, x, y, w, h, radius);
  ctx.clip();

  let viewY = y;
  let viewH = h;

  if (showChrome) {
    // Minimal dark macOS top chrome bar
    ctx.fillStyle = "#141418";
    ctx.fillRect(x, y, w, chromeHeight);

    // 3 quiet traffic-light dots
    const dotY = y + chromeHeight / 2;
    const dotR = Math.max(3.6, Math.round(chromeHeight * 0.11));
    const dotGap = Math.round(dotR * 3.1);
    const dotStart = x + Math.round(chromeHeight * 0.48);
    ctx.fillStyle = "rgba(255, 255, 255, 0.16)";
    for (let i = 0; i < 3; i++) {
      ctx.beginPath();
      ctx.arc(dotStart + i * dotGap, dotY, dotR, 0, Math.PI * 2);
      ctx.fill();
    }

    // Centered URL pill
    const pillW = Math.min(Math.round(w * 0.34), Math.max(170, Math.round(w * 0.28)));
    const pillH = Math.round(chromeHeight * 0.56);
    const pillX = x + (w - pillW) / 2;
    const pillY = y + (chromeHeight - pillH) / 2;
    roundRectPath(ctx, pillX, pillY, pillW, pillH, Math.round(pillH / 2));
    ctx.fillStyle = "#1d1d22";
    ctx.fill();
    ctx.lineWidth = 1;
    ctx.strokeStyle = "rgba(255, 255, 255, 0.06)";
    ctx.stroke();

    ctx.fillStyle = "#8a8c9d";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.font = `450 ${Math.max(10, Math.round(chromeHeight * 0.29))}px "Geist Mono", ui-monospace, monospace`;
    let label = domain || "";
    while (label.length > 8 && ctx.measureText(label).width > pillW - 22) {
      label = `${label.slice(0, -2)}…`;
    }
    ctx.fillText(label, x + w / 2, dotY + 0.5);
    ctx.textAlign = "left";

    // Subtle divider under chrome
    ctx.fillStyle = "rgba(255, 255, 255, 0.07)";
    ctx.fillRect(x, y + chromeHeight - 1, w, 1);

    viewY = y + chromeHeight;
    viewH = h - chromeHeight;
  }

  // Draw website capture scaled cleanly to full viewport width, top-aligned
  if (img && img.naturalWidth > 0 && img.naturalHeight > 0) {
    const scale = w / img.naturalWidth;
    const drawnH = img.naturalHeight * scale;
    if (cropMode === "contain-height" && drawnH < viewH) {
      ctx.drawImage(img, x, viewY, w, drawnH);
    } else {
      const srcH = Math.min(img.naturalHeight, viewH / scale);
      const dstH = srcH * scale;
      ctx.drawImage(img, 0, 0, img.naturalWidth, srcH, x, viewY, w, dstH);
    }
  }

  ctx.restore();

  // Crisp outer 1px hairline border
  roundRectPath(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius);
  ctx.lineWidth = 1;
  ctx.strokeStyle = "rgba(255, 255, 255, 0.13)";
  ctx.stroke();
  ctx.restore();
}

/* ---------- Format Renderers ---------- */

/**
 * 1. Tall Editorial Poster (matches the 01-reflect .. 05-layer9 signature aesthetic)
 */
async function renderTallEditorial(canvas, site, opts) {
  const img = await loadImage(site.image);
  const W = 1200;
  const PAD = 38;
  const TOP_BAR = 76;
  const FOOT_BAR = 62;
  const FRAME_W = W - PAD * 2;
  const CHROME_H = opts.showChrome ? 44 : 0;

  const naturalRatio = img.naturalHeight / img.naturalWidth;
  // Cap extreme aspect ratios while preserving generous full-page editorial height
  const targetImgH = Math.round(
    Math.min(3450, Math.max(680, FRAME_W * naturalRatio)),
  );
  const FRAME_H = CHROME_H + targetImgH;
  const H = TOP_BAR + FRAME_H + FOOT_BAR;

  canvas.width = W;
  canvas.height = H;
  const ctx = canvas.getContext("2d");

  // Obsidian studio backdrop
  ctx.fillStyle = "#08080a";
  ctx.fillRect(0, 0, W, H);

  // Subtle top ambient sheen
  const topGlow = ctx.createRadialGradient(W * 0.5, 0, 10, W * 0.5, 0, W * 0.7);
  topGlow.addColorStop(0, "rgba(129, 140, 248, 0.06)");
  topGlow.addColorStop(1, "rgba(8, 8, 10, 0)");
  ctx.fillStyle = topGlow;
  ctx.fillRect(0, 0, W, 320);

  // Header bar: [01]  Name  domain.com               [D·] designtaste.wtf
  const headY = Math.round(TOP_BAR / 2) + 2;
  let cursorX = PAD;
  ctx.textBaseline = "middle";
  if (opts.showNumber && opts.total >= 1) {
    ctx.font = '500 18px "Geist Mono", ui-monospace, monospace';
    ctx.fillStyle = "#6c6e7d";
    const numStr = pad2(opts.index + 1);
    ctx.fillText(numStr, cursorX, headY + 1);
    cursorX += ctx.measureText(numStr).width + 18;
  }

  ctx.font = '600 22px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#f5f6fa";
  const maxNameW = 540;
  let displayName = site.name || hostOf(site.url);
  while (displayName.length > 6 && ctx.measureText(displayName).width > maxNameW) {
    displayName = `${displayName.slice(0, -2)}…`;
  }
  ctx.fillText(displayName, cursorX, headY);
  cursorX += ctx.measureText(displayName).width + 14;

  const domain = hostOf(site.url);
  ctx.font = '400 18px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#696b7a";
  ctx.fillText(domain, cursorX, headY + 1);

  drawBrandLockupRight(ctx, W - PAD, headY, { markSize: 24, fontSize: 18 });

  // Framed browser capture
  drawBrowserFrame(ctx, {
    x: PAD,
    y: TOP_BAR,
    w: FRAME_W,
    h: FRAME_H,
    domain,
    img,
    showChrome: opts.showChrome,
    radius: 14,
    chromeHeight: 44,
  });

  // Footer bar
  const footY = TOP_BAR + FRAME_H + Math.round(FOOT_BAR / 2);
  ctx.font = '500 13.5px "Geist Mono", ui-monospace, monospace';
  ctx.fillStyle = "#5b5d6c";
  ctx.textBaseline = "middle";
  const footerLeft = (
    opts.editionLabel ||
    `${(site.category || "CURATED").toUpperCase()} · DESIGNTASTE`
  ).toUpperCase();
  drawTrackedText(ctx, footerLeft, PAD, footY, 1.5, "left");

  const footerRight =
    opts.showNumber && opts.total > 1
      ? `${pad2(opts.index + 1)} / ${pad2(opts.total)}`
      : BRAND_DOMAIN.toUpperCase();
  drawTrackedText(ctx, footerRight, W - PAD, footY, 1.5, "right");
}

/**
 * 2. 4:5 Carousel Slide (1080 × 1350 — LinkedIn / Instagram / X swipe thread)
 */
async function renderCarousel4x5(canvas, site, opts) {
  const img = await loadImage(site.image);
  const W = 1080;
  const H = 1350;
  const PAD = 42;
  const TOP_BAR = 84;
  const FOOT_BAR = 68;
  const FRAME_W = W - PAD * 2;
  const FRAME_H = H - TOP_BAR - FOOT_BAR;

  canvas.width = W;
  canvas.height = H;
  const ctx = canvas.getContext("2d");

  ctx.fillStyle = "#08080a";
  ctx.fillRect(0, 0, W, H);

  const glow = ctx.createRadialGradient(W * 0.25, 0, 10, W * 0.25, 0, 720);
  glow.addColorStop(0, "rgba(129, 140, 248, 0.11)");
  glow.addColorStop(1, "rgba(8, 8, 10, 0)");
  ctx.fillStyle = glow;
  ctx.fillRect(0, 0, W, H);

  // Header
  const headY = Math.round(TOP_BAR / 2) + 4;
  let cursorX = PAD;
  ctx.textBaseline = "middle";
  if (opts.showNumber && opts.total >= 1) {
    ctx.font = '500 18px "Geist Mono", ui-monospace, monospace';
    ctx.fillStyle = "#727487";
    const numStr = pad2(opts.index + 1);
    ctx.fillText(numStr, cursorX, headY + 1);
    cursorX += ctx.measureText(numStr).width + 16;
  }

  ctx.font = '600 23px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#f5f6fa";
  const domain = hostOf(site.url);
  let displayName = site.name || domain;
  while (displayName.length > 6 && ctx.measureText(displayName).width > 420) {
    displayName = `${displayName.slice(0, -2)}…`;
  }
  ctx.fillText(displayName, cursorX, headY);
  cursorX += ctx.measureText(displayName).width + 12;

  ctx.font = '400 18px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#6c6e7f";
  ctx.fillText(domain, cursorX, headY + 1);

  drawBrandLockupRight(ctx, W - PAD, headY, { markSize: 24, fontSize: 18 });

  drawBrowserFrame(ctx, {
    x: PAD,
    y: TOP_BAR,
    w: FRAME_W,
    h: FRAME_H,
    domain,
    img,
    showChrome: opts.showChrome,
    radius: 16,
    chromeHeight: 42,
  });

  // Footer
  const footY = TOP_BAR + FRAME_H + Math.round(FOOT_BAR / 2);
  ctx.font = '500 13.5px "Geist Mono", ui-monospace, monospace';
  ctx.fillStyle = "#606273";
  ctx.textBaseline = "middle";
  const footerLeft = (
    opts.editionLabel ||
    `${(site.category || "CURATED").toUpperCase()} · DESIGNTASTE`
  ).toUpperCase();
  drawTrackedText(ctx, footerLeft, PAD, footY, 1.5, "left");

  const footerRight =
    opts.showNumber && opts.total > 1
      ? `${pad2(opts.index + 1)} / ${pad2(opts.total)}`
      : BRAND_DOMAIN.toUpperCase();
  drawTrackedText(ctx, footerRight, W - PAD, footY, 1.5, "right");
}

/**
 * 3. 16:9 X / LinkedIn Feed Card (1600 × 900)
 */
async function renderFeed16x9(canvas, site, opts) {
  const img = await loadImage(site.image);
  const W = 1600;
  const H = 900;
  canvas.width = W;
  canvas.height = H;
  const ctx = canvas.getContext("2d");

  ctx.fillStyle = "#08080a";
  ctx.fillRect(0, 0, W, H);

  // Subtle iris + rose ambient studio glow
  const g1 = ctx.createRadialGradient(W * 0.16, H * 0.1, 10, W * 0.16, H * 0.1, 780);
  g1.addColorStop(0, "rgba(129, 140, 248, 0.16)");
  g1.addColorStop(1, "rgba(8, 8, 10, 0)");
  ctx.fillStyle = g1;
  ctx.fillRect(0, 0, W, H);

  const g2 = ctx.createRadialGradient(W * 0.88, H * 0.95, 10, W * 0.88, H * 0.95, 620);
  g2.addColorStop(0, "rgba(255, 77, 109, 0.11)");
  g2.addColorStop(1, "rgba(8, 8, 10, 0)");
  ctx.fillStyle = g2;
  ctx.fillRect(0, 0, W, H);

  // Left editorial column
  const LEFT_X = 68;
  const LEFT_W = 450;
  const domain = hostOf(site.url);

  // Top brand lockup on left
  drawBrandMark(ctx, LEFT_X, 66, 30);
  ctx.textBaseline = "middle";
  ctx.font = '600 20px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#f4f5fa";
  ctx.fillText("designtaste", LEFT_X + 41, 82);
  const bw = ctx.measureText("designtaste").width;
  ctx.fillStyle = "#7c7e90";
  ctx.fillText(".wtf", LEFT_X + 41 + bw, 82);

  // Category pill
  const pillText = (site.category || "Curated").toUpperCase();
  ctx.font = '600 12px "Geist Mono", ui-monospace, monospace';
  const pw = ctx.measureText(pillText).width + 26;
  roundRectPath(ctx, LEFT_X, 232, pw, 30, 15);
  ctx.fillStyle = "rgba(129, 140, 248, 0.16)";
  ctx.fill();
  ctx.lineWidth = 1;
  ctx.strokeStyle = "rgba(165, 180, 252, 0.35)";
  ctx.stroke();
  ctx.fillStyle = "#d3dcff";
  ctx.fillText(pillText, LEFT_X + 13, 248);

  // Site headline
  ctx.font = '660 54px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#ffffff";
  const nameLines = drawWrappedLines(ctx, site.name || domain, LEFT_X, 316, LEFT_W, 60, 2);

  // Domain
  const afterNameY = 316 + nameLines * 60 + 6;
  ctx.font = '450 22px "Geist Mono", ui-monospace, monospace';
  ctx.fillStyle = "#8a8c9f";
  ctx.fillText(domain, LEFT_X, afterNameY);

  // Design observation
  const noteText = site.note || site.description || "";
  if (noteText) {
    ctx.font = '420 21px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
    ctx.fillStyle = "#b5b7c8";
    drawWrappedLines(ctx, noteText, LEFT_X, afterNameY + 54, LEFT_W, 32, 4);
  }

  // Bottom footer left
  ctx.font = '500 13px "Geist Mono", ui-monospace, monospace';
  ctx.fillStyle = "#626476";
  const footerLeft = (
    opts.editionLabel || "CURATED WEB DESIGN TASTE"
  ).toUpperCase();
  drawTrackedText(ctx, footerLeft, LEFT_X, H - 56, 1.4, "left");
  if (opts.showNumber && opts.total > 1) {
    drawTrackedText(
      ctx,
      `${pad2(opts.index + 1)} / ${pad2(opts.total)}`,
      LEFT_X,
      H - 84,
      1.4,
      "left",
    );
  }

  // Right framed browser showcase
  drawBrowserFrame(ctx, {
    x: 564,
    y: 66,
    w: 970,
    h: 768,
    domain,
    img,
    showChrome: opts.showChrome,
    radius: 18,
    chromeHeight: 42,
  });
}

/**
 * 4. 2×2 Contact Sheet Grid (1600 × 1040 — Edition mode multi-site single-image X banger)
 */
async function renderGrid2x2(canvas, sites, opts) {
  const picked = sites.slice(0, 4);
  const imgs = await Promise.all(picked.map((s) => loadImage(s.image)));

  const W = 1600;
  const H = 1040;
  const PAD = 48;
  const TOP_BAR = 92;
  const FOOT_BAR = 58;
  const GAP = 24;

  canvas.width = W;
  canvas.height = H;
  const ctx = canvas.getContext("2d");

  ctx.fillStyle = "#08080a";
  ctx.fillRect(0, 0, W, H);

  const g1 = ctx.createRadialGradient(W * 0.22, 0, 10, W * 0.22, 0, 820);
  g1.addColorStop(0, "rgba(129, 140, 248, 0.14)");
  g1.addColorStop(1, "rgba(8, 8, 10, 0)");
  ctx.fillStyle = g1;
  ctx.fillRect(0, 0, W, H);

  // Header
  ctx.textBaseline = "middle";
  const title = (opts.editionLabel || "CURATED EDITION").toUpperCase();
  ctx.font = '600 22px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
  ctx.fillStyle = "#f5f6fa";
  ctx.fillText(title, PAD, TOP_BAR / 2 + 2);

  drawBrandLockupRight(ctx, W - PAD, TOP_BAR / 2 + 2, { markSize: 26, fontSize: 19 });

  const cols = picked.length === 1 ? 1 : 2;
  const rows = picked.length <= 2 ? 1 : 2;
  const cellW = Math.floor((W - PAD * 2 - GAP * (cols - 1)) / cols);
  const cellH = Math.floor((H - TOP_BAR - FOOT_BAR - GAP * (rows - 1)) / rows);

  picked.forEach((site, idx) => {
    const col = idx % cols;
    const row = Math.floor(idx / cols);
    const cx = PAD + col * (cellW + GAP);
    const cy = TOP_BAR + row * (cellH + GAP);
    const labelH = 30;
    const domain = hostOf(site.url);

    // Mini caption bar above each cell
    ctx.font = '500 13px "Geist Mono", ui-monospace, monospace';
    ctx.fillStyle = "#6d6f80";
    ctx.fillText(pad2(idx + 1), cx + 2, cy + 12);
    ctx.font = '600 16px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
    ctx.fillStyle = "#f0f1f6";
    ctx.fillText(site.name || domain, cx + 30, cy + 12);
    const nw = ctx.measureText(site.name || domain).width;
    ctx.font = '400 14px "Geist", -apple-system, BlinkMacSystemFont, sans-serif';
    ctx.fillStyle = "#6d6f80";
    ctx.fillText(domain, cx + 30 + nw + 10, cy + 12);

    drawBrowserFrame(ctx, {
      x: cx,
      y: cy + labelH,
      w: cellW,
      h: cellH - labelH,
      domain,
      img: imgs[idx],
      showChrome: opts.showChrome,
      radius: 12,
      chromeHeight: 32,
    });
  });

  // Footer
  const footY = H - Math.round(FOOT_BAR / 2);
  ctx.font = '500 13px "Geist Mono", ui-monospace, monospace';
  ctx.fillStyle = "#5f6171";
  drawTrackedText(
    ctx,
    `${picked.length} CURATED WEBSITES · ${BRAND_DOMAIN.toUpperCase()}`,
    PAD,
    footY,
    1.5,
    "left",
  );
  drawTrackedText(
    ctx,
    `01–${pad2(picked.length)}`,
    W - PAD,
    footY,
    1.5,
    "right",
  );
}

export async function renderShareCanvas(canvas, sites, opts) {
  if (document.fonts?.ready) {
    try {
      await document.fonts.ready;
    } catch {
      // continue with fallback fonts
    }
  }
  const format = opts.format || "tall";
  const activeSite = sites[opts.index || 0] || sites[0];
  if (format === "grid" && sites.length > 1) {
    await renderGrid2x2(canvas, sites, opts);
    return;
  }
  if (format === "carousel") {
    await renderCarousel4x5(canvas, activeSite, opts);
    return;
  }
  if (format === "feed") {
    await renderFeed16x9(canvas, activeSite, opts);
    return;
  }
  await renderTallEditorial(canvas, activeSite, opts);
}

/* ---------- Zero-Dependency Uncompressed ZIP Writer (STORE method 0) ---------- */
const CRC_TABLE = (() => {
  const t = new Uint32Array(256);
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) {
      c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    }
    t[n] = c >>> 0;
  }
  return t;
})();

function crc32(bytes) {
  let c = 0xffffffff;
  for (let i = 0; i < bytes.length; i++) {
    c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
  }
  return (c ^ 0xffffffff) >>> 0;
}

function buildZipBlob(files) {
  const encoder = new TextEncoder();
  const localParts = [];
  const centralParts = [];
  let offset = 0;

  for (const file of files) {
    const nameBytes = encoder.encode(file.name);
    const data = file.bytes;
    const crc = crc32(data);
    const size = data.length;

    const localHeader = new Uint8Array(30 + nameBytes.length);
    const lv = new DataView(localHeader.buffer);
    lv.setUint32(0, 0x04034b50, true);
    lv.setUint16(4, 20, true);
    lv.setUint16(6, 0x0800, true); // UTF-8 flag
    lv.setUint16(8, 0, true); // STORE (no recompression needed for PNG/JPG)
    lv.setUint32(14, crc, true);
    lv.setUint32(18, size, true);
    lv.setUint32(22, size, true);
    lv.setUint16(26, nameBytes.length, true);
    localHeader.set(nameBytes, 30);

    localParts.push(localHeader, data);

    const centralHeader = new Uint8Array(46 + nameBytes.length);
    const cv = new DataView(centralHeader.buffer);
    cv.setUint32(0, 0x02014b50, true);
    cv.setUint16(4, 20, true);
    cv.setUint16(6, 20, true);
    cv.setUint16(8, 0x0800, true);
    cv.setUint16(10, 0, true);
    cv.setUint32(16, crc, true);
    cv.setUint32(20, size, true);
    cv.setUint32(24, size, true);
    cv.setUint16(28, nameBytes.length, true);
    cv.setUint32(42, offset, true);
    centralHeader.set(nameBytes, 46);
    centralParts.push(centralHeader);

    offset += localHeader.length + data.length;
  }

  let centralSize = 0;
  for (const p of centralParts) centralSize += p.length;

  const endRecord = new Uint8Array(22);
  const ev = new DataView(endRecord.buffer);
  ev.setUint32(0, 0x06054b50, true);
  ev.setUint16(8, files.length, true);
  ev.setUint16(10, files.length, true);
  ev.setUint32(12, centralSize, true);
  ev.setUint32(16, offset, true);

  return new Blob([...localParts, ...centralParts, endRecord], {
    type: "application/zip",
  });
}

function canvasToBlob(canvas, type = "image/png", quality = 0.94) {
  return new Promise((resolve, reject) => {
    canvas.toBlob(
      (blob) => (blob ? resolve(blob) : reject(new Error("Canvas export failed"))),
      type,
      quality,
    );
  });
}

function triggerDownload(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 4000);
}

/* ---------- Interactive Share Studio Modal ---------- */
let modalEl = null;
let state = {
  sites: [],
  index: 0,
  format: "tall",
  showChrome: true,
  showNumber: true,
  editionLabel: "",
  renderSeq: 0,
};

function ensureModal() {
  if (modalEl) return modalEl;

  const dialog = document.createElement("dialog");
  dialog.id = "share-studio-modal";
  dialog.className = "share-studio-dialog";
  dialog.setAttribute("aria-labelledby", "share-studio-title");

  dialog.innerHTML = `
    <div class="share-studio-panel">
      <div class="share-studio-head">
        <div>
          <p class="eyebrow" id="share-studio-eyebrow">Branded Share Card</p>
          <h2 id="share-studio-title">Export for X, LinkedIn, or Figma</h2>
        </div>
        <button type="button" class="icon-close" data-close-studio aria-label="Close share studio">
          <svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
        </button>
      </div>

      <div class="share-studio-body">
        <div class="share-studio-stage">
          <div class="share-studio-canvas-wrap">
            <canvas id="share-studio-canvas" class="share-studio-canvas"></canvas>
            <div id="share-studio-loading" class="share-studio-loading" hidden>Rendering high-res card…</div>
          </div>
          <div id="share-studio-slides" class="share-studio-slides" hidden></div>
        </div>

        <aside class="share-studio-controls">
          <div class="studio-group">
            <span class="studio-label">Format</span>
            <div class="studio-seg" role="group" aria-label="Export format">
              <button type="button" class="studio-seg-btn is-active" data-studio-format="tall">Tall poster</button>
              <button type="button" class="studio-seg-btn" data-studio-format="carousel">4:5 slide</button>
              <button type="button" class="studio-seg-btn" data-studio-format="feed">16:9 feed</button>
              <button type="button" class="studio-seg-btn" data-studio-format="grid" id="studio-grid-btn" hidden>2×2 grid</button>
            </div>
          </div>

          <div class="studio-group">
            <label class="studio-label" for="studio-edition-label">Footer / Edition label</label>
            <input id="studio-edition-label" class="studio-input" type="text" maxlength="64" placeholder="DARK WEB DESIGN · EDITION 01">
          </div>

          <div class="studio-toggles">
            <label class="studio-check">
              <input id="studio-chrome-toggle" type="checkbox" checked>
              <span>macOS browser frame</span>
            </label>
            <label class="studio-check">
              <input id="studio-number-toggle" type="checkbox" checked>
              <span>Editorial index (01 / 05)</span>
            </label>
          </div>

          <div class="studio-actions">
            <button type="button" class="btn btn-primary" id="studio-copy-btn">Copy image</button>
            <button type="button" class="btn btn-ghost" id="studio-download-btn">Download PNG</button>
            <button type="button" class="btn btn-ghost" id="studio-zip-btn" hidden>Download all (.zip)</button>
            <a class="btn btn-ghost" id="studio-x-btn" target="_blank" rel="noopener">Post on X ↗</a>
          </div>

          <p class="studio-status" id="studio-status" role="status" aria-live="polite" hidden></p>
          <p class="studio-hint">Rendered locally at full resolution with zero watermarks cropped out — paste straight into X, Slack, or Figma.</p>
        </aside>
      </div>
    </div>
  `;

  document.body.appendChild(dialog);
  modalEl = dialog;

  const closeBtn = dialog.querySelector("[data-close-studio]");
  closeBtn.addEventListener("click", () => dialog.close());
  dialog.addEventListener("click", (e) => {
    if (e.target === dialog) dialog.close();
  });

  for (const btn of dialog.querySelectorAll("[data-studio-format]")) {
    btn.addEventListener("click", () => {
      state.format = btn.dataset.studioFormat;
      syncControls();
      rerender();
    });
  }

  const labelInput = dialog.querySelector("#studio-edition-label");
  let labelTimer;
  labelInput.addEventListener("input", () => {
    state.editionLabel = labelInput.value;
    clearTimeout(labelTimer);
    labelTimer = setTimeout(rerender, 120);
  });

  dialog.querySelector("#studio-chrome-toggle").addEventListener("change", (e) => {
    state.showChrome = e.target.checked;
    rerender();
  });
  dialog.querySelector("#studio-number-toggle").addEventListener("change", (e) => {
    state.showNumber = e.target.checked;
    rerender();
  });

  dialog.querySelector("#studio-copy-btn").addEventListener("click", copyActiveImage);
  dialog.querySelector("#studio-download-btn").addEventListener("click", downloadActiveImage);
  dialog.querySelector("#studio-zip-btn").addEventListener("click", downloadEditionZip);

  return dialog;
}

function setStatus(msg, isError = false) {
  const el = modalEl?.querySelector("#studio-status");
  if (!el) return;
  if (!msg) {
    el.hidden = true;
    el.textContent = "";
    return;
  }
  el.hidden = false;
  el.className = `studio-status${isError ? " is-error" : ""}`;
  el.textContent = msg;
}

function syncControls() {
  if (!modalEl) return;
  const isEdition = state.sites.length > 1;
  modalEl.querySelector("#share-studio-eyebrow").textContent = isEdition
    ? `Edition Exporter · ${state.sites.length} slides`
    : "Branded Share Card";
  modalEl.querySelector("#share-studio-title").textContent = isEdition
    ? "Export numbered edition"
    : `Share ${state.sites[0]?.name || "website"}`;

  const gridBtn = modalEl.querySelector("#studio-grid-btn");
  gridBtn.hidden = !isEdition;
  if (!isEdition && state.format === "grid") state.format = "tall";

  for (const btn of modalEl.querySelectorAll("[data-studio-format]")) {
    btn.classList.toggle("is-active", btn.dataset.studioFormat === state.format);
  }

  const labelInput = modalEl.querySelector("#studio-edition-label");
  if (labelInput.value !== state.editionLabel) labelInput.value = state.editionLabel;

  modalEl.querySelector("#studio-chrome-toggle").checked = state.showChrome;
  modalEl.querySelector("#studio-number-toggle").checked = state.showNumber;

  const zipBtn = modalEl.querySelector("#studio-zip-btn");
  zipBtn.hidden = !isEdition || state.format === "grid";
  zipBtn.textContent = `Download all ${state.sites.length} (.zip)`;

  const dlBtn = modalEl.querySelector("#studio-download-btn");
  dlBtn.textContent =
    state.format === "grid"
      ? "Download 2×2 PNG"
      : isEdition
        ? `Download slide ${pad2(state.index + 1)}`
        : "Download PNG";

  // Pre-filled X intent link
  const xBtn = modalEl.querySelector("#studio-x-btn");
  const active = state.sites[state.index] || state.sites[0];
  const tweetText = isEdition
    ? `${state.editionLabel || `${state.sites.length} standout web designs`} — curated on designtaste.wtf`
    : `${active?.name || "Great web design"} — found on designtaste.wtf`;
  const sharePageUrl = isEdition
    ? location.href
    : `https://${BRAND_DOMAIN}/sites/${active?.id || ""}/`;
  xBtn.href = `https://x.com/intent/tweet?text=${encodeURIComponent(tweetText)}&url=${encodeURIComponent(sharePageUrl)}`;

  // Slide switcher pills in Edition mode
  const slidesEl = modalEl.querySelector("#share-studio-slides");
  slidesEl.hidden = !isEdition || state.format === "grid";
  if (isEdition && state.format !== "grid") {
    slidesEl.replaceChildren();
    state.sites.forEach((s, idx) => {
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = `studio-slide-pill${idx === state.index ? " is-active" : ""}`;
      btn.textContent = `${pad2(idx + 1)} ${s.name}`;
      btn.addEventListener("click", () => {
        state.index = idx;
        syncControls();
        rerender();
      });
      slidesEl.appendChild(btn);
    });
  }
}

async function rerender() {
  if (!modalEl || !state.sites.length) return;
  const seq = ++state.renderSeq;
  const canvas = modalEl.querySelector("#share-studio-canvas");
  const loading = modalEl.querySelector("#share-studio-loading");
  loading.hidden = false;
  setStatus("");

  try {
    await renderShareCanvas(canvas, state.sites, {
      index: state.index,
      total: state.sites.length,
      format: state.format,
      showChrome: state.showChrome,
      showNumber: state.showNumber,
      editionLabel: state.editionLabel.trim(),
    });
    if (seq !== state.renderSeq) return;
  } catch (err) {
    if (seq === state.renderSeq) {
      setStatus(err?.message || "Could not render preview.", true);
    }
  } finally {
    if (seq === state.renderSeq) loading.hidden = true;
  }
}

async function copyActiveImage() {
  const canvas = modalEl?.querySelector("#share-studio-canvas");
  const btn = modalEl?.querySelector("#studio-copy-btn");
  if (!canvas || !btn) return;
  const prev = btn.textContent;
  btn.disabled = true;
  btn.textContent = "Copying…";
  try {
    const blob = await canvasToBlob(canvas, "image/png");
    if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
      await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
      setStatus("Copied PNG to clipboard — paste straight into X, Slack, or Figma.");
      btn.textContent = "Copied!";
    } else {
      triggerDownload(blob, activeFilename());
      setStatus("Clipboard image copy isn't supported in this browser — downloaded PNG instead.");
      btn.textContent = "Downloaded";
    }
  } catch {
    const blob = await canvasToBlob(canvas, "image/png");
    triggerDownload(blob, activeFilename());
    setStatus("Downloaded PNG (browser blocked direct image clipboard access).");
    btn.textContent = "Downloaded";
  } finally {
    setTimeout(() => {
      btn.disabled = false;
      btn.textContent = prev;
    }, 1500);
  }
}

function activeFilename() {
  if (state.format === "grid") {
    return `${slugify(state.editionLabel || "designtaste-edition")}-grid.png`;
  }
  const site = state.sites[state.index] || state.sites[0];
  const prefix = state.sites.length > 1 ? `${pad2(state.index + 1)}-` : "";
  return `${prefix}${slugify(site?.id || site?.name || "site")}-designtaste.png`;
}

async function downloadActiveImage() {
  const canvas = modalEl?.querySelector("#share-studio-canvas");
  if (!canvas) return;
  const blob = await canvasToBlob(canvas, "image/png");
  triggerDownload(blob, activeFilename());
  setStatus(`Saved ${activeFilename()}`);
}

async function downloadEditionZip() {
  const btn = modalEl?.querySelector("#studio-zip-btn");
  if (!btn || state.sites.length < 2) return;
  const prev = btn.textContent;
  btn.disabled = true;
  const offscreen = document.createElement("canvas");
  const files = [];

  try {
    for (let i = 0; i < state.sites.length; i++) {
      btn.textContent = `Rendering ${i + 1} / ${state.sites.length}…`;
      await renderShareCanvas(offscreen, state.sites, {
        index: i,
        total: state.sites.length,
        format: state.format,
        showChrome: state.showChrome,
        showNumber: state.showNumber,
        editionLabel: state.editionLabel.trim(),
      });
      const blob = await canvasToBlob(offscreen, "image/png");
      const bytes = new Uint8Array(await blob.arrayBuffer());
      const site = state.sites[i];
      files.push({
        name: `${pad2(i + 1)}-${slugify(site.id || site.name)}.png`,
        bytes,
      });
    }
    const zipBlob = buildZipBlob(files);
    const zipName = `${slugify(state.editionLabel || "designtaste-edition")}.zip`;
    triggerDownload(zipBlob, zipName);
    setStatus(`Downloaded ${zipName} (${files.length} branded PNGs).`);
  } catch (err) {
    setStatus(err?.message || "Could not build edition archive.", true);
  } finally {
    btn.disabled = false;
    btn.textContent = prev;
  }
}

export function openShareStudio({ sites, editionLabel = "", format = "tall" }) {
  const clean = (sites || []).filter((s) => s && s.image).slice(0, MAX_EDITION_SLIDES);
  if (!clean.length) return;
  const dialog = ensureModal();
  state.sites = clean;
  state.index = 0;
  state.format = format;
  state.showChrome = true;
  state.showNumber = clean.length > 1;
  state.editionLabel =
    editionLabel ||
    (clean.length > 1
      ? `DESIGNTASTE · EDITION 01`
      : `${(clean[0].category || "CURATED").toUpperCase()} · DESIGNTASTE`);

  syncControls();
  if (typeof dialog.showModal === "function") {
    dialog.showModal();
  } else {
    dialog.setAttribute("open", "");
  }
  rerender();
}

function siteFromCard(card) {
  return {
    id: card.dataset.id || "",
    name: card.dataset.name || card.querySelector(".site-name")?.textContent?.trim() || "",
    url: card.dataset.url || card.querySelector(".site-name")?.href || "",
    category: card.dataset.category || "",
    image: card.dataset.image || "",
    note: card.dataset.note || "",
  };
}

function defaultEditionLabel(sites, explicitTitle = "") {
  const cleanTitle = String(explicitTitle || "").trim();
  if (cleanTitle && cleanTitle.toLowerCase() !== "shared list") {
    return `${cleanTitle.toUpperCase()} · EDITION 01`;
  }
  const cats = [...new Set(sites.map((s) => s.category).filter(Boolean))];
  if (cats.length === 1) {
    return `${cats[0].toUpperCase()} · EDITION 01`;
  }
  return "DESIGNTASTE · EDITION 01";
}

if (typeof document !== "undefined") {
  document.addEventListener("click", (e) => {
    const shareBtn = e.target.closest("[data-share-site]");
    if (shareBtn) {
      e.preventDefault();
      openShareStudio({
        sites: [
          {
            id: shareBtn.dataset.siteId || "",
            name: shareBtn.dataset.siteName || "",
            url: shareBtn.dataset.siteUrl || "",
            category: shareBtn.dataset.siteCategory || "",
            image: shareBtn.dataset.siteImage || "",
            note: shareBtn.dataset.siteNote || "",
          },
        ],
      });
      return;
    }

    const editionBtn = e.target.closest("[data-export-edition]");
    if (editionBtn) {
      e.preventDefault();
      const visibleCards = [
        ...document.querySelectorAll(".site-card:not([hidden])"),
      ];
      const picked = visibleCards.map(siteFromCard).filter((s) => s.image);
      if (!picked.length) return;
      const mode = editionBtn.dataset.exportEdition;
      const explicitTitle =
        mode === "shared"
          ? document.querySelector("#shared-list-title")?.textContent || ""
          : document.querySelector("#share-list-title")?.value || "";
      openShareStudio({
        sites: picked,
        editionLabel: defaultEditionLabel(picked, explicitTitle),
      });
    }
  });
}