/* eslint-disable */
/* =========================================================
   TEO IoT Dashboard — chart primitives (pure SVG, no deps).
   ========================================================= */

// Multi-series area chart with hover crosshair.
const TimeSeriesChart = ({ series, height=200, range='24h', onRange }) => {
  const w = 720, h = height, pad = 24;
  const all = series.flatMap(s => s.data);
  const max = Math.max(...all), min = Math.min(...all);
  const xAt = (i, len) => pad + i*(w-pad*2)/(len-1);
  const yAt = (v) => h - pad - (v-min)/(max-min||1) * (h-pad*2);
  const [hover, setHover] = React.useState(null);

  return (
    <Card pad={24} style={{ borderRight:'1px solid #EDEDED' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:16 }}>
        <div>
          <Eyebrow>Telemetry · {range}</Eyebrow>
          <div style={{ display:'flex', gap:24, marginTop:12 }}>
            {series.map(s => (
              <div key={s.label}>
                <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:11, letterSpacing:'0.04em', color:'#5A5E6E', textTransform:'uppercase' }}>
                  <span style={{ width:10, height:2, background:s.color }} />{s.label}
                </div>
                <div style={{ fontSize:24, fontWeight:300, letterSpacing:'-0.04em', color:'#0A0F1F', marginTop:4, fontVariantNumeric:'tabular-nums' }}>
                  {s.data[s.data.length-1].toFixed(1)}<span style={{ fontSize:13, color:'#5A5E6E', marginLeft:4 }}>{s.unit}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
        {onRange && <SegmentedControl value={range} onChange={onRange} options={['1h','24h','7d','30d']} />}
      </div>
      <svg width="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display:'block' }}
        onMouseMove={e => {
          const r = e.currentTarget.getBoundingClientRect();
          const x = (e.clientX - r.left) / r.width * w;
          const i = Math.max(0, Math.min(series[0].data.length-1, Math.round((x - pad) / (w-pad*2) * (series[0].data.length-1))));
          setHover(i);
        }}
        onMouseLeave={() => setHover(null)}
      >
        {/* gridlines */}
        <g stroke="#EDEDED" strokeWidth="0.5">
          {[0.25,0.5,0.75].map(f => <line key={f} x1={pad} x2={w-pad} y1={h*f} y2={h*f} />)}
        </g>
        {series.map((s, si) => {
          const pts = s.data.map((v,i) => [xAt(i, s.data.length), yAt(v)]);
          const d = pts.map((p,i) => (i?'L':'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
          const area = d + ` L ${pts[pts.length-1][0]} ${h-pad} L ${pts[0][0]} ${h-pad} Z`;
          const gid = `g-${si}`;
          return (
            <g key={s.label}>
              <defs>
                <linearGradient id={gid} x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0" stopColor={s.color} stopOpacity="0.18"/>
                  <stop offset="1" stopColor={s.color} stopOpacity="0"/>
                </linearGradient>
              </defs>
              <path d={area} fill={`url(#${gid})`} />
              <path d={d} stroke={s.color} strokeWidth="1.5" fill="none" />
            </g>
          );
        })}
        {hover != null && (
          <g>
            <line x1={xAt(hover, series[0].data.length)} x2={xAt(hover, series[0].data.length)} y1={pad} y2={h-pad} stroke="#0A0F1F" strokeWidth="0.5" strokeDasharray="2 3" />
            {series.map(s => (
              <circle key={s.label} cx={xAt(hover, s.data.length)} cy={yAt(s.data[hover])} r="3" fill="#FFF" stroke={s.color} strokeWidth="1.5" />
            ))}
          </g>
        )}
      </svg>
    </Card>
  );
};

// Distribution bar chart
const DistributionChart = ({ title, bars, total }) => {
  const max = Math.max(...bars.map(b => b[1]));
  return (
    <Card pad={24}>
      <Eyebrow>{title}</Eyebrow>
      {total && <div style={{ fontSize:28, fontWeight:300, letterSpacing:'-0.04em', color:'#0A0F1F', marginTop:8, marginBottom:20, fontVariantNumeric:'tabular-nums' }}>{total}</div>}
      <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop: total?0:16 }}>
        {bars.map(([l,v,c]) => (
          <div key={l} style={{ display:'grid', gridTemplateColumns:'110px 1fr 50px', gap:12, alignItems:'center' }}>
            <div style={{ fontSize:13, color:'#242739' }}>{l}</div>
            <div style={{ height:8, background:'#F6F7F9', position:'relative', border:'1px solid #EDEDED' }}>
              <div style={{ position:'absolute', inset:'0 auto 0 0', width:`${v/max*100}%`, background: c || '#0A0F1F' }} />
            </div>
            <div style={{ fontSize:13, color:'#0A0F1F', textAlign:'right', fontVariantNumeric:'tabular-nums', fontFamily:"'IBM Plex Mono', monospace" }}>{v}</div>
          </div>
        ))}
      </div>
    </Card>
  );
};

// Gauge — radial half-circle, used for SoC, load, etc.
const Gauge = ({ value, min=0, max=100, unit='', label, warn, crit, size=140 }) => {
  const r = size/2 - 8;
  const cx = size/2, cy = size/2 + 8;
  const ang = (v) => Math.PI - (v-min)/(max-min) * Math.PI;
  const arc = (a1, a2, color, w=4) => {
    const x1 = cx + r*Math.cos(a1), y1 = cy - r*Math.sin(a1);
    const x2 = cx + r*Math.cos(a2), y2 = cy - r*Math.sin(a2);
    const large = Math.abs(a2 - a1) > Math.PI ? 1 : 0;
    const sweep = a2 < a1 ? 1 : 0;
    return <path d={`M ${x1} ${y1} A ${r} ${r} 0 ${large} ${sweep} ${x2} ${y2}`} fill="none" stroke={color} strokeWidth={w} strokeLinecap="butt" />;
  };
  const valAng = ang(Math.max(min, Math.min(max, value)));
  const color = crit!=null && value>=crit ? '#C44A4A'
              : warn!=null && value>=warn ? '#E0A13B'
              : '#3A6FF8';
  return (
    <div style={{ textAlign:'center' }}>
      <svg width={size} height={size/2 + 24}>
        {arc(Math.PI, 0, '#EDEDED', 4)}
        {arc(Math.PI, valAng, color, 4)}
      </svg>
      <div style={{ fontSize:28, fontWeight:300, letterSpacing:'-0.04em', color:'#0A0F1F', marginTop:-8, fontVariantNumeric:'tabular-nums' }}>
        {value}<span style={{ fontSize:13, color:'#5A5E6E', marginLeft:4 }}>{unit}</span>
      </div>
      <Eyebrow style={{ marginTop:4 }}>{label}</Eyebrow>
    </div>
  );
};

// =============================================================
// Donut chart — circular segmented breakdown.
// `slices`: [{ label, value, color }]
// Renders the donut + a key beside it. Always on-brand colours.
// =============================================================
const Donut = ({ title, total, totalLabel, slices, size=180, strokeWidth=24 }) => {
  const isMobile = useIsMobile();
  const sum = slices.reduce((s, x) => s + x.value, 0) || 1;
  const cx = size/2, cy = size/2;
  const r = size/2 - strokeWidth/2 - 2;
  const C = 2 * Math.PI * r;
  let offset = 0;
  const arcs = slices.map(s => {
    const len = (s.value / sum) * C;
    const a = { ...s, len, offset };
    offset += len;
    return a;
  });
  return (
    <Card pad={isMobile ? 16 : 24}>
      <Eyebrow>{title}</Eyebrow>
      <div style={{
        display: isMobile ? 'flex' : 'grid',
        flexDirection: isMobile ? 'column' : undefined,
        alignItems:'center',
        gap: isMobile ? 18 : 24,
        gridTemplateColumns: isMobile ? undefined : `${size}px 1fr`,
        marginTop:16
      }}>
        <div style={{ position:'relative', width:size, height:size, flexShrink:0 }}>
          <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display:'block', transform:'rotate(-90deg)' }}>
            <circle cx={cx} cy={cy} r={r} fill="none" stroke="#EDEDED" strokeWidth={strokeWidth} />
            {arcs.map((a, i) => (
              <circle key={i} cx={cx} cy={cy} r={r} fill="none"
                      stroke={a.color} strokeWidth={strokeWidth}
                      strokeDasharray={`${a.len} ${C - a.len}`}
                      strokeDashoffset={-a.offset} />
            ))}
          </svg>
          <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
            <div style={{ fontSize:30, fontWeight:300, letterSpacing:'-0.05em', color:'#0A0F1F', fontVariantNumeric:'tabular-nums' }}>{total}</div>
            {totalLabel && <div style={{ fontSize:11, color:'#5A5E6E', letterSpacing:'0.08em', textTransform:'uppercase', marginTop:2 }}>{totalLabel}</div>}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:10, width: isMobile ? '100%' : 'auto' }}>
          {slices.map((s, i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'14px 1fr auto auto', gap:10, alignItems:'center', fontSize:13 }}>
              <span style={{ width:12, height:12, background:s.color }} />
              <span style={{ color:'#0A0F1F' }}>{s.label}</span>
              <span style={{ fontFamily:'IBM Plex Mono, monospace', color:'#0A0F1F', fontVariantNumeric:'tabular-nums' }}>{s.value}</span>
              <span style={{ fontFamily:'IBM Plex Mono, monospace', color:'#5A5E6E', fontVariantNumeric:'tabular-nums', minWidth:42, textAlign:'right' }}>{((s.value/sum)*100).toFixed(0)}%</span>
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
};

