/* global React */
const { useEffect: useME, useState: useMS } = React;

// macOS variant of the Dimmy pill · same visual design as the Windows pill,
// rendered with system fonts and a backdrop tuned for the macOS desktop.
function MacPill({ state = "idle", border = "rainbow", waveform = "bars", llmDot = "#0a84ff", shortcut = "⌃⌥", timer = null, scale = 1 }) {
  const [tick, setTick] = useMS(0);
  useME(() => {
    let raf, run = true;
    const loop = () => { if (!run) return; setTick(t => t + 1); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => { run = false; cancelAnimationFrame(raf); };
  }, []);

  const isRec = state === "recording";
  const isTrans = state === "transcribing" || state === "processing";
  const isDone = state === "done";
  const isErr = state === "error";

  const recColor =
    border === "blue" ? "#0a84ff" :
    border === "green" ? "#30d158" :
    border === "purple" ? "#bf5af2" :
    border === "orange" ? "#ff9f0a" :
    border === "rainbow" ? "#bf5af2" : "#0a84ff";

  // Bars (centered)
  const barCount = 18;
  const bars = Array.from({ length: barCount }, (_, i) => {
    if (!isRec && !isTrans) return 2;
    const phase = (tick / 6) + i * 0.6;
    const center = (barCount - 1) / 2;
    const distFromCenter = Math.abs(i - center) / center;
    const amplitudeBase = isTrans ? 0.5 : 1;
    const wave = (Math.sin(phase) * 0.4 + Math.sin(phase * 2.3 + i) * 0.3 + 0.6) * (1 - distFromCenter * 0.4) * amplitudeBase;
    return Math.max(2, Math.round(2 + wave * 14));
  });

  return (
    <div style={{
      transform: `scale(${scale})`,
      transformOrigin: "center",
      position: "relative",
      display: "inline-block",
    }}>
      <div style={{
        position: "relative",
        height: 44,
        minWidth: 200,
        padding: "0 14px",
        borderRadius: 9999,
        background: "rgba(20, 20, 22, 0.78)",
        backdropFilter: "blur(40px) saturate(180%)",
        WebkitBackdropFilter: "blur(40px) saturate(180%)",
        border: "0.5px solid rgba(255,255,255,0.12)",
        display: "inline-flex",
        alignItems: "center",
        gap: 10,
        boxShadow: isRec ? `0 8px 28px rgba(0,0,0,0.5), 0 0 24px ${recColor}55` : "0 8px 28px rgba(0,0,0,0.4)",
        color: "rgba(255,255,255,0.9)",
        fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif',
        fontSize: 12,
      }}>
        {/* Rainbow rotating border */}
        {isRec && border === "rainbow" && (
          <span style={{
            position: "absolute", inset: -1, borderRadius: 9999, padding: 1.5,
            background: "conic-gradient(from var(--dimmy-angle, 0deg), #ff453a, #ff9f0a, #ffd60a, #30d158, #5ac8fa, #0a84ff, #bf5af2, #ff375f, #ff453a)",
            WebkitMask: "linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)",
            WebkitMaskComposite: "xor", maskComposite: "exclude",
            animation: "dimmy-rotate 3s linear infinite", pointerEvents: "none",
          }}/>
        )}
        {isRec && border !== "rainbow" && border !== "none" && (
          <span style={{
            position: "absolute", inset: -1, borderRadius: 9999,
            border: `1.5px solid ${recColor}`, pointerEvents: "none",
            animation: "mac-pulse 1.6s ease-in-out infinite",
          }}/>
        )}

        {/* Mic glyph / state glyph */}
        <span style={{
          width: 22, height: 22, borderRadius: 99,
          background: isRec ? recColor : isErr ? "#ff453a" : "rgba(255,255,255,0.12)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}>
          <svg width="11" height="13" viewBox="0 0 11 13" fill="none" style={{ color: "#fff" }}>
            <rect x="3" y="0" width="5" height="8" rx="2.5" fill="currentColor"/>
            <path d="M1 6.5C1 9 2.8 11 5.5 11M5.5 11C8.2 11 10 9 10 6.5M5.5 11V13" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
          </svg>
        </span>

        {/* Waveform */}
        {(isRec || isTrans) && waveform === "bars" && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 2, height: 18, flexShrink: 0 }}>
            {bars.map((h, i) => (
              <span key={i} style={{
                width: 2, height: h, borderRadius: 1,
                background: isTrans ? "rgba(255,255,255,0.5)" : recColor,
                transition: "height 60ms linear",
              }}/>
            ))}
          </span>
        )}
        {(isRec || isTrans) && waveform === "dots" && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
            {[0, 1, 2, 3, 4].map(i => (
              <span key={i} style={{
                width: 4, height: 4, borderRadius: 99,
                background: recColor,
                opacity: 0.4 + 0.6 * Math.abs(Math.sin(tick / 8 + i)),
              }}/>
            ))}
          </span>
        )}
        {(isRec || isTrans) && waveform === "line" && (
          <svg width="80" height="14" viewBox="0 0 80 14">
            <path d={`M 0 7 ${bars.map((h, i) => `L ${i * 4.5} ${7 - (h - 2) / 2}`).join(" ")}`}
                  stroke={recColor} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
          </svg>
        )}

        {/* Status text */}
        <span style={{ flex: 1, color: "rgba(255,255,255,0.85)", whiteSpace: "nowrap" }}>
          {state === "idle" && <span style={{ color: "rgba(255,255,255,0.55)" }}>Hold {shortcut} to speak</span>}
          {state === "recording" && (timer || "Recording")}
          {state === "transcribing" && "Transcribing…"}
          {state === "processing" && "Polishing…"}
          {state === "done" && "Done"}
          {state === "error" && "Microphone error"}
        </span>

        {/* LLM indicator dot */}
        {(isRec || isTrans || isDone) && (
          <span style={{
            width: 8, height: 8, borderRadius: 99,
            background: llmDot, boxShadow: `0 0 6px ${llmDot}88`,
            flexShrink: 0,
          }}/>
        )}
      </div>

      <style>{`
        @keyframes mac-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.55; } }
      `}</style>
    </div>
  );
}

window.MacPill = MacPill;
