// Preview SVG del pastel — pisos apilables con colores dinámicos
const { useMemo } = React;

function CakePreview({ tiers }) {
  // tiers: array de { flavorColor, color (hex), tierType }
  // Piso 1 = base (más grande), piso N = arriba (más chico)
  const data = useMemo(() => {
    const n = tiers.length;
    if (n === 0) return [];
    // Width scaling: base piso width depends on n; smaller cakes are narrower
    const baseMax = 280;
    const maxW = n === 1 ? 180 : Math.min(baseMax, 140 + n * 24);
    const minW = Math.max(70, maxW - 50 - (n - 1) * 14);
    const widthStep = n === 1 ? 0 : (maxW - minW) / (n - 1);
    const baseH = 70;
    const heightStep = 5;
    return tiers.map((t, i) => {
      const w = maxW - i * widthStep;
      let h = baseH - i * heightStep;
      if (t.tierType === "doble") h = h * 1.55;
      if (t.tierType === "extendido") h = h * 1.25;
      const fillRaw = t.color || "#F8EFD9";
      // Si el color es muy claro (cerca de blanco), usar contorno fuerte
      return {
        w, h,
        flavorColor: t.flavorColor || "#F4E4BC",
        color: fillRaw,
      };
    });
  }, [tiers]);

  const totalH = data.reduce((s, d) => s + d.h + 4, 0) + 40;
  const cx = 175;
  let yCursor = totalH - 24;
  const vbH = Math.max(totalH + 20, 280);

  return (
    <svg viewBox={`0 0 350 ${vbH}`} className="cake-svg">
      <defs>
        <linearGradient id="plateGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#4a4a4a" />
          <stop offset="1" stopColor="#1a1a1a" />
        </linearGradient>
      </defs>

      {/* sombra suelo */}
      <ellipse cx={cx} cy={totalH - 4} rx={150} ry={6} fill="#1a1a1a" opacity="0.12" />

      {/* plato */}
      <ellipse cx={cx} cy={totalH - 14} rx={155} ry={7} fill="url(#plateGrad)" />
      <ellipse cx={cx} cy={totalH - 17} rx={155} ry={5} fill="#1a1a1a" />

      {/* pisos: stack desde abajo */}
      {data.map((d, i) => {
        const y = yCursor - d.h - 4;
        yCursor = y;
        const x = cx - d.w / 2;
        const ry = 4;
        return (
          <g key={i}>
            {/* sombra lateral */}
            <rect
              x={x}
              y={y}
              width={d.w}
              height={d.h}
              fill={d.color}
              stroke="#2a2a2a"
              strokeWidth="1.2"
              rx={ry}
              ry={ry}
            />
            {/* highlight superior */}
            <ellipse
              cx={cx}
              cy={y + 2}
              rx={d.w / 2}
              ry={4}
              fill={d.color}
              stroke="#2a2a2a"
              strokeWidth="1.2"
            />
            {/* sombra interior (banda de relleno = sabor del pan) */}
            <rect
              x={x + 2}
              y={y + d.h * 0.55}
              width={d.w - 4}
              height={Math.max(4, d.h * 0.08)}
              fill={d.flavorColor}
              opacity="0.85"
            />
            {/* gotitas decorativas en la base del piso */}
            {(() => {
              const count = Math.max(4, Math.floor(d.w / 26));
              return Array.from({ length: count }).map((_, k) => {
                const px = x + (k + 0.5) * (d.w / count);
                return (
                  <g key={k}>
                    <path
                      d={`M ${px - 5} ${y + d.h} q 0 -6 5 -6 q 5 0 5 6 z`}
                      fill={d.color}
                      stroke="#2a2a2a"
                      strokeWidth="0.9"
                    />
                  </g>
                );
              });
            })()}
            {/* etiqueta del piso */}
            <text
              x={x - 10}
              y={y + d.h / 2}
              fontSize="10"
              fontFamily="ui-monospace, monospace"
              textAnchor="end"
              fill="#6e6e6e"
              dominantBaseline="middle"
            >
              {data.length - i}
            </text>
          </g>
        );
      })}

      {/* coronita estilo logo en el último piso (arriba) */}
      {data.length > 0 && (() => {
        const topW = data[data.length - 1].w;
        const cy = yCursor - 10;
        const scale = topW < 110 ? 0.7 : 1;
        return (
          <g transform={`translate(${cx}, ${cy}) scale(${scale})`}>
            <path
              d="M -22 6 L -22 -2 L -14 -12 L -7 -4 L 0 -16 L 7 -4 L 14 -12 L 22 -2 L 22 6 Z"
              fill="#F2B233"
              stroke="#1a1a1a"
              strokeWidth="1.4"
              strokeLinejoin="round"
            />
            <ellipse cx="-14" cy="-13" rx="2" ry="3" fill="#F2B233" />
            <ellipse cx="0" cy="-17" rx="2.2" ry="3.4" fill="#F2B233" />
            <ellipse cx="14" cy="-13" rx="2" ry="3" fill="#F2B233" />
          </g>
        );
      })()}
    </svg>
  );
}

window.CakePreview = CakePreview;
