/* global React */
// Realistic SVG trend chart with ISO 10816-3 reference bands

function TrendChart({ data, thresholds = { warn: 4.5, alarm: 7.1 }, unit = "mm/s", height = 260, showBands = true }) {
  const width = 880;
  const padL = 44, padR = 16, padT = 16, padB = 28;
  const innerW = width - padL - padR;
  const innerH = height - padT - padB;

  const values = data.map(d => d.value);
  const maxY = Math.max(Math.max(...values, thresholds.alarm * 1.15), 10);
  const minY = 0;

  const xStep = innerW / (data.length - 1);
  const yScale = (v) => padT + innerH - ((v - minY) / (maxY - minY)) * innerH;
  const xScale = (i) => padL + i * xStep;

  const linePath = data.map((d, i) => `${i === 0 ? "M" : "L"}${xScale(i).toFixed(1)},${yScale(d.value).toFixed(1)}`).join(" ");
  const areaPath = `${linePath} L${xScale(data.length - 1).toFixed(1)},${yScale(0)} L${xScale(0).toFixed(1)},${yScale(0)} Z`;

  const yTicks = [0, maxY * 0.25, maxY * 0.5, maxY * 0.75, maxY];

  const last = data[data.length - 1];
  const lastStatus = last.value > thresholds.alarm ? "alarm" : last.value > thresholds.warn ? "warn" : "ok";

  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: "100%", height: "auto", display: "block" }}>
      <defs>
        <linearGradient id="trend-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--fg)" stopOpacity="0.08" />
          <stop offset="100%" stopColor="var(--fg)" stopOpacity="0" />
        </linearGradient>
        <pattern id="hatch-alarm" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="4" stroke="var(--alarm)" strokeWidth="0.4" opacity="0.25"/>
        </pattern>
        <pattern id="hatch-warn" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="4" stroke="var(--warn)" strokeWidth="0.4" opacity="0.25"/>
        </pattern>
      </defs>

      {/* Reference bands */}
      {showBands && (
        <>
          <rect x={padL} y={yScale(thresholds.alarm)} width={innerW} height={yScale(0) - yScale(thresholds.alarm)} fill="url(#hatch-alarm)" />
          <rect x={padL} y={yScale(thresholds.warn)} width={innerW} height={yScale(thresholds.alarm) - yScale(thresholds.warn)} fill="url(#hatch-warn)" />
        </>
      )}

      {/* Y gridlines */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={padL} x2={width - padR} y1={yScale(t)} y2={yScale(t)} stroke="var(--hairline)" strokeWidth="1" />
          <text x={padL - 8} y={yScale(t) + 3} fontSize="10" fill="var(--fg-subtle)" textAnchor="end" fontFamily="var(--font-mono)">{t.toFixed(1)}</text>
        </g>
      ))}

      {/* Threshold lines */}
      <line x1={padL} x2={width - padR} y1={yScale(thresholds.warn)} y2={yScale(thresholds.warn)} stroke="var(--warn)" strokeWidth="1" strokeDasharray="3 3" />
      <text x={width - padR - 4} y={yScale(thresholds.warn) - 4} fontSize="9" fill="var(--warn)" textAnchor="end" fontFamily="var(--font-mono)" style={{ textTransform: "uppercase", letterSpacing: "0.08em" }}>
        ISO B/C · {thresholds.warn.toFixed(1)}
      </text>
      <line x1={padL} x2={width - padR} y1={yScale(thresholds.alarm)} y2={yScale(thresholds.alarm)} stroke="var(--alarm)" strokeWidth="1" strokeDasharray="3 3" />
      <text x={width - padR - 4} y={yScale(thresholds.alarm) - 4} fontSize="9" fill="var(--alarm)" textAnchor="end" fontFamily="var(--font-mono)" style={{ textTransform: "uppercase", letterSpacing: "0.08em" }}>
        ISO C/D · {thresholds.alarm.toFixed(1)}
      </text>

      {/* Area + line */}
      <path d={areaPath} fill="url(#trend-fill)" />
      <path d={linePath} stroke="var(--fg)" strokeWidth="1.5" fill="none" />

      {/* Dots */}
      {data.map((d, i) => {
        const s = d.value > thresholds.alarm ? "var(--alarm)" : d.value > thresholds.warn ? "var(--warn)" : "var(--ok)";
        const isLast = i === data.length - 1;
        return (
          <g key={i}>
            <circle cx={xScale(i)} cy={yScale(d.value)} r={isLast ? 4 : 2.2} fill={isLast ? s : "var(--bg)"} stroke={s} strokeWidth={isLast ? 2 : 1.2} />
          </g>
        );
      })}

      {/* Last value callout */}
      <g transform={`translate(${xScale(data.length - 1) - 110}, ${yScale(last.value) - 34})`}>
        <rect x="0" y="0" width="104" height="28" fill="var(--surface)" stroke="var(--border-strong)" />
        <text x="8" y="11" fontSize="8.5" fill="var(--fg-subtle)" style={{ textTransform: "uppercase", letterSpacing: "0.08em" }} fontFamily="var(--font-mono)">OSTATNI</text>
        <text x="8" y="22" fontSize="11" fill="var(--fg)" fontFamily="var(--font-mono)" fontWeight="600">{last.value.toFixed(2)} {unit}</text>
        <rect x="70" y="6" width="28" height="16" fill={`var(--${lastStatus}-weak)`} stroke={`var(--${lastStatus}-border)`} />
        <text x="84" y="17" fontSize="9" fill={`var(--${lastStatus})`} textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="600" style={{ textTransform: "uppercase", letterSpacing: "0.08em" }}>
          {lastStatus === "alarm" ? "ALM" : lastStatus === "warn" ? "WRN" : "OK"}
        </text>
      </g>

      {/* X axis — every 5th label */}
      {data.map((d, i) => i % 6 === 0 && (
        <text key={i} x={xScale(i)} y={height - 10} fontSize="9.5" fill="var(--fg-subtle)" textAnchor="middle" fontFamily="var(--font-mono)">
          {d.date.slice(5)}
        </text>
      ))}

      {/* Baseline */}
      <line x1={padL} x2={width - padR} y1={yScale(0)} y2={yScale(0)} stroke="var(--border-strong)" strokeWidth="1" />
    </svg>
  );
}

Object.assign(window, { TrendChart });