// =============================================================
// RadialBar — concentric arc gauges showing multiple metrics
// `rings`: [{ label, value, max, color, unit }]
// =============================================================
const RadialBar = ({ title, rings, size=200 }) => {
  const isMobile = useIsMobile();
  const cx = size/2, cy = size/2;
  const ringWidth = 12;
  const gap = 6;
  return (
    <Card pad={isMobile ? 16 : 24}>
      <Eyebrow>{title}</Eyebrow>
      <div style={{
        display: isMobile ? 'flex' : 'grid',
        flexDirection: isMobile ? 'column' : undefined,
        alignItems:'center',
        gap: isMobile ? 18 : 24,
        gridTemplateColumns: isMobile ? undefined : `${size}px 1fr`,
        marginTop:16
      }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display:'block' }}>
          <g transform={`rotate(-90 ${cx} ${cy})`}>
            {rings.map((r, i) => {
              const radius = size/2 - 8 - i*(ringWidth + gap);
              const C = 2 * Math.PI * radius;
              const len = Math.max(0, Math.min(1, r.value / r.max)) * C;
              return (
                <g key={i}>
                  <circle cx={cx} cy={cy} r={radius} fill="none" stroke="#EDEDED" strokeWidth={ringWidth} />
                  <circle cx={cx} cy={cy} r={radius} fill="none" stroke={r.color} strokeWidth={ringWidth}
                          strokeDasharray={`${len} ${C - len}`} strokeLinecap="butt" />
                </g>
              );
            })}
          </g>
        </svg>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {rings.map((r, i) => (
            <div key={i}>
              <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:11, letterSpacing:'0.04em', textTransform:'uppercase', color:'#5A5E6E' }}>
                <span style={{ width:10, height:2, background:r.color }} />
                {r.label}
              </div>
              <div style={{ fontSize:20, fontWeight:300, letterSpacing:'-0.03em', color:'#0A0F1F', marginTop:2, fontVariantNumeric:'tabular-nums' }}>
                {r.value}{r.unit && <span style={{ fontSize:12, color:'#5A5E6E', marginLeft:4 }}>{r.unit}</span>}
                <span style={{ fontSize:12, color:'#5A5E6E', marginLeft:8, fontVariantNumeric:'tabular-nums' }}>· {((r.value/r.max)*100).toFixed(0)}%</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
};

// =============================================================
// Heatmap — day × hour grid (or any 2D matrix).
// `matrix`: 2D array of numbers, `rows` and `cols` are labels.
// `palette` defaults to navy → accent blue.
// =============================================================
const Heatmap = ({ title, matrix, rows, cols, max, palette }) => {
  const isMobile = useIsMobile();
  const computedMax = max != null ? max : Math.max(...matrix.flat(), 1);
  const colorFor = (v) => {
    const t = Math.max(0, Math.min(1, v / computedMax));
    if (palette === 'warn') {
      if (t < 0.5) return blend('#0F162D', '#E0A13B', t * 2);
      return blend('#E0A13B', '#C44A4A', (t - 0.5) * 2);
    }
    return blend('#0F162D', '#3A6FF8', t);
  };
  const labelCol = isMobile ? 38 : 70;
  return (
    <Card pad={isMobile ? 16 : 24}>
      <Eyebrow>{title}</Eyebrow>
      <div style={{ marginTop:16 }}>
        <div style={{ display:'grid', gridTemplateColumns:`${labelCol}px repeat(${cols.length}, 1fr)`, gap:2 }}>
          <div />
          {cols.map((c, i) => (
            <div key={i} style={{ fontSize:10, color:'#5A5E6E', textAlign:'center', fontFamily:'IBM Plex Mono, monospace' }}>{c}</div>
          ))}
          {rows.map((row, ri) => (
            <React.Fragment key={ri}>
              <div style={{ fontSize:11, color:'#5A5E6E', display:'flex', alignItems:'center', justifyContent:'flex-end', paddingRight:6 }}>{row}</div>
              {matrix[ri].map((v, ci) => (
                <div key={ci} title={`${row} · ${cols[ci]} · ${v}`} style={{
                  height: isMobile ? 22 : 18, background: colorFor(v), border:'1px solid #FFF', boxSizing:'border-box'
                }} />
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>
      {/* Legend */}
      <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:14, fontSize:11, color:'#5A5E6E', fontFamily:'IBM Plex Mono, monospace' }}>
        <span>0</span>
        <div style={{ flex:1, height:6, background:`linear-gradient(to right, ${palette==='warn' ? '#0F162D, #E0A13B, #C44A4A' : '#0F162D, #3A6FF8'})` }} />
        <span>{computedMax}</span>
      </div>
    </Card>
  );
};

// Hex-blend helper (used by Heatmap)
function blend(a, b, t) {
  const p = (h) => [1,3,5].map(i => parseInt(h.substr(i,2), 16));
  const [ar, ag, ab] = p(a);
  const [br, bg, bb] = p(b);
  const m = (x, y) => Math.round(x + (y - x) * t).toString(16).padStart(2,'0');
  return `#${m(ar,br)}${m(ag,bg)}${m(ab,bb)}`;
}

// =============================================================
// Stacked bar — categorical breakdown across N buckets.
// `bars`: [{ label, segments: [{ value, color, label }] }]
// =============================================================
const StackedBar = ({ title, bars }) => {
  const totals = bars.map(b => b.segments.reduce((s, x) => s + x.value, 0));
  const max = Math.max(...totals, 1);
  return (
    <Card pad={24}>
      <Eyebrow>{title}</Eyebrow>
      <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:16 }}>
        {bars.map((b, i) => {
          const total = totals[i];
          return (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'110px 1fr 60px', gap:12, alignItems:'center' }}>
              <div style={{ fontSize:13, color:'#242739' }}>{b.label}</div>
              <div style={{ display:'flex', height:14, background:'#F6F7F9', border:'1px solid #EDEDED', width:`${(total/max)*100}%` }}>
                {b.segments.map((s, si) => (
                  <div key={si} title={`${s.label}: ${s.value}`} style={{ flex: s.value, background: s.color, minWidth: s.value > 0 ? 2 : 0 }} />
                ))}
              </div>
              <div style={{ textAlign:'right', fontSize:13, fontFamily:'IBM Plex Mono, monospace', color:'#0A0F1F', fontVariantNumeric:'tabular-nums' }}>{total}</div>
            </div>
          );
        })}
      </div>
    </Card>
  );
};

Object.assign(window, { TimeSeriesChart, DistributionChart, Gauge, Donut, RadialBar, Heatmap, StackedBar });
