function linReg(points){
  const n = points.length; if (!n) return { a:0, b:0 };
  let sumX=0,sumY=0,sumXY=0,sumXX=0;
  for (let i=0;i<n;i++){ const x=i, y=points[i]; sumX+=x; sumY+=y; sumXY+=x*y; sumXX+=x*x; }
  const denom = (n*sumXX - sumX*sumX) || 1;
  const a = (n*sumXY - sumX*sumY) / denom; // slope
  const b = (sumY - a*sumX) / n; // intercept
  return { a, b };
}

function drawAxes(ctx, w, h){
  ctx.strokeStyle = '#e5e7eb'; ctx.lineWidth=1;
  ctx.beginPath(); ctx.moveTo(40.5, 10.5); ctx.lineTo(40.5, h-30.5); ctx.lineTo(w-10.5, h-30.5); ctx.stroke();
}

function yScale(values, h){
  const max = Math.max(1, ...values);
  const top = 10, bottom = h-30; const scale = (v)=> bottom - (v/max)*(bottom-top);
  return { max, scale };
}

function pathLine(ctx, values, scale){
  ctx.beginPath();
  values.forEach((v,i)=>{
    const x = 40 + i*((ctx.canvas.width-60)/Math.max(1,values.length-1));
    const y = scale(v);
    if(i===0) ctx.moveTo(x+0.5,y+0.5); else ctx.lineTo(x+0.5,y+0.5);
  });
  ctx.stroke();
}

export async function initPredChart(state, utils){
  const { fmtBRL } = utils;
  const c = document.getElementById('predCanvas'); if (!c) return;
  const ctx = c.getContext('2d'); const w = c.width, h = c.height;
  ctx.clearRect(0,0,w,h);
  drawAxes(ctx, w, h);

  // Coletar série (uso simples: total diário somando PDV + Pedidos)
  const useApiReq = (typeof window !== 'undefined' && typeof window.apiRequest === 'function');
  const [pdvRes, pedRes] = await Promise.all([
    useApiReq ? window.apiRequest('/api/pdv/vendas', { method:'GET' }) : fetch('/api/pdv/vendas', { credentials:'include' }),
    useApiReq ? window.apiRequest('/api/vendas/pedidos', { method:'GET' }) : fetch('/api/vendas/pedidos', { credentials:'include' }),
  ]);
  const pdv = pdvRes.ok ? (await pdvRes.json()).data || [] : [];
  const ped = pedRes.ok ? (await pedRes.json()).data || [] : [];

  const { start, end } = state.filters || {};
  const byDay = {};
  function parseBR(s){
    if (!s) return null;
    try { if (typeof window !== 'undefined' && typeof window.parseDateBR === 'function') return window.parseDateBR(s); } catch(_){ }
    const d = new Date(s); return isNaN(d) ? null : d;
  }
  function inRange(dt){
    if(!dt) return true;
    const d=new Date(dt);
    const sDate = start ? parseBR(start) : null;
    const eDate = end ? parseBR(end) : null;
    if (sDate && d < sDate) return false;
    if (eDate){ const e2=new Date(eDate); e2.setHours(23,59,59,999); if (d > e2) return false; }
    return true;
  }
  pdv.filter(r=>inRange(r.created_at)).forEach(r=>{ const k=(r.created_at||'').substring(0,10); byDay[k]=(byDay[k]||0)+Number(r.valor_total||0); });
  ped.filter(r=>inRange(r.created_at)).forEach(r=>{ const k=(r.created_at||'').substring(0,10); byDay[k]=(byDay[k]||0)+Number(r.valor_total||0); });
  const keys = Object.keys(byDay).sort();
  const series = keys.map(k=>byDay[k]);

  // Previsão por regressão linear simples adicional de 7 pontos
  const { a, b } = linReg(series);
  const future = [];
  for (let i=series.length; i<series.length+7; i++) future.push(Math.max(0, a*i + b));

  const all = series.concat(future);
  const { scale } = yScale(all, h);
  // Desenhar série histórica
  ctx.strokeStyle = '#2563eb'; ctx.lineWidth=2; pathLine(ctx, series, scale);
  // Desenhar previsão tracejada
  ctx.setLineDash([5,4]); ctx.strokeStyle = '#f59e0b'; pathLine(ctx, future.map((v,i)=>{return v;}), (v)=>scale(v)); ctx.setLineDash([]);

  // Meta diária visual
  const meta = (state.thresholds?.metaDiaria)||0;
  const yMeta = scale(meta);
  ctx.strokeStyle = '#10b981'; ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(40.5,yMeta+0.5); ctx.lineTo(w-10.5,yMeta+0.5); ctx.stroke();
  const metaEl = document.getElementById('chartPredMeta'); if (metaEl) metaEl.textContent = 'Meta diária: ' + fmtBRL(meta);

  // Tooltip PT-BR
  let tip;
  const ddmmyyyy = (iso)=>{ try { const d=new Date(iso); const dd=String(d.getDate()).padStart(2,'0'); const mm=String(d.getMonth()+1).padStart(2,'0'); const yy=d.getFullYear(); return `${dd}-${mm}-${yy}`; } catch(_){ return iso; } };
  const showTip = (text, mx, my) => {
    if (!tip) { tip = document.createElement('div'); tip.style.position='absolute'; tip.style.background='#111'; tip.style.color='#fff'; tip.style.padding='6px 8px'; tip.style.borderRadius='6px'; tip.style.fontSize='12px'; tip.style.pointerEvents='none'; tip.style.boxShadow='0 4px 16px rgba(0,0,0,0.2)'; c.parentNode.appendChild(tip); }
    tip.textContent = text; const rect = c.getBoundingClientRect(); tip.style.left = (mx - rect.left + 12) + 'px'; tip.style.top = (my - rect.top - 24) + 'px'; tip.style.display='block';
  };
  const hideTip = ()=>{ if (tip) tip.style.display='none'; };
  const stepX = (w - 60) / Math.max(1, keys.length-1);
  c.onmousemove = (e)=>{
    const rect = c.getBoundingClientRect(); const mx=e.clientX; const my=e.clientY; const xIn = mx - rect.left;
    let i = Math.round((xIn - 40) / stepX); i = Math.max(0, Math.min(i, keys.length-1));
    const k = keys[i]; const v = series[i];
    if (k && typeof v==='number') showTip(`${ddmmyyyy(k)} • Histórico: ${fmtBRL(v)}`, mx, my); else hideTip();
  };
  c.onmouseleave = hideTip;
}