/* Santos OS — chart primitives + per-metric chart configs for Analítica */
const Tc = window.T;

function HBar({ label, value, max, color, note }) {
  const pct = Math.max((value/max)*100, 3);
  return (
    <div style={{marginBottom:10}}>
      <div style={{display:'flex', justifyContent:'space-between', marginBottom:4}}>
        <span style={{fontSize:12, color:Tc.fg1, fontWeight:600}}>{label}</span>
        <span style={{fontSize:12, color:Tc.fg2, fontFamily:Tc.mono}}>{note}</span>
      </div>
      <div style={{height:9, background:Tc.border, borderRadius:5, overflow:'hidden'}}><div style={{width:`${pct}%`, height:'100%', background:color, borderRadius:5}}></div></div>
    </div>
  );
}

// deterministic pseudo-series
function series(base, n, varc, seed=7) {
  const out = []; let s = seed;
  for (let i=0;i<n;i++){ s=(s*9301+49297)%233280; const r=s/233280; out.push(Math.max(0, Math.round(base*(1+(r-0.5)*varc)))); }
  return out;
}

function BarSeries({ data, color, labels, unit='' }) {
  const max = Math.max(...data);
  const W=326, H=130, n=data.length, gap=4, bw=(W-(n-1)*gap)/n;
  return (
    <svg viewBox={`0 0 ${W} ${H+20}`} style={{width:'100%', height:'auto', display:'block'}}>
      {data.map((v,i)=>{
        const h=Math.max(3,(v/max)*H), x=i*(bw+gap), y=H-h;
        const last=i===n-1;
        return <g key={i}>
          <rect x={x} y={y} width={bw} height={h} rx={3} fill={last?color:color+'66'} />
          {labels && (i%2===0||last) && <text x={x+bw/2} y={H+14} fontSize="8.5" fill={Tc.fg3} textAnchor="middle" fontFamily={Tc.mono}>{labels[i]}</text>}
        </g>;
      })}
    </svg>
  );
}

