/* =========================================================
   軽量SVGチャート群  (members/charts.jsx)
   ========================================================= */
const C = { blue:"#1a6fd0", blueDeep:"#0f4f9e", blueLine:"#cfe2f6", orange:"#f5871f", orangeDeep:"#d96f08",
            red:"#e05a37", green:"#1f9d6b", grid:"#e8eef6", sub:"#6c7886", faint:"#9aa4b1", ink:"#27313f" };

/* ---- 折れ線（複数系列） ---- */
function LineChart({ labels, series, height=220, yMin, yMax, fmt }){
  const W=720, H=height, pad={l:46,r:18,t:16,b:30};
  const all=series.flatMap(s=>s.data);
  const mn = yMin!=null?yMin:Math.min(...all), mx = yMax!=null?yMax:Math.max(...all);
  const span=(mx-mn)||1;
  const x=i=> pad.l + i*((W-pad.l-pad.r)/(labels.length-1));
  const y=v=> pad.t + (1-(v-mn)/span)*(H-pad.t-pad.b);
  const ticks=4;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{display:"block"}}>
      {Array.from({length:ticks+1}).map((_,i)=>{ const v=mn+span*i/ticks; const yy=y(v);
        return <g key={i}><line x1={pad.l} x2={W-pad.r} y1={yy} y2={yy} stroke={C.grid}/>
          <text x={pad.l-8} y={yy+4} textAnchor="end" fontSize="10" fill={C.faint}>{fmt?fmt(v):Math.round(v*10)/10}</text></g>; })}
      {labels.map((l,i)=> (i%Math.ceil(labels.length/8||1)===0)&&
        <text key={i} x={x(i)} y={H-10} textAnchor="middle" fontSize="10" fill={C.sub}>{l}</text>)}
      {series.map((s,si)=>{ const d=s.data.map((v,i)=>`${i===0?"M":"L"}${x(i)},${y(v)}`).join(" ");
        return <g key={si}>
          {s.fill && <path d={`${d} L${x(s.data.length-1)},${H-pad.b} L${x(0)},${H-pad.b} Z`} fill={s.color} opacity=".09"/>}
          <path d={d} fill="none" stroke={s.color} strokeWidth={s.w||2.5} strokeLinejoin="round" strokeLinecap="round" strokeDasharray={s.dash||"0"}/>
          {s.data.map((v,i)=><circle key={i} cx={x(i)} cy={y(v)} r={s.dot||3} fill="#fff" stroke={s.color} strokeWidth="2"/>)}
        </g>; })}
    </svg>
  );
}

/* ---- 横棒（カテゴリ比較） ---- */
function BarsH({ items, max, height=210, unit="" }){
  const mx = max || Math.max(...items.map(i=>i.value));
  const rowH = height/items.length;
  return (
    <svg viewBox={`0 0 720 ${height}`} width="100%" style={{display:"block"}}>
      {items.map((it,i)=>{ const y=i*rowH+rowH*0.18; const h=rowH*0.5;
        const w=Math.max(2,(it.value/mx)*(720-180));
        return <g key={i}>
          <text x={0} y={y+h*0.72} fontSize="12" fontWeight={it.me?"700":"500"} fill={it.me?C.orangeDeep:C.ink}>{it.label}</text>
          <rect x={150} y={y} width={720-180} height={h} rx={h/2} fill={C.grid}/>
          <rect x={150} y={y} width={w} height={h} rx={h/2} fill={it.me?C.orange:(it.color||C.blue)}/>
          <text x={150+w+8} y={y+h*0.74} fontSize="11.5" fontWeight="700" fill={it.me?C.orangeDeep:C.blueDeep}>{it.value.toLocaleString()}{unit}</text>
        </g>; })}
    </svg>
  );
}

/* ---- ヒストグラム（縦棒 / 2系列重ね） ---- */
function Histo({ items, height=230 }){
  const W=720, pad={l:8,r:8,t:14,b:46};
  const mx=Math.max(...items.flatMap(i=>[i.wins,i.mine||0]));
  const bw=(W-pad.l-pad.r)/items.length;
  const y=v=>pad.t+(1-v/mx)*(height-pad.t-pad.b);
  return (
    <svg viewBox={`0 0 ${W} ${height}`} width="100%" style={{display:"block"}}>
      <line x1={pad.l} x2={W-pad.r} y1={height-pad.b} y2={height-pad.b} stroke={C.grid}/>
      {items.map((it,i)=>{ const cx=pad.l+i*bw+bw/2; const w=bw*0.32;
        const hw=(height-pad.b)-y(it.wins); const hm=(height-pad.b)-y(it.mine||0);
        return <g key={i}>
          <rect x={cx-w-2} y={y(it.wins)} width={w} height={Math.max(0,hw)} rx="4" fill={C.blue}/>
          <rect x={cx+2} y={y(it.mine||0)} width={w} height={Math.max(0,hm)} rx="4" fill={C.orange}/>
          <text x={cx} y={height-pad.b+16} textAnchor="middle" fontSize="9.5" fill={C.sub}>{it.band}</text>
        </g>; })}
    </svg>
  );
}

