/* Spend vs ROAS chart =============================================== */

const RC = (typeof Recharts !== 'undefined') ? Recharts : window.Recharts;

function CustomTooltip({ active, payload, label, dark, hideRoas }){
  if (!active || !payload || !payload.length) return null;
  const data = payload[0]?.payload;
  const isProj = data?.projected;
  return (
    <div className="rounded-xl shadow-float border bg-white dark:bg-ink-800 border-ink-200 dark:border-white/10 px-3 py-2.5 min-w-[200px]">
      <div className="flex items-center justify-between gap-2">
        <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">
          {data?.label || label}
        </div>
        {isProj && <Pill tone="accent">Projected</Pill>}
      </div>
      <div className="mt-1.5 space-y-1">
        <div className="flex items-center justify-between gap-3 text-[12px]">
          <div className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-accent-500"/>
            <span className="text-ink-700 dark:text-ink-200">Spend</span>
          </div>
          <span className="tabular font-medium">{fmt(data.spend,'currency')}</span>
        </div>
        {!hideRoas && (
        <div className="flex items-center justify-between gap-3 text-[12px]">
          <div className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-emerald-500"/>
            <span className="text-ink-700 dark:text-ink-200">ROAS</span>
          </div>
          <span className="tabular font-medium">{data.roas.toFixed(2)}×</span>
        </div>
        )}
      </div>
    </div>
  );
}

