// Donut/breakdown card + full-width revenue trend chart.

function useWidth(){
  const ref = React.useRef(null);
  const [w, setW] = React.useState(800);
  React.useEffect(()=>{
    if(!ref.current) return;
    const ro = new ResizeObserver(es=>{ for(const e of es) setW(e.contentRect.width); });
    ro.observe(ref.current);
    return ()=>ro.disconnect();
  },[]);
  return [ref, w];
}

// segments: [{label, value, color}] · mode: 'donut' | 'bars'
const BreakdownCard = ({ eyebrow, title, segments, mode='donut', unit='USD' }) => {
  const sum = segments.reduce((s,x)=>s+x.value,0) || 1;
  let acc = 0;
  const stops = segments.map(s=>{
    const start = acc/sum*100; acc += s.value; const end = acc/sum*100;
    return `${s.color} ${start}% ${end}%`;
  }).join(', ');
  const maxv = Math.max(...segments.map(s=>s.value), 1);
  return (
    <div style={ch.panel}>
      <div style={ch.head}>
        <div style={ch.eye}>{eyebrow}</div>
        <div style={ch.title}>{title}</div>
      </div>

      {mode==='donut' ? (
        <div style={ch.donutWrap}>
          <div style={{...ch.donut, background:`conic-gradient(${stops})`}}>
            <div style={ch.hole}>
              <span style={ch.holeVal} className="fenix-num">{USDk(sum)}</span>
              <span style={ch.holeLab}>total</span>
            </div>
          </div>
        </div>
      ) : (
        <div style={ch.miniBars}>
          {segments.map(s=>(
            <div key={s.label} style={ch.miniRow}>
              <div style={ch.miniTop}>
                <span style={ch.miniName}><span style={{...ch.dot, background:s.color}}/>{s.label}</span>
                <span style={ch.miniPct} className="fenix-num">{(s.value/sum*100).toFixed(0)}%</span>
              </div>
              <div style={ch.miniTrack}><div style={{width:(s.value/maxv*100)+'%', height:'100%', background:s.color, borderRadius:'var(--r-pill)', transition:'width .5s var(--ease)'}}/></div>
            </div>
          ))}
        </div>
      )}

      <div style={ch.legend}>
        {segments.map(s=>(
          <div key={s.label} style={ch.legRow}>
            <span style={{...ch.dot, background:s.color}}/>
            <span style={ch.legName}>{s.label}</span>
            <span style={ch.legPct} className="fenix-num">{(s.value/sum*100).toFixed(0)}%</span>
            <span style={ch.legVal} className="fenix-num">{USDk(s.value)}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// Full-width revenue trend, responde ao período. mode: 'line' | 'area' | 'bars'
// points: [{bucket, total, bySource, byPlatform}] · granularity: hour|day|week|month
const SRC_LABELS = [['direct','Direto'],['logicall','Logicall'],['tauk','Tauk'],['salesbound','Salesbound'],['email','Email'],['sms','SMS']];

const TrendTooltip = ({ p, x, y, cw }) => {
  const srcRows = SRC_LABELS.filter(([k])=>p.bySource && p.bySource[k]!=null && p.bySource[k]>0);
  const noGord = !p.bySource || p.bySource.logicall==null;
  const pltRows = Object.values(PLATFORM).filter(pl=>p.byPlatform && p.byPlatform[pl.key]>0);
  const left = Math.min(Math.max(x-110, 8), Math.max(cw-228, 8));
  return (
    <div style={{...ch.tip, left, top:y+16}}>
      <div style={ch.tipTitle}>{p.label} · <span className="fenix-num">{USDk(p.total)}</span></div>
      <div style={ch.tipSect}>Por fonte</div>
      {srcRows.map(([k,l])=>(
        <div key={k} style={ch.tipRow}>
          <span style={{...ch.dot, background:CH[k].color}}/>
          <span style={ch.tipLab}>{l}</span>
          <span style={ch.tipVal} className="fenix-num">{USDk(p.bySource[k])}</span>
        </div>
      ))}
      {noGord && <div style={ch.tipNote}>Gorduras sem fonte integrada</div>}
      <div style={ch.tipSect}>Por plataforma</div>
      {pltRows.map(pl=>(
        <div key={pl.key} style={ch.tipRow}>
          <span style={{...ch.dot, background:pl.color}}/>
          <span style={ch.tipLab}>{pl.label}</span>
          <span style={ch.tipVal} className="fenix-num">{USDk(p.byPlatform[pl.key])}</span>
        </div>
      ))}
    </div>
  );
};

const PERIOD_TITLES = { ontem:'Ontem', '7d':'Últimos 7 dias', '14d':'Últimos 14 dias',
  '30d':'Últimos 30 dias', '90d':'Últimos 90 dias', ytd:'Ano até hoje', total:'Todo período', custom:'Período personalizado' };

// suaviza uma lista de pontos [x,y] em path bézier (Catmull-Rom)
const smoothPath = (pp) => {
  if(pp.length<2) return pp.length ? `M ${pp[0][0]} ${pp[0][1]}` : '';
  let d = `M ${pp[0][0]} ${pp[0][1]}`;
  for(let i=0;i<pp.length-1;i++){
    const p0=pp[i-1]||pp[i], p1=pp[i], p2=pp[i+1], p3=pp[i+2]||p2;
    const c1x=p1[0]+(p2[0]-p0[0])/6, c1y=p1[1]+(p2[1]-p0[1])/6;
    const c2x=p2[0]-(p3[0]-p1[0])/6, c2y=p2[1]-(p3[1]-p1[1])/6;
    d += ` C ${c1x} ${c1y} ${c2x} ${c2y} ${p2[0]} ${p2[1]}`;
  }
  return d;
};

const RevenueTrend = ({ trend, mode='area', period='30d' }) => {
  const [ref, w] = useWidth();
  const [hover, setHover] = React.useState(null);
  const pts0 = (trend?.points || []).map(p=>({ ...p, label: trendLabel(p.bucket, trend.granularity) }));
  if(pts0.length===0) return null;
  // linha = receita Direta (visual de sempre). Logicall/Salesbound aparecem só no tooltip,
  // que usa p.total (consolidado, Direto+gorduras) no título e a quebra por fonte.
  const data = pts0.map(p => (p.bySource && p.bySource.direct != null) ? p.bySource.direct : p.total);

  const H = 230, padL = 64, padR = 22, padT = 18, padB = 34;
  const cw = Math.max(w, 320);
  const innerW = cw - padL - padR, innerH = H - padT - padB;
  const max = Math.max(...data), min = Math.min(...data);
  const lo = Math.max(0, min - (max-min)*0.5), hi = max + (max-min)*0.25;
  const x = i => padL + (data.length<=1?0:innerW*i/(data.length-1));
  const y = v => padT + innerH*(1-(v-lo)/(hi-lo||1));
  const baseY = padT+innerH;
  const pts = data.map((v,i)=>[x(i),y(v)]);
  const line = smoothPath(pts);
  const area = line + ` L ${x(data.length-1)} ${baseY} L ${padL} ${baseY} Z`;
  const ticks = 4;
  const gy = Array.from({length:ticks+1},(_,i)=>lo+(hi-lo)*i/ticks);
  const bw = innerW/data.length*0.46;
  const lblStep = Math.max(1, Math.ceil(pts0.length/10));

  return (
    <div style={{...ch.panel, marginBottom:0, position:'relative'}}>
      <div style={ch.head}>
        <div style={ch.eye}>Série temporal</div>
        <div style={ch.title}>Evolução do Canal · {PERIOD_TITLES[period] || period}</div>
      </div>
      <div ref={ref} style={{width:'100%'}}>
        <svg width={cw} height={H} style={{display:'block'}} onMouseLeave={()=>setHover(null)}>
          <defs>
            <linearGradient id="trendFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#FD7119" stopOpacity="0.22"/>
              <stop offset="100%" stopColor="#FD7119" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {gy.map((v,i)=>(
            <g key={i}>
              <line x1={padL} y1={y(v)} x2={cw-padR} y2={y(v)} stroke="#DEE2EA" strokeWidth="1" strokeDasharray={i===0?'0':'3 4'}/>
              <text x={padL-12} y={y(v)+4} textAnchor="end" fontFamily="var(--font-num)" fontSize="11" fill="#9AA3B5">{USDk(v)}</text>
            </g>
          ))}
          {mode==='bars' ? (
            data.map((v,i)=>(
              <rect key={i} x={x(i)-bw/2} y={y(v)} width={bw} height={baseY-y(v)} rx="4"
                fill="url(#trendFill)" stroke="#FD7119" strokeWidth="1.5"
                onMouseEnter={()=>setHover(i)} style={{cursor:'pointer'}}/>
            ))
          ) : (
            <>
              {mode==='area' && <path d={area} fill="url(#trendFill)"/>}
              <path d={line} fill="none" stroke="#FD7119" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
              {hover!=null && <line x1={x(hover)} y1={padT} x2={x(hover)} y2={baseY} stroke="#FD7119" strokeWidth="1" strokeDasharray="3 3" opacity="0.5"/>}
              {pts.map((p,i)=>(
                <g key={i} onMouseEnter={()=>setHover(i)} style={{cursor:'pointer'}}>
                  <circle cx={p[0]} cy={p[1]} r="13" fill="transparent"/>
                  <circle cx={p[0]} cy={p[1]} r={hover===i?6:4.5} fill="#fff" stroke="#FD7119" strokeWidth="2.5"/>
                </g>
              ))}
            </>
          )}
          {pts0.map((p,i)=>( i%lblStep===0 &&
            <text key={i} x={x(i)} y={H-12} textAnchor="middle" fontFamily="'Archivo', sans-serif" fontWeight="600" fontSize="12" fill="#6B7488">{p.label}</text>
          ))}
        </svg>
      </div>
      {hover!=null && pts0[hover] && (
        <TrendTooltip p={pts0[hover]} x={x(hover)} y={y(data[hover])} cw={cw}/>
      )}
    </div>
  );
};

const ch = {
  panel:{ background:'#fff', border:'1px solid var(--border-1)', borderRadius:'var(--r-lg)', padding:'20px 22px', boxShadow:'var(--shadow-sm)' },
  head:{ marginBottom:18 },
  eye:{ font:'var(--text-label)', letterSpacing:'.05em', textTransform:'uppercase', color:'var(--fg-3)' },
  title:{ font:'var(--text-h3)', color:'var(--fg-1)', marginTop:4 },
  donutWrap:{ display:'flex', justifyContent:'center', padding:'4px 0 18px' },
  donut:{ width:150, height:150, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center' },
  hole:{ width:96, height:96, borderRadius:'50%', background:'#fff', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' },
  holeVal:{ font:'800 19px/1 var(--font-num)', color:'var(--fg-1)', letterSpacing:'-.01em', fontVariantNumeric:'tabular-nums' },
  holeLab:{ font:'var(--text-caption)', color:'var(--fg-3)', marginTop:3, textTransform:'uppercase', letterSpacing:'.06em' },
  miniBars:{ display:'flex', flexDirection:'column', gap:13, padding:'2px 0 16px' },
  miniRow:{},
  miniTop:{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6 },
  miniName:{ display:'inline-flex', alignItems:'center', gap:8, font:'var(--text-body-sm)', fontWeight:600, color:'var(--fg-1)' },
  miniPct:{ font:'600 12px/1 var(--font-mono)', color:'var(--fg-2)' },
  miniTrack:{ height:8, background:'var(--gray-100)', borderRadius:'var(--r-pill)', overflow:'hidden' },
  legend:{ display:'flex', flexDirection:'column', gap:10, borderTop:'1px solid var(--border-1)', paddingTop:14 },
  legRow:{ display:'flex', alignItems:'center', gap:9 },
  dot:{ width:9, height:9, borderRadius:'50%', flex:'none' },
  legName:{ font:'var(--text-body-sm)', fontWeight:600, color:'var(--fg-1)' },
  legPct:{ font:'600 12px/1 var(--font-mono)', color:'var(--fg-3)', marginLeft:'auto' },
  legVal:{ font:'600 12px/1 var(--font-mono)', color:'var(--fg-1)', minWidth:56, textAlign:'right' },
  tip:{ position:'absolute', width:220, background:'var(--fenix-navy)', borderRadius:'var(--r-md)',
    padding:'12px 14px', boxShadow:'var(--shadow-lg)', zIndex:20, pointerEvents:'none' },
  tipTitle:{ font:'700 12.5px/1.2 var(--font-sans)', color:'#F6E9E0', marginBottom:4 },
  tipSect:{ font:'700 9.5px/1 var(--font-sans)', letterSpacing:'.08em', textTransform:'uppercase', color:'#FFA866', margin:'9px 0 5px' },
  tipRow:{ display:'flex', alignItems:'center', gap:7, padding:'2.5px 0' },
  tipLab:{ font:'500 11.5px/1 var(--font-sans)', color:'#C3D0E2', flex:1 },
  tipVal:{ font:'600 11.5px/1 var(--font-mono)', color:'#F6E9E0' },
  tipNote:{ font:'italic 10.5px/1.3 var(--font-sans)', color:'#7E92AE', padding:'2px 0' },
};

Object.assign(window, { BreakdownCard, RevenueTrend, useWidth });
