// ChartLine.jsx — EKG-style temperature line chart
// Usage: <ChartLine data={[...]} threshold={8} label="MUC → AMS" />

const chartLineStyles = {
  wrap: {
    background: '#37657B',
    border: '1px solid #4A7A90',
    borderRadius: 4,
    padding: '20px 22px',
    fontFamily: "'DM Sans', sans-serif",
  },
  header: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    marginBottom: 16,
  },
  title: { fontSize: 12, fontWeight: 600, color: '#F0EEE9', letterSpacing: '0.02em' },
  badge: {
    fontSize: 10, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
    padding: '3px 8px', borderRadius: 2, background: 'rgba(178,222,123,0.15)', color: '#B2DE7B',
  },
  svgWrap: { width: '100%', overflow: 'hidden' },
  xLabels: { display: 'flex', justifyContent: 'space-between', marginTop: 6 },
  xLabel: { fontSize: 10, color: 'rgba(240,238,233,0.3)', letterSpacing: '0.04em' },
};

function ChartLine({ data, threshold = 8, label = 'Temperature', unit = '°C', height = 80 }) {
  const svgRef = React.useRef(null);
  const [w, setW] = React.useState(400);

  React.useEffect(() => {
    if (svgRef.current) setW(svgRef.current.clientWidth || 400);
  }, []);

  const pts = data || Array.from({ length: 24 }, (_, i) => ({
    t: `${String(i).padStart(2,'0')}:00`,
    v: 4 + Math.sin(i * 0.5) * 1.2 + (Math.random() - 0.5) * 0.4,
  }));

  const vals = pts.map(p => p.v);
  const min = Math.min(...vals) - 1;
  const max = Math.max(...vals, threshold) + 1;
  const pad = 8;

  const toX = i => pad + (i / (pts.length - 1)) * (w - pad * 2);
  const toY = v => height - pad - ((v - min) / (max - min)) * (height - pad * 2);

  const pathD = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${toX(i).toFixed(1)},${toY(p.v).toFixed(1)}`).join(' ');
  const threshY = toY(threshold);

  const isOk = vals.every(v => v <= threshold);

  return (
    <div style={chartLineStyles.wrap}>
      <div style={chartLineStyles.header}>
        <span style={chartLineStyles.title}>{label}</span>
        <span style={{
          ...chartLineStyles.badge,
          background: isOk ? 'rgba(178,222,123,0.15)' : 'rgba(254,236,126,0.15)',
          color: isOk ? '#B2DE7B' : '#FEEC7E',
        }}>{isOk ? `Within Range` : `Deviation`}</span>
      </div>
      <div style={chartLineStyles.svgWrap} ref={svgRef}>
        <svg width="100%" height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none">
          {/* threshold line */}
          <line x1={pad} y1={threshY} x2={w - pad} y2={threshY}
            stroke="#FEEC7E" strokeWidth="1" strokeDasharray="4 4" opacity="0.4" />
          {/* area fill */}
          <path d={`${pathD} L${toX(pts.length-1)},${height} L${toX(0)},${height} Z`}
            fill="url(#grad)" opacity="0.15" />
          {/* line */}
          <path d={pathD} fill="none" stroke={isOk ? '#B2DE7B' : '#FEEC7E'} strokeWidth="1.5"
            strokeLinejoin="round" strokeLinecap="round" />
          <defs>
            <linearGradient id="grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={isOk ? '#B2DE7B' : '#FEEC7E'} stopOpacity="1"/>
              <stop offset="100%" stopColor={isOk ? '#B2DE7B' : '#FEEC7E'} stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* current value dot */}
          <circle cx={toX(pts.length - 1)} cy={toY(vals[vals.length - 1])}
            r="3" fill={isOk ? '#B2DE7B' : '#FEEC7E'} />
        </svg>
      </div>
      <div style={chartLineStyles.xLabels}>
        {['00:00','06:00','12:00','18:00','Now'].map(t => (
          <span key={t} style={chartLineStyles.xLabel}>{t}</span>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ChartLine });
