/* ============================================================
   SKYVIDYA — ScoreGauge (HUD radial)
   Full 360° ring · 48 precision ticks · volumetric glow ·
   RES_LVL badge · indicator dots · outer pulsing HUD rings.
   Skyvidya palette (success→cyan→warn→coral), JetBrains Mono.
   Exported as ResilienceGauge so existing usages auto-upgrade.
   `compact` strips outer rings + bottom pill for cards/selo.
   ============================================================ */
const { useState, useEffect, useRef } = React;

function gaugeColor(v) {
  if (v >= 80) return { main: "var(--risk-low)",       rgb: "78,224,142" };
  if (v >= 65) return { main: "var(--sv-cyan)",        rgb: "78,210,210" };
  if (v >= 45) return { main: "var(--sv-warn)",        rgb: "246,198,18" };
  return { main: "var(--risk-critical)", rgb: "255,92,46" };
}

function ResilienceGauge({
  value = 72, max = 100,
  label = "ÍNDICE DE RESILIÊNCIA", sublabel = "Rating multicritério proprietário",
  size = 252, ticks = 48, compact = false,
  showDots = true, showLabel = true, showRings = true, badge = "RES_LVL",
}) {
  const [disp, setDisp] = useState(0);
  const [fill, setFill] = useState(0);            // 0..1
  const ivRef = useRef(null);
  const target = Math.max(0, Math.min(max, value));
  const pct = (target / max) * 100;
  const col = gaugeColor(pct);

  useEffect(() => {
    clearInterval(ivRef.current);
    const start = performance.now(), dur = 1100;
    setFill(0); setDisp(0);
    ivRef.current = setInterval(() => {
      const t = Math.min(1, (performance.now() - start) / dur);
      const e = 1 - Math.pow(1 - t, 3);
      setDisp(Math.round(target * e));
      setFill(e * (target / max));
      if (t >= 1) clearInterval(ivRef.current);
    }, 24);
    return () => clearInterval(ivRef.current);
  }, [target, max]);

  const R = 90, C = 2 * Math.PI * R;
  const offset = C - fill * C;
  const dispPct = (disp / max) * 100;

  // 48 precision ticks at the ring edge
  const tickEls = [];
  for (let i = 0; i < ticks; i++) {
    const active = (i * (100 / ticks)) < dispPct;
    tickEls.push(
      <line key={i} x1="100" y1="5" x2="100" y2="12"
        stroke={active ? col.main : "rgba(255,255,255,0.08)"} strokeWidth="1.5"
        transform={`rotate(${i * (360 / ticks)} 100 100)`}
        style={{ transition: "stroke 240ms" }} />
    );
  }
  const dots = 5, dotsActive = Math.round((disp / max) * dots);

  return (
    <div className={"sg-wrap" + (compact ? " sg-compact" : "")} style={{ maxWidth: size }}>
      <div className="sg-dial" style={{ "--sg-color": col.main, "--sg-glow": `rgba(${col.rgb},0.22)` }}>
        {showRings && !compact && (
          <>
            <div className="sg-ring sg-ring1"></div>
            <div className="sg-ring sg-ring2"></div>
            <div className="sg-ring sg-ring3"></div>
          </>
        )}
        <svg className="sg-svg" viewBox="0 0 200 200">
          <defs>
            <linearGradient id={"sgGrad" + badge} x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor={col.main} stopOpacity="0.4" />
              <stop offset="100%" stopColor={col.main} />
            </linearGradient>
            <filter id="sgGlow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="6" result="b" />
              <feComposite in="SourceGraphic" in2="b" operator="over" />
            </filter>
          </defs>
          {/* dark track */}
          <circle cx="100" cy="100" r={R} stroke="rgba(255,255,255,0.04)" strokeWidth="20" fill="none" />
          {/* precision ticks */}
          <g>{tickEls}</g>
          {/* active progress arc (rotated so it starts at top) */}
          <circle cx="100" cy="100" r={R} stroke={`url(#sgGrad${badge})`} strokeWidth="10"
            strokeDasharray={C} strokeDashoffset={offset} strokeLinecap="round" fill="none"
            filter="url(#sgGlow)" transform="rotate(-90 100 100)"
            style={{ transition: "stroke-dashoffset 1.1s cubic-bezier(.2,.7,.3,1)" }} />
        </svg>
        <div className="sg-center">
          <div className="sg-num-wrap">
            <span className="sg-num" style={{ color: col.main, textShadow: `0 0 36px rgba(${col.rgb},0.5)` }}>{disp}</span>
            {badge && <span className="sg-badge mono">{badge}</span>}
          </div>
          {showDots && (
            <div className="sg-dots">
              {Array.from({ length: dots }).map((_, i) => (
                <span key={i} className={"sg-dot" + (i < dotsActive ? " on" : "")}
                  style={i < dotsActive ? { background: col.main, boxShadow: `0 0 8px ${col.main}` } : null} />
              ))}
            </div>
          )}
        </div>
      </div>
      {showLabel && !compact && (
        <div className="sg-label">
          <Icon name="target" size={13} color="var(--sv-cyan)" className="sg-radar" />
          <p className="mono">{label}</p>
        </div>
      )}
      {showLabel && !compact && sublabel && <div className="sg-sub mono">{sublabel}</div>}
    </div>
  );
}

Object.assign(window, { ResilienceGauge, gaugeColor });
