<script lang="ts">
  // Floating focus-timer overlay. Renders nothing when no timer is
  // active. When a timer is running, pins a compact SVG progress ring
  // to the top-right of the viewport with the remaining mm:ss in the
  // centre. Completion plays a gentle chime, flashes a success ring
  // for 3 s, then disappears. Cancel button appears on hover.
  //
  // Mounted once in +layout.svelte. Listens for `magnotia:start-timer`
  // events from anywhere in the app (e.g. MicroSteps) and delegates
  // to the focus-timer store.
  //
  // Design tokens used: --color-accent (mid-progress),
  // --color-warning (final 15%), --color-success (flourish),
  // --color-border (unfilled ring track). No literals, so the ring
  // follows the sensory-zone theme switcher in Settings.

  import { onMount, onDestroy } from "svelte";
  import { X, Plus, ExternalLink } from "lucide-svelte";
  import { focusTimer } from "$lib/stores/focusTimer.svelte.js";
  import { hasTauriRuntime } from "$lib/utils/runtime.js";

  // Hide the "pop out" button inside the float window itself — opening
  // a second float from a float would be silly and would re-mount the
  // same component. Detect via URL rather than a prop so we do not
  // have to thread context through every mount site.
  let isSecondaryWindow = $state(false);
  if (typeof window !== "undefined") {
    isSecondaryWindow = window.location.pathname.startsWith("/float")
      || window.location.pathname.startsWith("/viewer");
  }

  function handlePopOut() {
    // Mirror the button in TasksPage.svelte — opens the always-on-top
    // Now list + pinned timer in one floating window.
    if (!hasTauriRuntime()) return;
    window.open("/float", "_blank", "width=380,height=520");
  }

  const RING_SIZE = 64;
  const RING_STROKE = 5;
  const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;
  const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;

  // Progress ring fills as time elapses. Stroke-dashoffset goes from
  // circumference (empty) to 0 (full) — we want it the other way,
  // because the UX is a shrinking-time disc: more elapsed = less
  // ring visible. Render the remaining arc: dashoffset = circumference * progress.
  let dashOffset = $derived(RING_CIRCUMFERENCE * focusTimer.progress);

  function formatRemaining(ms: number): string {
    const total = Math.ceil(ms / 1000);
    const mins = Math.floor(total / 60);
    const secs = total % 60;
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  }

  // Colour shifts over the last 15% of the timer to cue "nearly done"
  // without resorting to red (which the brief flags as anxiogenic for
  // the target audience).
  let ringColor = $derived.by(() => {
    if (focusTimer.showingCompletionFlash) return "var(--color-success)";
    if (focusTimer.progress >= 0.85) return "var(--color-warning)";
    return "var(--color-accent)";
  });

  // Event handler: start a timer when any component fires `magnotia:start-timer`.
  // Payload shape from MicroSteps.svelte and task row buttons:
  //   { taskId?: string, seconds: number, label?: string }
  function handleStartEvent(evt: Event) {
    const detail = (evt as CustomEvent).detail ?? {};
    const seconds = Number(detail.seconds);
    if (!Number.isFinite(seconds) || seconds <= 0) return;
    focusTimer.start(seconds, {
      taskId: detail.taskId ?? null,
      label: detail.label ?? null,
    });
  }

  onMount(() => {
    window.addEventListener("magnotia:start-timer", handleStartEvent);
    // Rehydrate any in-flight timer that survived a window close.
    focusTimer.rehydrate();
  });

  onDestroy(() => {
    window.removeEventListener("magnotia:start-timer", handleStartEvent);
  });

  function handleCancel() {
    focusTimer.cancel();
  }

  function handleExtend() {
    focusTimer.extend(60);
  }

  function handleDismissFlash() {
    focusTimer.dismissCompletionFlash();
  }
</script>