function SpendRoasChart({ accountId, platformId, range='30d', dark=false, hideRoas=false }){
  const data = useMemo(()=>{
    const all = timeSeriesFor(accountId, platformId);
    let actual;
    if (range==='7d')       actual = all.slice(-7);
    else if (range==='14d') actual = all.slice(-14);
    else                    actual = all;
    const projected = projectedDays(accountId, platformId, 7);
    return { actual, projected, combined: [...actual, ...projected] };
  }, [accountId, platformId, range]);

  const tone = (PLATFORMS.find(p=>p.id===platformId)||PLATFORMS[0]).tone;
  const axis = dark ? '#8b8b80' : '#5e5e55';
  const grid = dark ? 'rgba(255,255,255,.06)' : 'rgba(0,0,0,.06)';

  if (!data.actual.length) return (
    <div className="h-[280px] grid place-items-center text-center text-ink-400">
      <div>
        <div className="text-[13px] font-medium text-ink-500 dark:text-ink-300">No spend data for this range</div>
        <div className="text-[11.5px] mt-1">Connect a data source or import data in Admin → Integrations.</div>
      </div>
    </div>
  );

  if (!RC) return <div className="h-72 grid place-items-center text-ink-400">Loading chart…</div>;

  const { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Area, AreaChart, ComposedChart, defs, Legend, ReferenceLine, ReferenceArea } = RC;

  /* Index where "now" sits (last actual day) */
  const nowIdx = data.actual.length - 1;
  const nowLabel = data.actual[nowIdx]?.label;
  const projStartLabel = data.projected[0]?.label;
  const projEndLabel = data.projected[data.projected.length-1]?.label;

  return (
    <div className="h-[280px] w-full">
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={data.combined} margin={{top:10, right:8, left:-12, bottom:0}}>
          <defs>
            <linearGradient id="gSpend" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={tone} stopOpacity="0.28"/>
              <stop offset="100%" stopColor={tone} stopOpacity="0"/>
            </linearGradient>
            <linearGradient id="gSpendProj" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={tone} stopOpacity="0.14"/>
              <stop offset="100%" stopColor={tone} stopOpacity="0"/>
            </linearGradient>
            <pattern id="projHatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke={tone} strokeOpacity="0.18" strokeWidth="2"/>
            </pattern>
          </defs>
          <CartesianGrid stroke={grid} strokeDasharray="3 3" vertical={false}/>
          {/* Projected zone */}
          {projStartLabel && (
            <ReferenceArea x1={projStartLabel} x2={projEndLabel} yAxisId="left" fill="url(#projHatch)" fillOpacity={0.85} stroke="none"/>
          )}
          <XAxis dataKey="label" tick={{fill:axis, fontSize:11, fontFamily:'Geist Mono'}} stroke={grid} interval={Math.max(0,Math.floor(data.combined.length/8))}/>
          <YAxis yAxisId="left" tick={{fill:axis, fontSize:11, fontFamily:'Geist Mono'}} stroke={grid}
            tickFormatter={(v)=>curPrefix()+(v>=1000?(v/1000).toFixed(1)+'k':v)}/>
          {!hideRoas && <YAxis yAxisId="right" orientation="right" tick={{fill:axis, fontSize:11, fontFamily:'Geist Mono'}} stroke={grid}
            tickFormatter={(v)=>v.toFixed(1)+'×'}/>}
          <Tooltip content={<CustomTooltip dark={dark} hideRoas={hideRoas}/>} cursor={{ stroke: tone, strokeOpacity:.4, strokeWidth:1, strokeDasharray:'2 3' }}/>
          {/* Now line */}
          {nowLabel && (
            <ReferenceLine x={nowLabel} yAxisId="left" stroke={dark?'#ffffff66':'#00000066'} strokeWidth={1.2} strokeDasharray="4 3"
              label={{ value:'NOW', position:'top', fontSize:9, fontFamily:'Geist Mono', fill: axis, dy:-2 }}/>
          )}
          {/* Actual area */}
          <Area yAxisId="left" type="monotone" dataKey={(d)=> d.projected ? null : d.spend} name="Spend" stroke={tone} strokeWidth={1.8} fill="url(#gSpend)" animationDuration={900} animationEasing="ease-out" connectNulls={false}/>
          {/* Projected spend (dashed) */}
          <Line yAxisId="left" type="monotone" dataKey={(d)=> d.projected ? d.spend : null} name="Spend (projected)" stroke={tone} strokeWidth={1.4} strokeDasharray="5 3" dot={false} animationDuration={900} connectNulls={false}/>
          {/* Actual ROAS line (dropped entirely for blocklisted accounts) */}
          {!hideRoas && <Line yAxisId="right" type="monotone" dataKey={(d)=> d.projected ? null : d.roas} name="ROAS" stroke="#10b981" strokeWidth={1.8} dot={false} animationDuration={1100} animationEasing="ease-out" activeDot={{r:4, strokeWidth:0, fill:'#10b981'}} connectNulls={false}/>}
          {/* Projected ROAS (dashed) */}
          {!hideRoas && <Line yAxisId="right" type="monotone" dataKey={(d)=> d.projected ? d.roas : null} name="ROAS (projected)" stroke="#10b981" strokeWidth={1.4} strokeDasharray="5 3" dot={false} animationDuration={1100} connectNulls={false}/>}
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}

/* Donut share — true pie/donut for clear platform contribution.
   Excludes blended 'overview', 'google_analytics' (not an ad platform)
   and 'meta' (its FB/IG children carry the spend). */
function PlatformShare({ accountId }){
  const data = useMemo(()=>{
    return platformBreakdown(accountId)
      .map(m=>{
        const p = PLATFORMS.find(x=>x.id===m.platform);
        if (!p || ['overview','google_analytics','meta'].includes(p.id)) return null;
        return { id:p.id, label:p.short, value:m.spend, tone:p.tone };
      })
      .filter(Boolean)
      .sort((a,b)=>b.value-a.value);
  }, [accountId]);
  const total = data.reduce((s,d)=>s+d.value, 0) || 1;

  // build donut arc stops
  const R=42, C=2*Math.PI*R; let acc=0;
  const segs = data.map(d=>{ const frac=d.value/total; const seg={ ...d, frac, dash:frac*C, offset:-acc*C }; acc+=frac; return seg; });

  return (
    <div className="flex items-center gap-4">
      <div className="relative flex-shrink-0" style={{width:120, height:120}}>
        <svg width="120" height="120" viewBox="0 0 120 120" className="-rotate-90">
          <circle cx="60" cy="60" r={R} fill="none" stroke="currentColor" className="text-ink-100 dark:text-white/5" strokeWidth="14"/>
          {segs.map(s=>(
            <circle key={s.id} cx="60" cy="60" r={R} fill="none" stroke={displayTone(s.tone)} strokeWidth="14"
              strokeDasharray={`${s.dash} ${C-s.dash}`} strokeDashoffset={s.offset}>
              <title>{s.label} · {fmt(s.value,'currency')}</title>
            </circle>
          ))}
        </svg>
        <div className="absolute inset-0 grid place-items-center -rotate-0">
          <div className="text-center leading-none">
            <div className="text-[15px] font-semibold tabular">{fmt(total,'currency')}</div>
            <div className="text-[10px] text-ink-400 mt-0.5">total spend</div>
          </div>
        </div>
      </div>
      <div className="flex-1 grid grid-cols-1 gap-y-1.5">
        {segs.map(d => (
          <div key={d.id} className="flex items-center justify-between text-[12px]">
            <div className="flex items-center gap-1.5 min-w-0">
              <span className="w-2 h-2 rounded-full flex-shrink-0" style={{background:displayTone(d.tone)}}/>
              <span className="text-ink-700 dark:text-ink-200 truncate">{d.label}</span>
            </div>
            <span className="tabular text-ink-500 dark:text-ink-300 ml-2">{(d.frac*100).toFixed(1)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { SpendRoasChart, PlatformShare });
