import { Show, type Component } from "solid-js"
import { Icon } from "@opencode-ai/ui/v2/icon"
import { useLanguage } from "@/context/language"
import { useVoice } from "./voice-context"

export const VoiceOverlay: Component = () => {
  const voice = useVoice()
  const language = useLanguage()

  const seconds = () => Math.floor(voice.durationMs() / 1000)
  const clock = () => {
    const total = seconds()
    const m = Math.floor(total / 60)
      .toString()
      .padStart(2, "0")
    const s = (total % 60).toString().padStart(2, "0")
    return `${m}:${s}`
  }

  return (
    <Show when={voice.available() && (voice.recording() || voice.processing() || voice.error())}>
      <div
        class="pointer-events-none fixed inset-x-0 bottom-24 z-50 flex justify-center px-4"
        data-component="voice-overlay"
      >
        <div class="pointer-events-auto flex max-w-xl flex-col gap-2 rounded-xl border border-border-weak-base bg-background-stronger px-4 py-3 shadow-lg">
          <div class="flex items-center gap-3">
            <div
              class="flex size-8 items-center justify-center rounded-full"
              style={{
                "background-color": voice.recording() ? "color-mix(in srgb, #ef4444 20%, transparent)" : undefined,
                animation: voice.recording() ? "voice-pulse 1.2s ease-in-out infinite" : undefined,
              }}
            >
              <Icon name="microphone" style={{ color: voice.recording() ? "#ef4444" : undefined }} />
            </div>
            <div class="min-w-0 flex-1">
              <div class="text-14-medium text-text-strong">
                <Show when={voice.recording()} fallback={language.t("voice.status.processing")}>
                  {language.t("voice.status.recording")} · {clock()}
                </Show>
              </div>
              <div class="truncate text-12-regular text-text-weak">
                <Show
                  when={voice.error()}
                  fallback={voice.interim() || voice.finalText() || language.t("voice.status.listening")}
                >
                  {(error) => error().message}
                </Show>
              </div>
            </div>
            <Show when={voice.recording()}>
              <button
                type="button"
                class="pointer-events-auto rounded-md px-2 py-1 text-12-medium text-text-weak hover:bg-surface-base"
                onClick={() => void voice.stop()}
              >
                {language.t("voice.action.stop")}
              </button>
            </Show>
          </div>
        </div>
      </div>
      <style>{`
        @keyframes voice-pulse {
          0%, 100% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.08); opacity: 0.85; }
        }
      `}</style>
    </Show>
  )
}
