export async function initForecast(state, { fmtBRL }){
  try {
    const canvas = document.getElementById('forecastCanvas');
    if (!canvas) return;
    const series = await loadDailySeries(state.filters);
    const forecast = exponentialSmoothing(series.map(p=>p.y), 0.3, 7);
    const combined = series.map((p,i)=>({ x: p.x, y: p.y, f: (i<forecast.seedLength?null:forecast.values[i-forecast.seedLength]) }));
    drawLineChart(canvas, combined);
  } catch (e) {
    console.error('Forecast error:', e);
    const el = document.getElementById('forecastPanel');
    if (el) el.querySelector('canvas')?.insertAdjacentHTML('afterend', '<div class="muted">Falha ao gerar predição</div>');
  }
}

async function loadDailySeries(filters){
  try {
    const params = new URLSearchParams();
    if (filters?.start) params.set('start', filters.start);
    if (filters?.end) params.set('end', filters.end);
    params.set('group_by', 'day');
    const resp = await fetch('/api/sales/advanced?'+params.toString(), { credentials:'include' });
    const json = await resp.json();
    const data = Array.isArray(json.data)?json.data:[];
    if (data.length) return data.map(r=>({ x: r.day||r.date||r.dia||'', y: Number(r.total||r.valor||0)/100 }));
  } catch(e) { /* fallback abaixo */ }
  // Fallback: série sintética curta
  const today = new Date(); const arr=[];
  for (let i=14;i>=0;i--) { const d = new Date(today); d.setDate(today.getDate()-i); arr.push({ x: d.toISOString().slice(0,10), y: Math.round(800 + Math.random()*600)/1 }); }
  return arr;
}

function exponentialSmoothing(values, alpha=0.3, horizon=7){
  const sm = []; let s = values[0]||0; sm.push(s);
  for (let i=1;i<values.length;i++){ s = alpha*values[i] + (1-alpha)*s; sm.push(s); }
  const last = sm[sm.length-1]||0; const future=[]; for(let h=0;h<horizon;h++){ future.push(last); }
  return { seedLength: values.length, values: sm.concat(future) };
}

function drawLineChart(canvas, points){
  const ctx=canvas.getContext('2d'); const w=canvas.width, h=canvas.height; ctx.clearRect(0,0,w,h);
  const pad=30; const ys = points.map(p=>p.y); const maxY=Math.max(1,...ys);
  const stepX = (w - pad*2) / Math.max(1, (points.length-1));
  // grid
  ctx.strokeStyle = '#e5e7eb'; ctx.lineWidth=1; for(let i=0;i<=4;i++){ const y = pad + i*((h-pad*2)/4); ctx.beginPath(); ctx.moveTo(pad,y); ctx.lineTo(w-pad,y); ctx.stroke(); }
  // linha real
  ctx.strokeStyle = '#2563eb'; ctx.lineWidth=2; ctx.beginPath(); points.forEach((p,i)=>{ const x = pad + i*stepX; const y = h-pad - (p.y/maxY)*(h-pad*2); if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y); }); ctx.stroke();
  // forecast
  ctx.strokeStyle = '#7c3aed'; ctx.setLineDash([6,4]); ctx.beginPath(); points.forEach((p,i)=>{ if (p.f==null) return; const x = pad + i*stepX; const y = h-pad - (p.f/maxY)*(h-pad*2); if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y); }); ctx.stroke(); ctx.setLineDash([]);
}