{#if focusTimer.active || focusTimer.showingCompletionFlash}
  <div
    class="focus-timer"
    class:completed={focusTimer.showingCompletionFlash}
    role="status"
    aria-live="polite"
    aria-label={focusTimer.label ?? "Focus timer"}
  >
    <div class="ring-wrap">
      <svg
        width={RING_SIZE}
        height={RING_SIZE}
        viewBox={`0 0 ${RING_SIZE} ${RING_SIZE}`}
        aria-hidden="true"
      >
        <!-- Track -->
        <circle
          cx={RING_SIZE / 2}
          cy={RING_SIZE / 2}
          r={RING_RADIUS}
          fill="none"
          stroke="var(--color-border)"
          stroke-width={RING_STROKE}
        />
        <!-- Progress (shrinking slice — full ring at start, none at end) -->
        <circle
          cx={RING_SIZE / 2}
          cy={RING_SIZE / 2}
          r={RING_RADIUS}
          fill="none"
          stroke={ringColor}
          stroke-width={RING_STROKE}
          stroke-linecap="round"
          stroke-dasharray={RING_CIRCUMFERENCE}
          stroke-dashoffset={dashOffset}
          transform={`rotate(-90 ${RING_SIZE / 2} ${RING_SIZE / 2})`}
          style="transition: stroke-dashoffset 250ms linear, stroke 400ms ease"
        />
      </svg>
      <div class="time" aria-hidden={focusTimer.showingCompletionFlash}>
        {#if focusTimer.showingCompletionFlash}
          <span class="done">done</span>
        {:else}
          {formatRemaining(focusTimer.remainingMs)}
        {/if}
      </div>
    </div>

    <div class="controls">
      {#if focusTimer.showingCompletionFlash}
        <button
          class="icon-btn"
          onclick={handleDismissFlash}
          aria-label="Dismiss completion"
          title="Dismiss"
        >
          <X size={14} aria-hidden="true" />
        </button>
      {:else}
        <button
          class="icon-btn"
          onclick={handleExtend}
          aria-label="Add one minute"
          title="+1 min"
        >
          <Plus size={14} aria-hidden="true" />
        </button>
        {#if !isSecondaryWindow}
          <button
            class="icon-btn"
            onclick={handlePopOut}
            aria-label="Pop out timer + Now list into floating window"
            title="Pop out (keeps timer + tasks on top)"
          >
            <ExternalLink size={14} aria-hidden="true" />
          </button>
        {/if}
        <button
          class="icon-btn"
          onclick={handleCancel}
          aria-label="Cancel timer"
          title="Cancel"
        >
          <X size={14} aria-hidden="true" />
        </button>
      {/if}
    </div>

    {#if focusTimer.label}
      <div class="label" aria-hidden="true">{focusTimer.label}</div>
    {/if}
  </div>
{/if}

<style>
  .focus-timer {
    position: fixed;
    top: 52px;
    right: 16px;
    z-index: 40;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 10px 6px 6px;
    background: var(--color-bg-elevated);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
    font-family: var(--font-family-body);
    font-variant-numeric: tabular-nums;
    transition: opacity 200ms ease, transform 200ms ease;
  }

  .focus-timer.completed {
    border-color: var(--color-success);
  }

  .ring-wrap {
    position: relative;
    width: 64px;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .time {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text);
  }

  .time .done {
    font-size: 11px;
    color: var(--color-success);
    font-family: var(--font-family-display);
    letter-spacing: 0.02em;
  }

  .controls {
    display: flex;
    flex-direction: column;
    gap: 4px;
    opacity: 0;
    transition: opacity 180ms ease;
  }

  .focus-timer:hover .controls,
  .focus-timer:focus-within .controls,
  .focus-timer.completed .controls {
    opacity: 1;
  }

  .icon-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 22px;
    height: 22px;
    padding: 0;
    border: 0;
    border-radius: var(--radius-sm);
    background: transparent;
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: background 150ms ease, color 150ms ease;
  }

  .icon-btn:hover {
    background: var(--color-hover);
    color: var(--color-text);
  }

  .icon-btn:focus-visible {
    outline: 2px solid var(--color-accent);
    outline-offset: 1px;
  }

  .label {
    max-width: 140px;
    font-size: 12px;
    color: var(--color-text-secondary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :global([data-reduce-motion="true"]) .focus-timer circle {
    transition: none !important;
  }
</style>
