// Success Fee animated chart — fixed cost crosses success-fee revenue at break-even
const { useEffect, useState, useRef } = React;

function FeeChart() {
  const ref = useRef(null);
  const [p, setP] = useState(0);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          let start = performance.now();
          const dur = 2200;
          const tick = (t) => {
            const v = Math.min(1, (t - start) / dur);
            // ease
            const eased = v < 0.5 ? 2 * v * v : 1 - Math.pow(-2 * v + 2, 2) / 2;
            setP(eased);
            if (v < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.disconnect();
        }
      },
      { threshold: 0.4 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const W = 720, H = 540;
  const PAD_L = 70, PAD_R = 40, PAD_T = 50, PAD_B = 70;
  const innerW = W - PAD_L - PAD_R;
  const innerH = H - PAD_T - PAD_B;

  // X = months 0..12, Y = $K
  const months = ['М0','М2','М4','М6','М8','М10','М12'];
  const x = (m) => PAD_L + (m / 12) * innerW;
  const y = (v) => PAD_T + innerH - (v / 100) * innerH;

  // Investment phase (fixed): flat ~30K, ramps down after break-even (M6)
  const fixedPath = (() => {
    const pts = [];
    for (let m = 0; m <= 12; m += 0.5) {
      let val = m < 6 ? 30 : Math.max(0, 30 - (m - 6) * 6);
      pts.push([x(m), y(val)]);
    }
    return pts;
  })();

  // Success fee curve: starts 0, climbs (S-curve)
  const feePath = (() => {
    const pts = [];
    for (let m = 0; m <= 12; m += 0.5) {
      // S-curve: val = 90 / (1+exp(-(m-6)*0.7))
      const v = 90 / (1 + Math.exp(-(m - 6) * 0.7));
      pts.push([x(m), y(v)]);
    }
    return pts;
  })();

  // Partnership total = success fee minus fixed (cumulative net)
  const partnerPath = (() => {
    const pts = [];
    for (let m = 0; m <= 12; m += 0.5) {
      const fee = 90 / (1 + Math.exp(-(m - 6) * 0.7));
      const fix = m < 6 ? 30 : Math.max(0, 30 - (m - 6) * 6);
      const net = fee - fix;
      pts.push([x(m), y(Math.max(-10, net))]);
    }
    return pts;
  })();

  const drawTo = (pts, prog) => {
    const cut = Math.max(1, Math.floor(pts.length * prog));
    return pts.slice(0, cut).map((p, i) => (i === 0 ? `M ${p[0]} ${p[1]}` : `L ${p[0]} ${p[1]}`)).join(' ');
  };

  // Break-even at M6
  const beX = x(6);
  const beY = y(36);

  return (
    <div className="fee-chart" ref={ref}>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
        <defs>
          <linearGradient id="feeFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="var(--accent-pop)" stopOpacity="0.18" />
            <stop offset="1" stopColor="var(--accent-pop)" stopOpacity="0" />
          </linearGradient>
          <pattern id="dotg" width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="0.6" fill="rgba(10,26,47,0.18)" />
          </pattern>
        </defs>

        <rect x={PAD_L} y={PAD_T} width={innerW} height={innerH} fill="url(#dotg)" />

        {/* Y axis labels */}
        {[0, 25, 50, 75, 100].map((v, i) => (
          <g key={v}>
            <line x1={PAD_L} x2={W - PAD_R} y1={y(v)} y2={y(v)} stroke="rgba(10,26,47,0.08)" />
            <text x={PAD_L - 14} y={y(v) + 4} textAnchor="end" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(10,26,47,0.5)" letterSpacing="1">${v}ТЫС</text>
          </g>
        ))}

        {/* X axis labels */}
        {months.map((m, i) => (
          <text key={m} x={x(i * 2)} y={H - PAD_B + 22} textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(10,26,47,0.5)" letterSpacing="1">{m}</text>
        ))}

        {/* Axis lines */}
        <line x1={PAD_L} x2={W - PAD_R} y1={H - PAD_B} y2={H - PAD_B} stroke="rgba(10,26,47,0.4)" strokeWidth="1" />
        <line x1={PAD_L} x2={PAD_L} y1={PAD_T} y2={H - PAD_B} stroke="rgba(10,26,47,0.4)" strokeWidth="1" />

        {/* Fixed cost line */}
        <path d={drawTo(fixedPath, p)} fill="none" stroke="#0A1A2F" strokeWidth="2" strokeLinecap="round" />

        {/* Success fee filled area */}
        {p > 0.3 && (
          <path
            d={`${drawTo(feePath, p)} L ${x(Math.min(12, p * 12))} ${y(0)} L ${PAD_L} ${y(0)} Z`}
            fill="url(#feeFill)"
          />
        )}

        {/* Success fee line */}
        <path d={drawTo(feePath, p)} fill="none" stroke="var(--accent-pop)" strokeWidth="2.5" strokeLinecap="round" />

        {/* Partnership net (dashed) */}
        <path d={drawTo(partnerPath, p)} fill="none" stroke="rgba(10,26,47,0.5)" strokeWidth="1.5" strokeDasharray="4,4" strokeLinecap="round" />

        {/* Break-even marker */}
        {p > 0.55 && (
          <g style={{ opacity: Math.min(1, (p - 0.55) * 4) }}>
            <line x1={beX} y1={PAD_T} x2={beX} y2={H - PAD_B} stroke="var(--accent-pop)" strokeWidth="1" strokeDasharray="3,3" opacity="0.6" />
            <circle cx={beX} cy={beY} r="6" fill="#F5F3EE" stroke="var(--accent-pop)" strokeWidth="2" />
            <circle cx={beX} cy={beY} r="14" fill="none" stroke="var(--accent-pop)" strokeWidth="0.6" opacity="0.4">
              <animate attributeName="r" values="8;22;8" dur="2.4s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0.5;0;0.5" dur="2.4s" repeatCount="indefinite" />
            </circle>
            <g transform={`translate(${beX + 14}, ${beY - 36})`}>
              <rect x="0" y="0" width="218" height="46" fill="#0A1A2F" />
              <text x="12" y="18" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="rgba(245,243,238,0.6)" letterSpacing="1.2">ТОЧКА ОКУПАЕМОСТИ</text>
              <text x="12" y="36" fontFamily="Fraunces, serif" fontSize="16" fill="#F5F3EE" letterSpacing="-0.01em">~ Месяц 6</text>
            </g>
          </g>
        )}

        {/* Legend top */}
        <g transform="translate(70, 22)">
          <rect x="0" y="0" width="14" height="2" fill="#0A1A2F" />
          <text x="22" y="6" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#0A1A2F" letterSpacing="1">ФИКС · ИНВЕСТ</text>

          <rect x="160" y="0" width="14" height="2" fill="var(--accent-pop)" />
          <text x="182" y="6" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#0A1A2F" letterSpacing="1">ГОНОРАР УСПЕХА · % ВЫРУЧКИ</text>

          <line x1="380" y1="1" x2="394" y2="1" stroke="rgba(10,26,47,0.5)" strokeWidth="1.5" strokeDasharray="3,3" />
          <text x="402" y="6" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#0A1A2F" letterSpacing="1">ЧИСТОЕ ПАРТНЁРСТВО</text>
        </g>

        {/* Caption corner */}
        <text x={W - PAD_R} y={H - 14} textAnchor="end" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="rgba(10,26,47,0.4)" letterSpacing="1.2">РИС. 03 · ТИПОВАЯ ТРАЕКТОРИЯ · ИЛЛЮСТРАТИВНО</text>
      </svg>
    </div>
  );
}

window.FeeChart = FeeChart;
