// src/components/pinIcon.ts
import L from 'leaflet';

/**
 * Build a glossy pin as an SVG data-URI with an optional centered image (PNG/SVG).
 * - No external SVG file needed.
 * - Scales crisply to any size.
 * - Has a soft shadow and a subtle inner highlight.
 *
 * @param color         Pin fill color (e.g. "#2E86FF" or "FF6600" or "tomato"). Null uses default.
 * @param sizePx        Target width in px (height scales 80:100).
 * @param centerImgUrl  Optional inner square icon (e.g. "/icon8/MLD24.png")
 */
export function pinIcon(
  color: string | null,
  sizePx = 28,
  centerImgUrl?: string,
): L.Icon {
  // normalize color
  let fill = '#2E86FF';
  if (color) fill = /^[0-9A-Fa-f]{6}$/.test(color) ? `#${color}` : color;
  const viewW = 80; // width of the viewBox
  const viewH = 100; // height of the viewBox
  const width = sizePx;
  const height = Math.round((sizePx / viewW) * viewH);

  // anchors: bottom-center, nice for pins
  const iconAnchor: [number, number] = [Math.round(width / 2), height - 2];
  const popupAnchor: [number, number] = [0, -height + 10];

  // inner image size (in *viewBox* units) relative to pin width
  const innerVw = 40; // Adjusted for better fit
  const cx = viewW / 2;
  const cy = 34; // sweet-spot inside head
  const x = cx - innerVw / 2;
  const y = cy - innerVw / 2;
  const safeHref = centerImgUrl ? centerImgUrl : null;

  // SVG pin path (classic teardrop), soft shadow, white ring, inner highlight
  const svg = `
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${viewW} ${viewH}" width="${width}" height="${height}">
    <defs>
      <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
        <feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="#000" flood-opacity="0.25"/>
      </filter>
      <clipPath id="circle-clip">
        <circle cx="${cx}" cy="${cy}" r="${innerVw / 2}" />
      </clipPath>
    </defs>

    <!-- pin body -->
    <g filter="url(#shadow)">
      <path d="
        M ${cx},2
        C ${cx - 18},2 ${cx - 32},16 ${cx - 32},34
        C ${cx - 32},60 ${cx},98 ${cx},98
        C ${cx},98 ${cx + 32},60 ${cx + 32},34
        C ${cx + 32},16 ${cx + 18},2 ${cx},2
        Z
      " fill="${fill}" />

      <!-- subtle white ring around the head -->
      <circle cx="${cx}" cy="${cy}" r="${innerVw / 2 + 6}" fill="none" stroke="white" stroke-opacity="0.6" stroke-width="2"/>

      <!-- soft top highlight -->
      <ellipse cx="${cx}" cy="${cy - 10}" rx="${innerVw * 0.7}" ry="${innerVw * 0.45}"
               fill="white" opacity="0.18"/>
    </g>

    ${
      safeHref
        ? `<image href="${safeHref}" x="${x}" y="${y}" width="${innerVw}" height="${innerVw}"
                  preserveAspectRatio="xMidYMid slice" clip-path="url(#circle-clip)"/>`
        : ''
    }
  </svg>`.trim();

  const iconUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;

  return L.icon({
    iconUrl,
    iconSize: [width, height],
    iconAnchor,
    popupAnchor,
  });
}
