// Logo tile — renders one of three things for a tool, in priority order:
//   1. tool.logoUrl   — a raster/svg image (PNG/JPG/SVG) inside a tile
//   2. tool.iconSvg   — inline SVG markup (auto-namespaced IDs to avoid collisions)
//   3. monogram fallback — gradient tile with letters

function namespaceSvgIds(svg, slug) {
  // Rewrite every id="X" and url(#X) to id="slug-X" / url(#slug-X)
  // so multiple SVGs on the page can reuse short ids like "a", "b" safely.
  const ids = new Set();
  svg.replace(/\sid="([^"]+)"/g, (_, id) => {
    ids.add(id);
  });
  let out = svg;
  ids.forEach((id) => {
    const safe = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    out = out.replace(new RegExp(`(\\s)id="${safe}"`, "g"), `$1id="${slug}-${id}"`);
    out = out.replace(new RegExp(`url\\(#${safe}\\)`, "g"), `url(#${slug}-${id})`);
    out = out.replace(new RegExp(`href="#${safe}"`, "g"), `href="#${slug}-${id}"`);
    out = out.replace(new RegExp(`xlink:href="#${safe}"`, "g"), `xlink:href="#${slug}-${id}"`);
  });
  return out;
}

function LogoTile({ tool, size = 48, radius }) {
  const r = radius ?? Math.round(size * 0.22);
  const fullBleed = tool.logoFullBleed;
  const bg = fullBleed ? "transparent" : (tool.logoBg || "#ffffff");
  const pad = fullBleed ? 0 : Math.round(size * 0.14);
  const inner = size - pad * 2;

  const tileStyle = {
    width: size,
    height: size,
    borderRadius: r,
    background: bg,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: pad,
    boxSizing: "border-box",
    boxShadow: fullBleed ? "none" : "inset 0 0 0 1px rgba(0,0,0,0.05)",
    flexShrink: 0,
    overflow: "hidden",
  };

  // Raster / file image
  const logoUrl = tool.logoUrl || (tool.logoFile ? `assets/${tool.logoFile}` : null);
  if (logoUrl) {
    return (
      <div style={tileStyle}>
        <img
          src={logoUrl}
          alt={tool.name}
          style={{
            width: inner,
            height: inner,
            objectFit: "contain",
            display: "block",
          }}
        />
      </div>
    );
  }

  // Inline SVG
  if (tool.iconSvg) {
    const slug = tool.name.toLowerCase().replace(/[^a-z0-9]/g, "");
    const safeSvg = namespaceSvgIds(tool.iconSvg, slug).replace(
      /<svg([^>]*?)>/,
      `<svg$1 width="${inner}" height="${inner}" style="display:block">`
    );
    return (
      <div style={tileStyle} dangerouslySetInnerHTML={{ __html: safeSvg }} />
    );
  }

  // Monogram fallback
  const [c1, c2] = tool.swatch || ["#475569", "#94a3b8"];
  const gradId = `g-${tool.name.replace(/[^a-z0-9]/gi, "")}`;
  const fontSize = tool.monogram.length >= 3 ? size * 0.34 : size * 0.42;
  return (
    <svg
      width={size}
      height={size}
      viewBox={`0 0 ${size} ${size}`}
      aria-hidden="true"
      style={{ flexShrink: 0, display: "block" }}
    >
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={c1} />
          <stop offset="100%" stopColor={c2} />
        </linearGradient>
      </defs>
      <rect width={size} height={size} rx={r} ry={r} fill={`url(#${gradId})`} />
      <text
        x="50%"
        y="50%"
        textAnchor="middle"
        dominantBaseline="central"
        fontFamily="'Inter', 'Helvetica Neue', system-ui"
        fontSize={fontSize}
        fontWeight={700}
        fill="rgba(255,255,255,0.96)"
        letterSpacing={tool.monogram.length >= 3 ? -0.5 : 0}
      >
        {tool.monogram}
      </text>
    </svg>
  );
}

window.LogoTile = LogoTile;