function AreaLine({ data, color }) {
  const max=Math.max(...data), min=Math.min(...data), W=326, H=130, n=data.length;
  const pad=(max-min)*0.2||1;
  const pts=data.map((v,i)=>[i*(W/(n-1)), H-((v-min+pad)/((max-min)+pad*2))*H]);
  const path=pts.map((p,i)=>`${i?'L':'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  const area=`${path} L${W} ${H} L0 ${H} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height:'auto', display:'block'}}>
      <defs><linearGradient id={'g'+color.slice(1)} x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity="0.28"/><stop offset="100%" stopColor={color} stopOpacity="0"/></linearGradient></defs>
      <path d={area} fill={`url(#g${color.slice(1)})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
      {pts.map((p,i)=>i===pts.length-1 && <circle key={i} cx={p[0]} cy={p[1]} r="4" fill={color} stroke="#fff" strokeWidth="2"/>)}
    </svg>
  );
}

function Gauge({ pct, color, label }) {
  const r=52, c=2*Math.PI*r, off=c*(1-pct/100);
  return (
    <div style={{display:'flex', justifyContent:'center', padding:'6px 0'}}>
      <svg viewBox="0 0 140 140" style={{width:150, height:150}}>
        <circle cx="70" cy="70" r={r} fill="none" stroke={Tc.border} strokeWidth="12" />
        <circle cx="70" cy="70" r={r} fill="none" stroke={color} strokeWidth="12" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off} transform="rotate(-90 70 70)" />
        <text x="70" y="68" fontSize="26" fontWeight="800" fill={Tc.fg1} textAnchor="middle" fontFamily={Tc.font}>{pct}%</text>
        <text x="70" y="88" fontSize="10" fill={Tc.fg3} textAnchor="middle" fontFamily={Tc.font}>{label}</text>
      </svg>
    </div>
  );
}

function Donut({ segments }) {
  const total=segments.reduce((a,s)=>a+s.v,0); let acc=0;
  const stops=segments.map(s=>{ const a=acc/total*360, b=(acc+s.v)/total*360; acc+=s.v; return `${s.c} ${a}deg ${b}deg`; }).join(',');
  return (
    <div style={{display:'flex', alignItems:'center', gap:18, padding:'4px 0'}}>
      <div style={{width:120, height:120, borderRadius:'50%', background:`conic-gradient(${stops})`, flexShrink:0, position:'relative'}}>
        <div style={{position:'absolute', inset:18, borderRadius:'50%', background:Tc.surface}}></div>
      </div>
      <div style={{flex:1, display:'flex', flexDirection:'column', gap:7}}>
        {segments.map(s=>(
          <div key={s.l} style={{display:'flex', alignItems:'center', gap:8}}>
            <span style={{width:11, height:11, borderRadius:3, background:s.c}}></span>
            <span style={{flex:1, fontSize:12, color:Tc.fg2}}>{s.l}</span>
            <span style={{fontSize:12, fontWeight:700, color:Tc.fg1, fontFamily:Tc.mono}}>{s.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

const DAYS = Array.from({length:14},(_,i)=>`${10+i}`);

// metric → chart card config
window.CHART_CFG = {
  ventas:    { title:'Ventas diarias', sub:'Últimos 14 días · Lempiras', render:()=> <BarSeries data={series(42000,14,0.35,5)} labels={DAYS} color={Tc.primary} /> },
  ticket:    { title:'Ticket promedio', sub:'Tendencia · 14 días', render:()=> <AreaLine data={series(390,14,0.18,9)} color={Tc.secondary} /> },
  captura:   { title:'Captura de cliente', sub:'% de ventas con Club Santos', render:()=> <><Gauge pct={68} color={Tc.primary} label="esta semana" /><AreaLine data={[52,55,58,61,60,64,66,68]} color={Tc.primary} /></> },
  miembros:  { title:'Composición de miembros', sub:'Club Santos por nivel', render:()=> <Donut segments={[{l:'Bronce',v:892,c:'#F59E0B'},{l:'Plata',v:285,c:'#94A3B8'},{l:'Oro',v:56,c:'#E8743A'},{l:'Jade',v:14,c:'#1B9C7E'}]} /> },
  uptime:    { title:'Disponibilidad POS', sub:'Promedio últimas 24h', render:()=> <Gauge pct={99.8} color={Tc.success} label="uptime" /> },
  stockouts: { title:'Stockouts críticos', sub:'SKUs vitales sin stock · 14 días', render:()=> <BarSeries data={[3,2,2,4,3,2,1,2,3,2,2,1,2,2]} labels={DAYS} color={Tc.danger} /> },
  despachos: { title:'Despachos del CEDI', sub:'Valor enviado a sucursales · 14 días', render:()=> <BarSeries data={series(58000,14,0.3,3)} labels={DAYS} color={Tc.primary} /> },
  ordenes:   { title:'Órdenes procesadas', sub:'Pedidos internos · 14 días', render:()=> <BarSeries data={series(16,14,0.5,11)} labels={DAYS} color={Tc.primaryMid} /> },
  transito:  { title:'SKUs en tránsito', sub:'Por destino', render:()=> <Donut segments={[{l:'→ Santa Rita',v:64,c:'#0E4D43'},{l:'→ Copán Ruinas',v:52,c:'#4A7C72'},{l:'En andén',v:26,c:'#C9DFDB'}]} /> },
  frio:      { title:'Cadena de frío', sub:'Temperatura °C · 24h (rango 2–8°C)', render:()=> <AreaLine data={[4.1,4.3,3.9,4.0,4.4,4.2,3.8,4.1,4.5,4.2,4.0,3.9]} color={Tc.info} /> },
  lotes:     { title:'Lotes por vencer', sub:'Inventario por ventana de caducidad', render:()=> <div style={{padding:'4px 0'}}>{[['< 30 días',2,Tc.danger],['30–60 días',2,Tc.warning],['60–90 días',3,Tc.primaryMid]].map(([l,v,c])=><window.HBar key={l} label={l} value={v} max={5} color={c} note={`${v} lotes`} />)}</div> },
};

Object.assign(window, { BarSeries, AreaLine, Gauge, Donut, HBar });
