window.MicRating = function MicRating({ initial = 0, imageId, userCallsign, onRate, displayOnly = false }) {
  const [rating, setRating] = React.useState(initial);
  const [clickedIndex, setClickedIndex] = React.useState(null);

const labels = [
  "No Signal",
  "Very Weak",
  "Weak but Audible",
  "Clear Enough",
  "Strong Signal",
  "Excellent — 5 by 9!"
];

  const handleRate = (value) => {
    if (displayOnly) return;

    setClickedIndex(value);

    fetch('/gallery/rate-image.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        image_id: imageId,
        rating: value,
        user_callsign: userCallsign
      })
    }).then(res => res.json())
      .then(data => {
        if (data.success) {
          Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Thanks for your rating!',
            showConfirmButton: false,
            timer: 1500
          });

          setTimeout(() => {
            setClickedIndex(null);
            setRating(value);
            if (onRate) onRate(value);
          }, 500);
        } else {
          Swal.fire('Error', data.message || 'Failed to rate image.', 'error');
          setClickedIndex(null);
        }
      });
  };

  return (
    <div style={{ textAlign: "right" }}>
      <div style={{
        display: "flex",
        justifyContent: "flex-end",
        gap: "4px",
        fontSize: "1rem",
        cursor: displayOnly ? "default" : "pointer",
        alignItems: "flex-start"
      }}>
        {[1, 2, 3, 4, 5].map(i => (
          <div
            key={i}
            style={{ position: "relative", marginTop: "8px" }}
            onClick={(e) => {
              if (displayOnly) return;
              e.stopPropagation();
              handleRate(i);
            }}
            onMouseEnter={(e) => {
              if (displayOnly) return;
              const tooltip = e.currentTarget.querySelector(".tooltip");
              if (tooltip) tooltip.style.opacity = "1";
            }}
            onMouseLeave={(e) => {
              if (displayOnly) return;
              const tooltip = e.currentTarget.querySelector(".tooltip");
              if (tooltip) tooltip.style.opacity = "0";
            }}
          >
            {/* Base mic icon (gray) */}
            <i
              className={`fa-solid fa-microphone inline-block transition-transform ${i === clickedIndex ? 'bounce-smooth' : ''}`}
              style={{
                position: 'relative',
                fontSize: '1.2rem',
                color: '#4b5563' // gray base
              }}
            >
              {/* Overlay mic for fill */}
              <i
                className="fa-solid fa-microphone"
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  overflow: 'hidden',
                  color: clickedIndex === i
                    ? '#facc15'
                    : i <= Math.floor(rating)
                    ? '#48a5ec'
                    : i === Math.ceil(rating) && rating % 1 !== 0
                    ? '#48a5ec'
                    : 'transparent',
                  clipPath:
                    i === Math.ceil(rating) && rating % 1 !== 0
                      ? `inset(0 ${100 - (rating % 1) * 100}% 0 0)`
                      : 'none',
                  pointerEvents: 'none'
                }}
              ></i>
            </i>

            {/* Tooltip */}
            {!displayOnly && (
              <div
                className="tooltip"
                style={{
                  position: 'absolute',
                  bottom: '100%',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  background: 'rgb(177, 28, 28)',
                  color: '#fff',
                  fontSize: '12px',
                  borderRadius: '4px',
                  padding: '2px 6px',
                  whiteSpace: 'nowrap',
                  opacity: 0,
                  transition: 'opacity 0.2s',
                  zIndex: 10,
                  marginBottom: '4px'
                }}
              >
                {labels[i - 1]}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};