/* ---- ドーナツ ---- */
function Donut({ value, max=100, label, sub, color, size=150, unit="%" }){
  const r=size/2-14, cx=size/2, cy=size/2, circ=2*Math.PI*r;
  const pct=Math.min(1,value/max), col=color||C.blue;
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={C.grid} strokeWidth="12"/>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={col} strokeWidth="12" strokeLinecap="round"
        strokeDasharray={`${circ*pct} ${circ}`} transform={`rotate(-90 ${cx} ${cy})`}/>
      <text x={cx} y={cy-1} textAnchor="middle" fontSize="26" fontWeight="900" fill={col} style={{fontVariantNumeric:"tabular-nums"}}>{value}<tspan fontSize="13">{unit}</tspan></text>
      {label && <text x={cx} y={cy+18} textAnchor="middle" fontSize="11" fill={C.sub}>{label}</text>}
    </svg>
  );
}

/* ---- 半円ゲージ（シミュレーター用） ---- */
function Gauge({ value, color, label, sub, size=260 }){
  const W=size, H=size*0.62, cx=W/2, cy=H-8, r=W/2-26;
  const a0=Math.PI, a1=0;
  const ang=a0+(a1-a0)*(value/100);
  const pt=(an,rad)=>[cx+Math.cos(an)*rad, cy-Math.sin(an)*rad];
  const arc=(s,e,rad)=>{ const[x1,y1]=pt(s,rad),[x2,y2]=pt(e,rad); const large=(s-e)>Math.PI?1:0;
    return `M${x1},${y1} A${rad},${rad} 0 ${large} 1 ${x2},${y2}`; };
  const col=color||C.blue;
  const [hx,hy]=pt(ang,r);
  return (
    <svg viewBox={`0 0 ${W} ${H+30}`} width="100%" style={{maxWidth:size}}>
      <path d={arc(a0,a1,r)} fill="none" stroke={C.grid} strokeWidth="18" strokeLinecap="round"/>
      <path d={arc(a0,ang,r)} fill="none" stroke={col} strokeWidth="18" strokeLinecap="round"/>
      <circle cx={hx} cy={hy} r="9" fill="#fff" stroke={col} strokeWidth="4"/>
      <text x={cx} y={cy-12} textAnchor="middle" fontSize="40" fontWeight="900" fill={col} style={{fontVariantNumeric:"tabular-nums"}}>{value}<tspan fontSize="18">%</tspan></text>
      {label && <text x={cx} y={H+14} textAnchor="middle" fontSize="13" fontWeight="700" fill={C.ink}>{label}</text>}
      {sub && <text x={cx} y={H+30} textAnchor="middle" fontSize="11" fill={C.sub}>{sub}</text>}
    </svg>
  );
}

/* ---- レーダー（多角形比較） ---- */
function Radar({ axes, series, size=260 }){
  const cx=size/2, cy=size/2, r=size/2-34, n=axes.length;
  const pt=(i,val)=>{ const a=-Math.PI/2 + i*2*Math.PI/n; const rr=r*val;
    return [cx+Math.cos(a)*rr, cy+Math.sin(a)*rr]; };
  const rings=[0.25,0.5,0.75,1];
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width="100%" style={{maxWidth:size, margin:"0 auto"}}>
      {rings.map((rg,ri)=><polygon key={ri} points={axes.map((_,i)=>pt(i,rg).join(",")).join(" ")} fill="none" stroke={C.grid}/>)}
      {axes.map((ax,i)=>{ const[x,y]=pt(i,1.0); const[lx,ly]=pt(i,1.2);
        return <g key={i}><line x1={cx} y1={cy} x2={x} y2={y} stroke={C.grid}/>
          <text x={lx} y={ly+3} textAnchor="middle" fontSize="10" fill={C.sub}>{ax}</text></g>; })}
      {series.map((s,si)=>(
        <polygon key={si} points={s.values.map((v,i)=>pt(i,v).join(",")).join(" ")}
          fill={s.color} fillOpacity={s.me?.22:.12} stroke={s.color} strokeWidth={s.me?2.5:1.8}/>
      ))}
    </svg>
  );
}

/* ---- スパークライン ---- */
function Spark({ data, color, w=110, h=34 }){
  const mn=Math.min(...data), mx=Math.max(...data), sp=(mx-mn)||1;
  const x=i=>i*(w/(data.length-1)), y=v=>h-2-((v-mn)/sp)*(h-4);
  const d=data.map((v,i)=>`${i?"L":"M"}${x(i)},${y(v)}`).join(" ");
  return <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
    <path d={`${d} L${w},${h} L0,${h} Z`} fill={color} opacity=".12"/>
    <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round"/>
  </svg>;
}

Object.assign(window, { LineChart, BarsH, Histo, Donut, Gauge, Radar, Spark, CHART_C:C });
