/* ── TRADINGVIEW-STYLE CHART ─────────────────────────────────────────────
   Lines: Carteira (gold area) · CDI (blue dashed) · IPCA (red dashed) · IBOV (gray dashed)
   Data from: market-data.js (Brapi API)
   ──────────────────────────────────────────────────────────────────────── */

function buildIndexedSeries(dataPoints, benchmarks) {
  if (!dataPoints.length) return { carteira: [], cdi: [], ipca: [], ibov: [] };
  const sorted = dataPoints.slice().sort((a, b) => a.key.localeCompare(b.key));

  // Use cumulative RENT (not PL ratio) so aportes/resgates don't inflate the return
  let cartCum = 1, cdiCum = 1, ipcaCum = 1, ibovCum = 1;
  const carteira = [], cdi = [], ipca = [], ibov = [];
  for (const d of sorted) {
    cartCum  *= 1 + (d.rent || 0);   // d.rent = rentMes from PDF (pure investment return)
    cdiCum   *= 1 + (benchmarks.monthly_cdi?.[d.key]  || 0);
    ipcaCum  *= 1 + (benchmarks.monthly_ipca?.[d.key] || 0);
    ibovCum  *= 1 + (benchmarks.monthly_ibov?.[d.key] || 0);
    carteira.push({ key: d.key, label: d.label, ret: cartCum - 1 });
    cdi.push({  key: d.key, label: d.label, ret: cdiCum  - 1 });
    ipca.push({ key: d.key, label: d.label, ret: ipcaCum - 1 });
    ibov.push({ key: d.key, label: d.label, ret: ibovCum - 1 });
  }
  return { carteira, cdi, ipca, ibov };
}

