// Tese.jsx — Gráfico SVG animado: Tentativas × Transformação
const { useRef: useTRef, useEffect: useTEff, useState: useTState } = React;

function TeseChart() {
  const [animated, setAnimated] = useTState(false);
  const chartRef = useTRef();

  useTEff(() => {
    const el = chartRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setAnimated(true); obs.disconnect(); }
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  const W = 500, H = 280, PL = 44, PR = 16, PT = 16, PB = 44;
  const cW = W - PL - PR, cH = H - PT - PB;
  const weeks = 25; // 0..24

  // Tentativas sem método — flat low with dips
  const attemptsData = Array.from({ length: weeks }, (_, i) => {
    const base = 0.22;
    const noise = Math.sin(i * 1.2) * 0.07 + Math.sin(i * 0.5) * 0.05;
    const dip = i > 6 && i < 10 ? -0.08 : 0;
    return Math.max(0.05, base + noise + dip);
  });

  // Transformação Conectadas — smooth growth curve
  const transformData = Array.from({ length: weeks }, (_, i) => {
    return Math.min(0.98, 0.06 + (i / (weeks - 1)) ** 1.6 * 0.92);
  });

  function dataToPath(data, cx, cy) {
    return data.map((v, i) => {
      const x = PL + (i / (data.length - 1)) * cW;
      const y = PT + cy - v * cy;
      return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`;
    }).join(' ');
  }

  function dataToAreaPath(data, cx, cy) {
    const line = dataToPath(data, cx, cy);
    const lastX = (PL + cW).toFixed(1);
    const lastY = (PT + cy).toFixed(1);
    const firstX = PL.toFixed(1);
    return `${line} L ${lastX} ${lastY} L ${firstX} ${lastY} Z`;
  }

  const attemptPath = dataToPath(attemptsData, cW, cH);
  const transformPath = dataToPath(transformData, cW, cH);
  const gapAreaPath = dataToAreaPath(transformData, cW, cH);

  const ticksY = [0, 25, 50, 75, 100];
  const ticksX = [0, 6, 12, 18, 24];

  return (
    <div className="tese-chart-wrap" ref={chartRef}>
      <div style={{ fontSize: 12, color: '#8a6070', marginBottom: 12, display: 'flex', gap: 20, flexWrap: 'wrap' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <svg width="24" height="3"><line x1="0" y1="1.5" x2="24" y2="1.5" stroke="#ccc" strokeWidth="2.5" strokeDasharray="5,3"/></svg>
          Tentativas sem método
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <svg width="24" height="3"><line x1="0" y1="1.5" x2="24" y2="1.5" stroke="#D97B96" strokeWidth="2.5"/></svg>
          Transformação com Conectadas
        </span>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        <defs>
          <linearGradient id="gradLine" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="#D97B96"/>
            <stop offset="60%" stopColor="#F4A7B9"/>
            <stop offset="100%" stopColor="#C9956A"/>
          </linearGradient>
          <linearGradient id="gapFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#D97B96" stopOpacity="0.13"/>
            <stop offset="100%" stopColor="#D97B96" stopOpacity="0.02"/>
          </linearGradient>
          <clipPath id="animClip">
            <rect x={PL} y={PT} width={animated ? cW : 0} height={cH}
              style={{ transition: 'width 1.6s cubic-bezier(.16,1,.3,1)' }}
            />
          </clipPath>
        </defs>

        {/* Grid lines */}
        {ticksY.map(v => {
          const y = PT + cH - (v / 100) * cH;
          return (
            <g key={v}>
              <line x1={PL} y1={y} x2={PL + cW} y2={y}
                stroke="rgba(217,123,150,0.1)" strokeWidth="1"/>
              <text x={PL - 6} y={y + 4} textAnchor="end" fontSize="10" fill="#b0909a">{v}%</text>
            </g>
          );
        })}

        {/* X ticks */}
        {ticksX.map(v => {
          const x = PL + (v / 24) * cW;
          return (
            <g key={v}>
              <text x={x} y={H - 8} textAnchor="middle" fontSize="10" fill="#b0909a">S{v}</text>
            </g>
          );
        })}

        {/* Gap area */}
        <path d={gapAreaPath} fill="url(#gapFill)" clipPath="url(#animClip)"/>

        {/* Attempts line */}
        <path d={attemptPath} fill="none" stroke="#ccc" strokeWidth="2.5"
          strokeDasharray="6,4" clipPath="url(#animClip)"/>

        {/* Transform line */}
        <path d={transformPath} fill="none" stroke="url(#gradLine)"
          strokeWidth="3" strokeLinecap="round" clipPath="url(#animClip)"/>

        {/* Axes */}
        <line x1={PL} y1={PT} x2={PL} y2={PT + cH} stroke="rgba(217,123,150,0.2)" strokeWidth="1.5"/>
        <line x1={PL} y1={PT + cH} x2={PL + cW} y2={PT + cH} stroke="rgba(217,123,150,0.2)" strokeWidth="1.5"/>

        {/* X label */}
        <text x={PL + cW / 2} y={H} textAnchor="middle" fontSize="11" fill="#b0909a">Semanas</text>
      </svg>
    </div>
  );
}

function Tese() {
  const ref = useTRef();
  useReveal(ref);

  const points = [
    { title: 'O problema não é você', body: 'Mulheres que não sustentam resultados não falharam por falta de esforço — falharam porque o método estava errado.' },
    { title: 'Corpo + mente + identidade', body: 'Transformação real acontece quando as três dimensões trabalham juntas — não em separado.' },
    { title: 'Constância é construída, não inspirada', body: 'A Taty desenvolveu ao longo de 10 anos de competição profissional um sistema que transforma disciplina em rotina inevitável.' },
  ];

  return (
    <section className="tese-section" ref={ref} id="tese">
      <div className="container">
        <div className="tese-inner">
          <div>
            <p className="eyebrow reveal">A tese</p>
            <h2 className="section-title reveal rev-d1">
              Por que a maioria das tentativas <em>falha</em> — e como isso muda
            </h2>
            <div className="tese-points">
              {points.map((p, i) => (
                <div key={i} className={`tese-point reveal rev-d${i+2}`}>
                  <div className="tese-point-icon">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                      <path d="M3 8l3.5 3.5L13 4.5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </div>
                  <div>
                    <div style={{ fontWeight: 800, marginBottom: 4, fontSize: 16, letterSpacing: '-0.01em' }}>{p.title}</div>
                    <p style={{ fontSize: 14, color: '#6a5060', lineHeight: 1.65 }}>{p.body}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="reveal rev-d2">
            <TeseChart />
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Tese });
