/* global React */
const { useMemo } = React;

// smooth a series of [x,y] into a catmull-rom path
function smooth(pts) {
  if (pts.length < 2) return "";
  let d = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i], p1 = pts[i], p2 = pts[i + 1], p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C ${c1x} ${c1y} ${c2x} ${c2y} ${p2[0]} ${p2[1]}`;
  }
  return d;
}

const SOIL = {
  "24h": [40, 44, 38, 52, 96, 60, 48, 44, 50, 46, 58, 52, 68, 56, 62, 88, 70],
  "48h": [52, 48, 60, 44, 70, 58, 84, 62, 50, 56, 48, 66, 54, 60, 78, 64, 58],
};

function SoilMoistureChart({ range }) {
  const W = 388, H = 150, pad = 6;
  const data = SOIL[range];
  const max = 100, min = 30;
  const pts = useMemo(() => data.map((v, i) => {
    const x = pad + (i / (data.length - 1)) * (W - pad * 2);
    const y = H - 18 - ((v - min) / (max - min)) * (H - 40);
    return [x, y];
  }), [range]);

  const peakIdx = data.indexOf(Math.max(...data));
  const peak = pts[peakIdx];
  const line = smooth(pts);
  const area = `${line} L ${pts[pts.length - 1][0]} ${H - 6} L ${pts[0][0]} ${H - 6} Z`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}>
      <defs>
        <linearGradient id="soilFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#c6e84b" stopOpacity="0.32" />
          <stop offset="1" stopColor="#c6e84b" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 1, 2, 3].map((i) => (
        <line key={i} x1="0" x2={W} y1={20 + i * 30} y2={20 + i * 30}
              stroke="#1b1e14" strokeOpacity="0.06" strokeWidth="1" />
      ))}
      <path d={area} fill="url(#soilFill)" />
      <path d={line} fill="none" stroke="#2c331f" strokeWidth="2.2"
            strokeLinecap="round" strokeLinejoin="round" />
      <line x1={peak[0]} y1="16" x2={peak[0]} y2={H - 6}
            stroke="#1b1e14" strokeOpacity="0.4" strokeWidth="1" strokeDasharray="3 4" />
      <circle cx={peak[0]} cy={peak[1]} r="5" fill="#1b1e14" />
      <circle cx={peak[0]} cy={peak[1]} r="9" fill="none" stroke="#1b1e14" strokeOpacity="0.25" />
      {/* tooltip */}
      <g transform={`translate(${Math.min(Math.max(peak[0] - 52, 0), W - 104)} ${peak[1] - 34})`}>
        <rect width="104" height="26" rx="13" fill="#fff"
              style={{ filter: "drop-shadow(0 6px 14px rgba(0,0,0,0.18))" }} />
        <text x="14" y="17" fontSize="12.5" fontFamily="Onest" fill="#8b9079">Nivel alto</text>
        <text x="74" y="17" fontSize="12.5" fontFamily="Onest" fontWeight="700" fill="#1b1e14">
          {range === "24h" ? 68 : 74}
        </text>
      </g>
    </svg>
  );
}

const NPK = [
  { k: "Nitrógeno", v: 48 },
  { k: "Fósforo", v: 40 },
  { k: "Potasio", v: 55 },
];

function NPKBars({ mode }) {
  const segs = 28;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      {NPK.map(({ k, v }) => {
        const val = mode === "record" ? Math.round(v * 0.82) : v;
        const filled = Math.round((val / 100) * segs);
        return (
          <div key={k}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 9 }}>
              <span style={{ fontSize: 15, fontWeight: 500, color: "var(--ink-2)" }}>{k}</span>
              <span style={{ fontSize: 14, fontWeight: 600, color: "var(--muted)" }}>
                <b style={{ color: "var(--ink)", fontWeight: 700 }}>{val}</b>/100
              </span>
            </div>
            <div style={{ display: "flex", gap: 3 }}>
              {Array.from({ length: segs }).map((_, i) => (
                <div key={i} style={{
                  flex: 1, height: 4, borderRadius: 2,
                  background: i < filled ? "#2c331f" : "#d7dac9",
                  transition: "background 0.4s ease", transitionDelay: `${i * 8}ms`,
                }} />
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// Leaf area index — two overlapping textured donuts on the dark card
function LeafDonut() {
  const Ring = ({ cx, r, stroke, sw, dash, op = 1 }) => (
    <circle cx={cx} cy="70" r={r} fill="none" stroke={stroke}
            strokeWidth={sw} strokeDasharray={dash} opacity={op}
            transform={`rotate(-90 ${cx} 70)`} />
  );
  return (
    <svg viewBox="0 0 230 150" width="100%" style={{ display: "block" }}>
      {/* left donut (lime, dotted) */}
      <circle cx="74" cy="70" r="46" fill="#454b32" />
      <Ring cx={74} r={46} stroke="#c6e84b" sw={16} dash="1.5 5" />
      <Ring cx={74} r={46} stroke="#c6e84b" sw={16} dash="64 400" op={0.9} />
      <circle cx="74" cy="70" r="30" fill="#373c2a" />
      <text x="74" y="76" textAnchor="middle" fontSize="20" fontWeight="700"
            fontFamily="Onest" fill="#f2f3ea">~2.2</text>
      {/* right donut (striped) */}
      <circle cx="158" cy="70" r="40" fill="#3f4530" />
      <Ring cx={158} r={40} stroke="#a7ab98" sw={13} dash="2 4" op={0.6} />
      <Ring cx={158} r={40} stroke="#c6e84b" sw={13} dash="50 400" />
      <circle cx="158" cy="70" r="26" fill="#373c2a" />
      <text x="158" y="76" textAnchor="middle" fontSize="18" fontWeight="700"
            fontFamily="Onest" fill="#f2f3ea">~1.4</text>
    </svg>
  );
}

Object.assign(window, { SoilMoistureChart, NPKBars, LeafDonut });
