/* JewelLink admin — reusable SVG charts (on-brand, lightweight) */

/* Smooth area/line chart with gridlines + x labels */
function AreaChart({ data, labels, color = 'var(--blue-500)', height = 150, valueFmt = (v)=>v, yTicks = 4 }) {
  const w = 560, h = height, padL = 6, padR = 6, padT = 12, padB = 22;
  const iw = w - padL - padR, ih = h - padT - padB;
  const max = Math.max(...data), min = Math.min(...data, 0);
  const rng = max - min || 1;
  const X = i => padL + (i/(data.length-1))*iw;
  const Y = v => padT + ih - ((v-min)/rng)*ih;
  const pts = data.map((v,i)=>[X(i),Y(v)]);
  // smooth path (catmull-rom → bezier)
  let d = `M${pts[0][0]} ${pts[0][1]}`;
  for (let i=0;i<pts.length-1;i++){
    const [x0,y0]=pts[Math.max(0,i-1)], [x1,y1]=pts[i], [x2,y2]=pts[i+1], [x3,y3]=pts[Math.min(pts.length-1,i+2)];
    const c1x=x1+(x2-x0)/6, c1y=y1+(y2-y0)/6, c2x=x2-(x3-x1)/6, c2y=y2-(y3-y1)/6;
    d += ` C${c1x.toFixed(1)} ${c1y.toFixed(1)} ${c2x.toFixed(1)} ${c2y.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`;
  }
  const area = d + ` L${X(data.length-1)} ${padT+ih} L${X(0)} ${padT+ih} Z`;
  const gid = 'ac'+color.replace(/[^a-z0-9]/gi,'');
  const ticks = Array.from({length:yTicks+1}, (_,i)=> min + (rng*i/yTicks));
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width:'100%', height, display:'block', overflow:'visible' }}>
      <defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={color} stopOpacity="0.22" /><stop offset="100%" stopColor={color} stopOpacity="0.02" />
      </linearGradient></defs>
      {ticks.map((t,i)=>(
        <g key={i}>
          <line x1={padL} y1={Y(t)} x2={w-padR} y2={Y(t)} stroke="var(--gray-200)" strokeWidth="1" strokeDasharray={i===0?'0':'3 4'} />
          <text x={w-padR} y={Y(t)-3} textAnchor="end" fontSize="9.5" fill="var(--gray-400)" fontFamily="var(--font-sans)" fontWeight="600">{valueFmt(Math.round(t))}</text>
        </g>
      ))}
      <path d={area} fill={`url(#${gid})`} />
      <path d={d} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p,i)=> i===pts.length-1 && <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill={color} stroke="#fff" strokeWidth="2" />)}
      {labels && labels.map((l,i)=>(
        <text key={i} x={X(i)} y={h-6} textAnchor="middle" fontSize="10" fill="var(--gray-500)" fontFamily="var(--font-sans)" fontWeight="600">{l}</text>
      ))}
    </svg>
  );
}

/* Grouped/single vertical bars with gridlines */
function BarChart({ data, labels, color = 'var(--navy-600)', height = 160, valueFmt = (v)=>v, max: maxProp }) {
  const w = 560, h = height, padL = 6, padR = 6, padT = 14, padB = 24;
  const iw = w - padL - padR, ih = h - padT - padB;
  const max = maxProp || Math.max(...data) * 1.1;
  const bw = iw / data.length;
  const barW = Math.min(46, bw * 0.5);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width:'100%', height, display:'block', overflow:'visible' }}>
      {[0,0.25,0.5,0.75,1].map((f,i)=>{
        const y = padT + ih - f*ih;
        return <g key={i}>
          <line x1={padL} y1={y} x2={w-padR} y2={y} stroke="var(--gray-200)" strokeWidth="1" strokeDasharray={f===0?'0':'3 4'} />
          <text x={w-padR} y={y-3} textAnchor="end" fontSize="9.5" fill="var(--gray-400)" fontFamily="var(--font-sans)" fontWeight="600">{valueFmt(Math.round(max*f))}</text>
        </g>;
      })}
      {data.map((v,i)=>{
        const x = padL + bw*i + bw/2;
        const bh = (v/max)*ih;
        const grad = 'bg'+i;
        return (
          <g key={i}>
            <defs><linearGradient id={grad} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={color} /><stop offset="100%" stopColor={color} stopOpacity="0.72" />
            </linearGradient></defs>
            <rect x={x-barW/2} y={padT+ih-bh} width={barW} height={bh} rx="5" fill={`url(#${grad})`} />
            <text x={x} y={padT+ih-bh-5} textAnchor="middle" fontSize="10" fontWeight="800" fill="var(--ink)" fontFamily="var(--font-sans)">{valueFmt(v)}</text>
            {labels && <text x={x} y={h-7} textAnchor="middle" fontSize="10" fill="var(--gray-500)" fontFamily="var(--font-sans)" fontWeight="600">{labels[i]}</text>}
          </g>
        );
      })}
    </svg>
  );
}

/* Donut chart with center label + legend */
function DonutChart({ segments, size = 150, thickness = 22, centerTop, centerSub }) {
  const total = segments.reduce((s,x)=>s+x.value,0);
  const r = (size - thickness)/2, cx = size/2, cy = size/2, C = 2*Math.PI*r;
  let acc = 0;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:20 }}>
      <div style={{ position:'relative', width:size, height:size, flex:'0 0 auto' }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform:'rotate(-90deg)' }}>
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--gray-200)" strokeWidth={thickness} />
          {segments.map((s,i)=>{
            const frac = s.value/total, len = frac*C;
            const el = <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={s.color} strokeWidth={thickness}
              strokeDasharray={`${len} ${C-len}`} strokeDashoffset={-acc} strokeLinecap="butt" />;
            acc += len; return el;
          })}
        </svg>
        <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
          <div style={{ fontSize:22, fontWeight:800, letterSpacing:'-.02em', color:'var(--ink)', lineHeight:1 }}>{centerTop}</div>
          {centerSub && <div style={{ fontSize:11, color:'var(--gray-500)', marginTop:2 }}>{centerSub}</div>}
        </div>
      </div>
      <div style={{ flex:1, display:'flex', flexDirection:'column', gap:10 }}>
        {segments.map((s,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:9 }}>
            <span style={{ width:10, height:10, borderRadius:3, background:s.color, flex:'0 0 auto' }} />
            <span style={{ fontSize:13, color:'var(--gray-700)', fontWeight:600, flex:1 }}>{s.label}</span>
            <span style={{ fontSize:13, fontWeight:800, color:'var(--ink)' }}>{s.value}{s.suffix||''}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { AreaChart, BarChart, DonutChart });