function TVChart({ data, height = 280, nome }) {
  const [hoverIdx, setHoverIdx] = React.useState(null);
  const [bench, setBench] = React.useState(() => window.BENCHMARKS || {});
  const svgRef = React.useRef(null);

  React.useEffect(() => {
    // Fetch all benchmark data in parallel
    Promise.all([
      window.fetchBenchmarks?.(),
      window.fetchIBOV?.(),
    ]).then(() => setBench({ ...window.BENCHMARKS }));
  }, []);

  if (!data || data.length < 2) return (
    <div style={{ height, display:'flex', alignItems:'center', justifyContent:'center',
      color:'rgba(255,255,255,0.3)', fontSize:'0.8rem', background:'#0D1520' }}>
      Histórico insuficiente
    </div>
  );

  const { carteira, cdi, ipca, ibov } = buildIndexedSeries(data, bench);
  const allRets = [...carteira, ...cdi, ...ipca, ...ibov].map(d => d.ret);
  const minY = Math.min(...allRets) - 0.003;
  const maxY = Math.max(...allRets) + 0.005;
  const rangeY = maxY - minY || 0.01;

  const W = 800, H = height;
  const pad = { t: 28, r: 24, b: 48, l: 76 };
  const iW = W - pad.l - pad.r, iH = H - pad.t - pad.b;
  const n = carteira.length;
  const xi = i => pad.l + (i / (n - 1)) * iW;
  const yi = v => pad.t + iH - ((v - minY) / rangeY) * iH;
  const pathOf = pts => pts.map((d,i) => `${i===0?'M':'L'} ${xi(i)},${yi(d.ret)}`).join(' ');
  const areaOf = pts => pathOf(pts) + ` L ${xi(n-1)},${yi(Math.max(0,minY))} L ${xi(0)},${yi(Math.max(0,minY))} Z`;
  const gridLines = Array.from({length:6},(_,i) => { const v=minY+(rangeY*i/5); return {y:yi(v),v}; });
  const fmtPct = v => (v>=0?'+':'')+(v*100).toFixed(2)+'%';

  function handleMouseMove(e) {
    const rect = svgRef.current?.getBoundingClientRect();
    if (!rect) return;
    const mx = (e.clientX - rect.left) / rect.width * W;
    setHoverIdx(Math.max(0, Math.min(n-1, Math.round((mx - pad.l) / iW * (n-1)))));
  }

  const hov = hoverIdx !== null && carteira[hoverIdx] ? {
    cart: carteira[hoverIdx], cdi: cdi[hoverIdx],
    ipca: ipca[hoverIdx], ibov: ibov[hoverIdx], x: xi(hoverIdx),
  } : null;

  // % CDI for last point
  const lastCart = carteira[n-1];
  const lastCdi  = cdi[n-1];
  const pctCDI   = lastCdi?.ret ? Math.round((lastCart?.ret / lastCdi?.ret) * 100) : null;

  const LEGENDS = [
    { color:'#C4A228', label: nome||'Carteira', dash:false },
    { color:'#5B8DEF', label:'CDI',    dash:true },
    { color:'#E85D75', label:'IPCA',   dash:true },
    { color:'#6B7E6B', label:'IBOV',   dash:true },
  ];

  return (
    <div style={{ background:'#0D1520', borderRadius:'var(--r-sm)' }}>
      {/* Header row */}
      <div style={{ display:'flex', alignItems:'center', padding:'12px 16px 0', gap:12 }}>
        <span style={{ fontSize:'0.7rem', fontWeight:600, letterSpacing:'0.06em', color:'rgba(255,255,255,0.4)', textTransform:'uppercase' }}>
          Retorno acumulado
        </span>
        {pctCDI !== null && (
          <span style={{ fontSize:'0.68rem', fontFamily:'JetBrains Mono,monospace',
            color: pctCDI >= 100 ? '#6FCF97' : '#E85D75',
            background:'rgba(255,255,255,0.07)', padding:'2px 8px', borderRadius:3 }}>
            {pctCDI}% do CDI
          </span>
        )}
        <div style={{ display:'flex', gap:14, marginLeft:'auto' }}>
          {LEGENDS.map(l => (
            <div key={l.label} style={{ display:'flex', alignItems:'center', gap:5 }}>
              <svg width="20" height="10">
                {l.dash
                  ? <line x1="0" y1="5" x2="20" y2="5" stroke={l.color} strokeWidth="1.5" strokeDasharray="4,3"/>
                  : <line x1="0" y1="5" x2="20" y2="5" stroke={l.color} strokeWidth="2"/>
                }
              </svg>
              <span style={{ fontSize:'0.65rem', color:'rgba(255,255,255,0.45)' }}>{l.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* SVG chart */}
      <svg ref={svgRef} viewBox={`0 0 ${W} ${H}`}
        style={{ width:'100%', height, display:'block', cursor:'crosshair' }}
        onMouseMove={handleMouseMove} onMouseLeave={() => setHoverIdx(null)}
        preserveAspectRatio="none">
        <defs>
          <linearGradient id="tvGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#C4A228" stopOpacity="0.22"/>
            <stop offset="100%" stopColor="#C4A228" stopOpacity="0"/>
          </linearGradient>
          <clipPath id="tvClip"><rect x={pad.l} y={pad.t} width={iW} height={iH}/></clipPath>
        </defs>

        {/* Grid */}
        {gridLines.map((g,i) => (
          <g key={i}>
            <line x1={pad.l} x2={pad.l+iW} y1={g.y} y2={g.y} stroke="rgba(255,255,255,0.05)" strokeWidth="1"/>
            <text x={pad.l-8} y={g.y+4} textAnchor="end" fontSize="8.5" fill="rgba(255,255,255,0.3)" fontFamily="JetBrains Mono,monospace">{fmtPct(g.v)}</text>
          </g>
        ))}
        {minY < 0 && maxY > 0 && (
          <line x1={pad.l} x2={pad.l+iW} y1={yi(0)} y2={yi(0)} stroke="rgba(255,255,255,0.14)" strokeWidth="1" strokeDasharray="4,3"/>
        )}

        <g clipPath="url(#tvClip)">
          {/* IBOV */}
          <path d={pathOf(ibov)} fill="none" stroke="#6B7E6B" strokeWidth="1.4" strokeDasharray="4,4" opacity="0.65"/>
          {/* IPCA */}
          <path d={pathOf(ipca)} fill="none" stroke="#E85D75" strokeWidth="1.5" strokeDasharray="5,4" opacity="0.75"/>
          {/* CDI */}
          <path d={pathOf(cdi)}  fill="none" stroke="#5B8DEF" strokeWidth="1.5" strokeDasharray="5,4" opacity="0.75"/>
          {/* Carteira area + line */}
          <path d={areaOf(carteira)} fill="url(#tvGrad)"/>
          <path d={pathOf(carteira)} fill="none" stroke="#C4A228" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
          {/* Dots */}
          {carteira.map((d,i) => (
            <circle key={i} cx={xi(i)} cy={yi(d.ret)} r={hoverIdx===i?5.5:3.5}
              fill={hoverIdx===i?'#C4A228':'#0D1520'} stroke="#C4A228" strokeWidth="2"
              style={{transition:'r 0.1s'}}/>
          ))}
          {/* Crosshair */}
          {hov && <line x1={hov.x} x2={hov.x} y1={pad.t} y2={pad.t+iH} stroke="rgba(255,255,255,0.18)" strokeWidth="1" strokeDasharray="3,3"/>}
        </g>

        {/* X axis labels */}
        {carteira.map((d,i) => (
          <text key={i} x={xi(i)} y={H-10}
            textAnchor={i===0?'start':i===n-1?'end':'middle'}
            fontSize="9.5" fill="rgba(255,255,255,0.38)" fontFamily="Inter,sans-serif">
            {d.label}
          </text>
        ))}

        {/* Tooltip */}
        {hov && (() => {
          const tx = Math.min(hov.x+12, W-168), ty = pad.t+4;
          const pCDI = hov.cdi.ret ? Math.round(hov.cart.ret / hov.cdi.ret * 100) : null;
          return <g>
            <rect x={tx} y={ty} width={162} height={96} rx="4"
              fill="#1A2840" stroke="rgba(255,255,255,0.1)" strokeWidth="1"/>
            <text x={tx+10} y={ty+16} fontSize="9" fill="rgba(255,255,255,0.5)" fontFamily="Inter,sans-serif">
              {hov.cart.label}{pCDI ? ` · ${pCDI}% CDI` : ''}
            </text>
            <text x={tx+10} y={ty+34} fontSize="11" fill="#C4A228" fontFamily="JetBrains Mono,monospace" fontWeight="600">
              Cart. {fmtPct(hov.cart.ret)}
            </text>
            <text x={tx+10} y={ty+52} fontSize="10" fill="#5B8DEF" fontFamily="JetBrains Mono,monospace">
              CDI  {fmtPct(hov.cdi.ret)}
            </text>
            <text x={tx+10} y={ty+68} fontSize="10" fill="#E85D75" fontFamily="JetBrains Mono,monospace">
              IPCA {fmtPct(hov.ipca.ret)}
            </text>
            <text x={tx+10} y={ty+84} fontSize="10" fill="#6B7E6B" fontFamily="JetBrains Mono,monospace">
              IBOV {fmtPct(hov.ibov.ret)}
            </text>
          </g>;
        })()}
      </svg>
    </div>
  );
}

window.TVChart = TVChart;
