/* Generated by scripts/build.mjs. Do not edit client.js by hand. */
window.__ModuleLoader__.load({
  id: '@local/dsh-pomodoro',
  factory(require) {
    const React = require('react');
    const h = React.createElement;

    /**
 * Pure timer state machine for the pomodoro plugin.
 *
 * A running round stores only its absolute `endAt`; the remaining time is
 * derived from the wall clock, so tab throttling, sleep, or a page refresh
 * cannot accumulate drift. Paused/idle rounds store an exact `remainingMs`.
 */

const STATE_VERSION = 1;

const MODE_ORDER = Object.freeze(['focus', 'shortBreak', 'test']);

const MODES = Object.freeze({
  focus: Object.freeze({ durationMs: 25 * 60 * 1000 }),
  shortBreak: Object.freeze({ durationMs: 5 * 60 * 1000 }),
  test: Object.freeze({ durationMs: 60 * 1000 }),
});

const STATUSES = new Set(['idle', 'running', 'paused', 'complete']);

function normalizeMode(mode) {
  return Object.prototype.hasOwnProperty.call(MODES, mode) ? mode : 'focus';
}

function clamp(value, min, max) {
  return Math.min(max, Math.max(min, value));
}

function finiteNumber(value) {
  return typeof value === 'number' && Number.isFinite(value);
}

/** Return the fixed duration of a mode, falling back to focus. */
function durationOf(mode) {
  return MODES[normalizeMode(mode)].durationMs;
}

/** Build a fresh idle round in focus mode. */
function createInitialState() {
  return {
    version: STATE_VERSION,
    mode: 'focus',
    durationMs: durationOf('focus'),
    status: 'idle',
    remainingMs: durationOf('focus'),
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
    completionCount: 0,
  };
}

/**
 * Parse a persisted snapshot and repair anything that cannot be trusted.
 * A running round that expired while the page was closed completes here.
 */
function hydrate(raw, now = Date.now()) {
  let value = raw;
  if (typeof raw === 'string') {
    try {
      value = JSON.parse(raw);
    } catch {
      return createInitialState();
    }
  }
  if (value === null || typeof value !== 'object' || value.version !== STATE_VERSION) {
    return createInitialState();
  }

  const mode = normalizeMode(value.mode);
  const durationMs = durationOf(mode);
  const status = STATUSES.has(value.status) ? value.status : 'idle';
  const completionCount = Number.isInteger(value.completionCount) && value.completionCount >= 0
    ? value.completionCount
    : 0;
  const noticeDismissed = value.noticeDismissed === true;
  const base = {
    version: STATE_VERSION,
    mode,
    durationMs,
    status: 'idle',
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed,
    completionCount,
  };

  if (status === 'running' && finiteNumber(value.endAt) && value.endAt > 0) {
    return sync({ ...base, status: 'running', endAt: value.endAt }, now);
  }
  if (status === 'paused') {
    const remainingMs = clamp(
      finiteNumber(value.remainingMs) ? value.remainingMs : durationMs,
      0,
      durationMs,
    );
    if (remainingMs <= 0) {
      return {
        ...base,
        status: 'complete',
        remainingMs: 0,
        completedAt: finiteNumber(value.completedAt) ? value.completedAt : now,
        noticeDismissed,
        completionCount,
      };
    }
    return { ...base, status: 'paused', remainingMs };
  }
  if (status === 'complete') {
    return {
      ...base,
      status: 'complete',
      remainingMs: 0,
      completedAt: finiteNumber(value.completedAt) ? value.completedAt : now,
    };
  }
  return base;
}

/** Remaining wall-clock time for a snapshot. */
function remainingMs(state, now = Date.now()) {
  if (state.status === 'complete') return 0;
  if (state.status === 'running' && finiteNumber(state.endAt)) {
    return Math.max(0, state.endAt - now);
  }
  return clamp(state.remainingMs, 0, state.durationMs);
}

/**
 * Advance a running round. Completion happens exactly once: later calls on a
 * completed state return the same reference and do not add another notice.
 */
function sync(state, now = Date.now()) {
  if (state.status !== 'running' || !finiteNumber(state.endAt)) return state;
  if (state.endAt > now) return state;
  return {
    ...state,
    status: 'complete',
    remainingMs: 0,
    endAt: null,
    completedAt: now,
    noticeDismissed: false,
    completionCount: state.completionCount + 1,
  };
}

/** Start a new round from idle or completed; paused rounds use resume(). */
function start(state, now = Date.now()) {
  if (state.status !== 'idle' && state.status !== 'complete') return state;
  const durationMs = durationOf(state.mode);
  return {
    ...state,
    status: 'running',
    durationMs,
    remainingMs: durationMs,
    endAt: now + durationMs,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Freeze a running round at its wall-clock remaining time. */
function pause(state, now = Date.now()) {
  if (state.status !== 'running' || !finiteNumber(state.endAt)) return state;
  const left = state.endAt - now;
  if (left <= 0) return sync(state, now);
  return {
    ...state,
    status: 'paused',
    remainingMs: left,
    endAt: null,
  };
}

/** Continue a paused round from exactly the frozen remaining time. */
function resume(state, now = Date.now()) {
  if (state.status !== 'paused') return state;
  const left = clamp(state.remainingMs, 0, state.durationMs);
  if (left <= 0) return state;
  return {
    ...state,
    status: 'running',
    remainingMs: left,
    endAt: now + left,
  };
}

/** Reset the current mode to a fresh idle round. */
function reset(state) {
  const durationMs = durationOf(state.mode);
  return {
    ...state,
    status: 'idle',
    durationMs,
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Switch mode and reset the countdown; the completion counter is retained. */
function setMode(state, mode) {
  const nextMode = normalizeMode(mode);
  if (nextMode === state.mode && state.status === 'idle') return state;
  const durationMs = durationOf(nextMode);
  return {
    ...state,
    mode: nextMode,
    status: 'idle',
    durationMs,
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Mark the one completion notice as seen. */
function dismissNotice(state) {
  if (state.status !== 'complete' || state.noticeDismissed) return state;
  return { ...state, noticeDismissed: true };
}

/** Format milliseconds as MM:SS, rounding up so a fresh 60s round says 01:00. */
function formatClock(ms) {
  const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
  const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
  const seconds = (totalSeconds % 60).toString().padStart(2, '0');
  return `${minutes}:${seconds}`;
}

/** Fraction of the current round that has elapsed, from 0 to 1. */
function progressOf(state, now = Date.now()) {
  if (state.durationMs <= 0) return 0;
  return clamp(1 - remainingMs(state, now) / state.durationMs, 0, 1);
}

    const NS = 'dshPomodoro';
const STORAGE_KEY = 'dsh.pomodoro.state.v1';
const PANEL_KEY = 'dsh.pomodoro.panel.v1';

const en = {
  'title': 'Pomodoro',
  'openAria': 'Open pomodoro timer',
  'hide': 'Hide timer',
  'modesAria': 'Timer mode',
  'progress': 'Round progress',
  'status.idle': 'Ready',
  'status.running': 'Running',
  'status.paused': 'Paused',
  'status.complete': 'Complete',
  'mode.focus': 'Focus 25m',
  'mode.shortBreak': 'Break 5m',
  'mode.test': 'Test 60s',
  'caption.focus': '25-minute focus round',
  'caption.shortBreak': '5-minute break',
  'caption.test': '60-second acceptance test',
  'start': 'Start',
  'pause': 'Pause',
  'resume': 'Continue',
  'reset': 'Reset',
  'resetHint': 'Stop this round and return to the start',
  'modeResetHint': 'Switching mode stops the current round',
  'notice.focus': 'Focus complete. Take a 5-minute break or start the next round.',
  'notice.shortBreak': 'Break complete. Ready for the next focus round.',
  'notice.test': '60-second test complete.',
  'dismiss': 'Got it',
  'hint': 'Absolute-deadline timing · hiding or refreshing keeps this round',
  'badgeDone': 'Done',
};

const zh = {
  'title': '番茄钟',
  'openAria': '打开番茄钟',
  'hide': '隐藏番茄钟',
  'modesAria': '计时档位',
  'progress': '本轮进度',
  'status.idle': '准备开始',
  'status.running': '进行中',
  'status.paused': '已暂停',
  'status.complete': '已完成',
  'mode.focus': '专注 25分',
  'mode.shortBreak': '休息 5分',
  'mode.test': '测试 60秒',
  'caption.focus': '25 分钟专注',
  'caption.shortBreak': '5 分钟休息',
  'caption.test': '60 秒验收测试',
  'start': '开始',
  'pause': '暂停',
  'resume': '继续',
  'reset': '重置',
  'resetHint': '停止本轮并回到起点',
  'modeResetHint': '切换档位会停止当前计时',
  'notice.focus': '专注完成。休息 5 分钟，或开始下一轮。',
  'notice.shortBreak': '休息结束。准备开始下一轮专注。',
  'notice.test': '60 秒测试已结束。',
  'dismiss': '知道了',
  'hint': '按绝对截止时间计时 · 隐藏或刷新不会丢失本轮',
  'badgeDone': '完成',
};

const CSS = `
.dsh-pomodoro-layer {
  position: relative;
  flex: 1 1 100%;
  min-width: 0;
  display: flex;
  align-items: center;
  width: 100%;
  height: 42px;
  margin: 8px 0 0;
}
.dsh-pomodoro-footer { display: flex; align-items: center; width: 100%; }
.dsh-pomodoro-badge {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  width: calc(100% + 4px);
  height: 42px;
  margin: 0 -2px;
  padding: 0 10px 0 8px;
  border: 0;
  border-radius: 12px;
  background: transparent;
  color: var(--dsw-alias-label-primary);
  font: inherit;
  font-size: 14px;
  cursor: pointer;
  overflow: hidden;
}
.dsh-pomodoro-badge:hover { background: var(--dsw-alias-bg-layer-2); }
.dsh-pomodoro-badge[data-open="true"] { background: var(--dsw-alias-bg-layer-2); }
.dsh-pomodoro-label {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dsh-pomodoro-clock {
  flex: none;
  margin-left: auto;
  color: var(--dsw-alias-label-secondary);
  font-size: 12px;
  line-height: 16px;
  font-variant-numeric: tabular-nums;
}
.dsh-pomodoro-badge[data-status="running"] .dsh-pomodoro-clock { color: var(--dsw-alias-brand-primary); }
.dsh-pomodoro-badge[data-status="paused"] .dsh-pomodoro-clock { color: var(--dsw-alias-state-warn-primary); }
.dsh-pomodoro-badge[data-status="complete"] .dsh-pomodoro-clock { color: var(--dsw-alias-state-success-primary); }
.dsh-pomodoro-dot {
  display: none;
  position: absolute;
  top: 5px;
  right: 5px;
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--dsw-alias-brand-primary);
  box-shadow: 0 0 0 2px var(--dsw-alias-bg-layer-1);
}
.dsh-pomodoro-dot[data-status="paused"] { background: var(--dsw-alias-state-warn-primary); }
.dsh-pomodoro-dot[data-status="complete"] { background: var(--dsw-alias-state-success-primary); }

.dsh-pomodoro-layer.dsh-pomodoro-rail { width: 36px; height: 36px; margin: 0; }
.dsh-pomodoro-rail .dsh-pomodoro-badge {
  justify-content: center;
  gap: 0;
  width: 36px;
  height: 36px;
  margin: 0;
  padding: 0;
  border-radius: 50%;
}
.dsh-pomodoro-rail .dsh-pomodoro-label,
.dsh-pomodoro-rail .dsh-pomodoro-clock { display: none; }
.dsh-pomodoro-rail .dsh-pomodoro-dot { display: block; }
.dsh-pomodoro-rail .dsh-pomodoro-dot[data-status="idle"] { display: none; }

.dsh-pomodoro-panel {
  position: fixed;
  z-index: 40;
  width: 344px;
  max-width: calc(100vw - 24px);
  max-height: min(560px, calc(100vh - 24px));
  overflow: auto;
  box-sizing: border-box;
  padding: 16px;
  border: 1px solid var(--dsw-alias-border-l1);
  border-radius: 16px;
  background: var(--dsw-alias-bg-overlay);
  color: var(--dsw-alias-label-primary);
  box-shadow: 0 16px 40px color-mix(in srgb, var(--dsw-alias-label-primary) 18%, transparent);
}
.dsh-pomodoro-panel:focus { outline: none; }
.dsh-pomodoro-panel:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
.dsh-pomodoro-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}
.dsh-pomodoro-title-group { display: flex; align-items: center; gap: 8px; min-width: 0; }
.dsh-pomodoro-title { font-size: 14px; font-weight: 600; line-height: 20px; }
.dsh-pomodoro-status {
  flex: none;
  padding: 0 8px;
  border-radius: 999px;
  background: var(--dsw-alias-bg-layer-2);
  color: var(--dsw-alias-label-secondary);
  font-size: 11px;
  line-height: 18px;
  white-space: nowrap;
}
.dsh-pomodoro-status[data-status="running"] { color: var(--dsw-alias-brand-primary); }
.dsh-pomodoro-status[data-status="complete"] { color: var(--dsw-alias-state-success-primary); }
.dsh-pomodoro-icon-button {
  flex: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  padding: 0;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: var(--dsw-alias-label-secondary);
  cursor: pointer;
}
.dsh-pomodoro-icon-button:hover {
  background: var(--dsw-alias-bg-layer-2);
  color: var(--dsw-alias-label-primary);
}
.dsh-pomodoro-modes {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 4px;
  margin: 14px 0 10px;
  padding: 3px;
  border-radius: 10px;
  background: var(--dsw-alias-bg-layer-2);
}
.dsh-pomodoro-mode {
  min-width: 0;
  height: 30px;
  padding: 0 4px;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: var(--dsw-alias-label-secondary);
  font: inherit;
  font-size: 12px;
  line-height: 18px;
  white-space: nowrap;
  cursor: pointer;
}
.dsh-pomodoro-mode:hover { color: var(--dsw-alias-label-primary); }
.dsh-pomodoro-mode[data-active="true"] {
  background: var(--dsw-alias-bg-overlay);
  box-shadow: inset 0 0 0 1px var(--dsw-alias-border-l1);
  color: var(--dsw-alias-label-primary);
}
.dsh-pomodoro-time {
  margin: 4px 0 2px;
  text-align: center;
  font-size: 56px;
  font-weight: 600;
  line-height: 1.05;
  letter-spacing: -0.03em;
  font-variant-numeric: tabular-nums;
}
.dsh-pomodoro-progress {
  height: 6px;
  margin: 8px 0 10px;
  border-radius: 999px;
  background: var(--dsw-alias-bg-layer-2);
  overflow: hidden;
}
.dsh-pomodoro-progress > span {
  display: block;
  height: 100%;
  border-radius: inherit;
  background: var(--dsw-alias-brand-primary);
  transition: width 200ms linear;
}
.dsh-pomodoro-panel[data-status="complete"] .dsh-pomodoro-progress > span {
  background: var(--dsw-alias-state-success-primary);
}
.dsh-pomodoro-caption {
  min-height: 18px;
  margin: 0 0 12px;
  text-align: center;
  color: var(--dsw-alias-label-secondary);
  font-size: 12px;
  line-height: 18px;
}
.dsh-pomodoro-notice {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 8px;
  margin: 0 0 12px;
  padding: 10px 12px;
  border: 1px solid color-mix(in srgb, var(--dsw-alias-state-success-primary) 48%, var(--dsw-alias-border-l1));
  border-radius: 10px;
  background: color-mix(in srgb, var(--dsw-alias-state-success-primary) 12%, var(--dsw-alias-bg-overlay));
}
.dsh-pomodoro-notice-text { font-size: 12px; line-height: 18px; }
.dsh-pomodoro-notice-action {
  flex: none;
  padding: 1px 0;
  border: 0;
  background: transparent;
  color: var(--dsw-alias-state-success-primary);
  font: inherit;
  font-size: 12px;
  line-height: 18px;
  cursor: pointer;
}
.dsh-pomodoro-notice-action:hover { text-decoration: underline; }
.dsh-pomodoro-controls {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 6px;
}
.dsh-pomodoro-control {
  height: 34px;
  min-width: 0;
  padding: 0 4px;
  border: 1px solid var(--dsw-alias-border-l1);
  border-radius: 9px;
  background: transparent;
  color: var(--dsw-alias-label-primary);
  font: inherit;
  font-size: 12px;
  cursor: pointer;
}
.dsh-pomodoro-control:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-2); }
.dsh-pomodoro-control:disabled { opacity: 0.4; cursor: default; }
.dsh-pomodoro-control[data-primary="true"] {
  border-color: var(--dsw-alias-brand-primary);
  background: var(--dsw-alias-brand-primary);
  color: var(--dsw-alias-bg-base);
}
.dsh-pomodoro-control[data-primary="true"]:hover:not(:disabled) {
  background: var(--dsw-alias-brand-primary);
  opacity: 0.9;
}
.dsh-pomodoro-hint {
  margin: 10px 0 0;
  text-align: center;
  color: var(--dsw-alias-label-secondary);
  font-size: 11px;
  line-height: 16px;
}
.dsh-pomodoro-layer button:focus-visible {
  outline: 2px solid var(--dsw-alias-brand-primary);
  outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
  .dsh-pomodoro-progress > span { transition: none; }
}
`;

function readStorage(key) {
  try {
    return window.localStorage.getItem(key);
  } catch {
    return null;
  }
}

function writeStorage(key, value) {
  try {
    window.localStorage.setItem(key, value);
  } catch {
    // Storage can be unavailable in hardened contexts; the in-memory round
    // still works for the lifetime of the page.
  }
}

const startRound = start;
const pauseRound = pause;
const resumeRound = resume;
const resetRound = reset;
const changeMode = setMode;
const syncRound = sync;

const store = (() => {
  let state = hydrate(readStorage(STORAGE_KEY), Date.now());
  const listeners = new Set();
  let ticker = null;
  let lastSecond = Math.ceil(remainingMs(state, Date.now()) / 1000);

  const getSnapshot = () => {
    const now = Date.now();
    const left = remainingMs(state, now);
    return {
      state,
      now,
      remaining: left,
      clock: formatClock(left),
      progress: progressOf(state, now),
    };
  };

  const persist = () => writeStorage(STORAGE_KEY, JSON.stringify(state));
  const publish = () => {
    const snapshot = getSnapshot();
    for (const listener of [...listeners]) listener(snapshot);
  };

  const commit = (next) => {
    if (next === state) return;
    state = next;
    lastSecond = Math.ceil(remainingMs(state, Date.now()) / 1000);
    persist();
    publish();
  };

  const tick = () => {
    const now = Date.now();
    const next = syncRound(state, now);
    const second = Math.ceil(remainingMs(next, now) / 1000);
    if (next === state && second === lastSecond) return;
    const changed = next !== state;
    state = next;
    lastSecond = second;
    if (changed) persist();
    publish();
  };

  const startTicker = () => {
    if (ticker !== null) return;
    lastSecond = Math.ceil(remainingMs(state, Date.now()) / 1000);
    ticker = window.setInterval(tick, 200);
  };

  const stop = () => {
    if (ticker === null) return;
    window.clearInterval(ticker);
    ticker = null;
  };

  const subscribe = (listener) => {
    listeners.add(listener);
    if (listeners.size === 1) startTicker();
    listener(getSnapshot());
    return () => {
      listeners.delete(listener);
      if (listeners.size === 0) stop();
    };
  };

  return {
    getSnapshot,
    subscribe,
    stop,
    start: () => commit(startRound(state, Date.now())),
    pause: () => commit(pauseRound(state, Date.now())),
    resume: () => commit(resumeRound(state, Date.now())),
    reset: () => commit(resetRound(state)),
    selectMode: mode => commit(changeMode(state, mode)),
    dismiss: () => commit(dismissNotice(state)),
  };
})();

function usePomodoro() {
  const [snapshot, setSnapshot] = React.useState(() => store.getSnapshot());
  React.useEffect(() => store.subscribe(setSnapshot), []);
  return snapshot;
}

function TomatoIcon({ size = 18 }) {
  return h('svg', {
    viewBox: '0 0 36 36',
    width: size,
    height: size,
    'aria-hidden': true,
    focusable: 'false',
    style: { display: 'block', flex: 'none' },
  },
  h('path', { d: 'M18 8.2c-1.7-3.2-4.5-4.3-6.8-3.9 1.3 2.3 3.2 3.5 5.5 3.8-2.8.5-4.9 1.8-6.2 3.5 3.1.5 5.5-.6 7.5-3.4Z', fill: '#2F8F5B' }),
  h('path', { d: 'M18 8.2c1.7-3.2 4.5-4.3 6.8-3.9-1.3 2.3-3.2 3.5-5.5 3.8 2.8.5 4.9 1.8 6.2 3.5-3.1.5-5.5-.6-7.5-3.4Z', fill: '#3AA66A' }),
  h('circle', { cx: 18, cy: 20.5, r: 9.5, fill: '#D94C38' }),
  h('path', { d: 'M18 11c5.2 0 9.5 4.3 9.5 9.5S23.2 30 18 30s-9.5-4.3-9.5-9.5S12.8 11 18 11Z', fill: '#E75A43' }),
  h('circle', { cx: 18, cy: 20.5, r: 6.3, fill: '#FFF5E9' }),
  h('path', { d: 'M18 16.6v4.2l2.9 1.8', stroke: '#8E2F24', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round', fill: 'none' }),
  h('circle', { cx: 18, cy: 20.5, r: 1.25, fill: '#8E2F24' }));
}

function CloseIcon() {
  return h('svg', {
    viewBox: '0 0 16 16',
    width: 14,
    height: 14,
    'aria-hidden': true,
    focusable: 'false',
  },
  h('path', {
    d: 'M3.5 3.5l9 9M12.5 3.5l-9 9',
    stroke: 'currentColor',
    strokeWidth: 1.5,
    strokeLinecap: 'round',
  }));
}

function readPanelOpen() {
  const saved = readStorage(PANEL_KEY);
  return saved === null ? true : saved === '1';
}

function PomodoroAction({ wide, t }) {
  const snapshot = usePomodoro();
  const { state, clock, progress } = snapshot;
  const tr = typeof t === 'function' ? t : key => en[key] ?? key;
  const [open, setOpen] = React.useState(readPanelOpen);
  const [anchor, setAnchor] = React.useState(null);
  const rootRef = React.useRef(null);
  const triggerRef = React.useRef(null);
  const panelRef = React.useRef(null);

  const hide = (focusTrigger) => {
    setOpen(false);
    writeStorage(PANEL_KEY, '0');
    if (focusTrigger) triggerRef.current?.focus();
  };

  const toggle = () => {
    if (open) {
      hide(true);
      return;
    }
    setOpen(true);
    writeStorage(PANEL_KEY, '1');
  };

  React.useLayoutEffect(() => {
    if (!open) {
      setAnchor(null);
      return;
    }
    const place = () => {
      const rect = rootRef.current?.getBoundingClientRect();
      if (!rect) return;
      const width = Math.min(344, window.innerWidth - 24);
      const left = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12));
      const bottom = Math.max(12, window.innerHeight - rect.top + 8);
      setAnchor(previous => (
        previous && previous.left === left && previous.bottom === bottom
          ? previous
          : { left, bottom }
      ));
    };
    place();
    window.addEventListener('resize', place);
    const observer = typeof ResizeObserver === 'function' && rootRef.current
      ? new ResizeObserver(place)
      : null;
    observer?.observe(rootRef.current);
    return () => {
      window.removeEventListener('resize', place);
      observer?.disconnect();
    };
  }, [open, wide]);

  React.useLayoutEffect(() => {
    if (open && anchor !== null) panelRef.current?.focus();
  }, [open, anchor]);

  React.useEffect(() => {
    if (!open) return;
    const onPointerDown = (event) => {
      if (rootRef.current && !rootRef.current.contains(event.target)) {
        setOpen(false);
        writeStorage(PANEL_KEY, '0');
      }
    };
    const onKeyDown = (event) => {
      if (event.key === 'Escape') hide(true);
    };
    document.addEventListener('pointerdown', onPointerDown, true);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown, true);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [open]);

  const statusKey = `status.${state.status}`;
  const notice = state.status === 'complete' && !state.noticeDismissed;
  const percent = Math.round(progress * 100);
  const badgeText = state.status === 'complete' ? tr('badgeDone') : clock;

  const modes = MODE_ORDER.map(mode => h('button', {
    key: mode,
    type: 'button',
    className: 'dsh-pomodoro-mode',
    'data-mode': mode,
    'data-active': state.mode === mode ? 'true' : 'false',
    'aria-pressed': state.mode === mode,
    title: tr('modeResetHint'),
    onClick: () => store.selectMode(mode),
  }, tr(`mode.${mode}`)));

  const panel = open && anchor !== null ? h('section', {
    ref: panelRef,
    className: 'dsh-pomodoro-panel',
    style: { left: anchor.left, bottom: anchor.bottom },
    tabIndex: -1,
    role: 'region',
    'aria-label': tr('title'),
    'data-dsh-pomodoro-panel': true,
    'data-status': state.status,
    'data-mode': state.mode,
    'data-clock': clock,
  },
  h('header', { className: 'dsh-pomodoro-header' },
    h('div', { className: 'dsh-pomodoro-title-group' },
      h(TomatoIcon, { size: 18 }),
      h('span', { className: 'dsh-pomodoro-title' }, tr('title')),
      h('span', {
        className: 'dsh-pomodoro-status',
        'data-status': state.status,
      }, tr(statusKey))),
    h('button', {
      type: 'button',
      className: 'dsh-pomodoro-icon-button',
      'data-action': 'hide',
      'aria-label': tr('hide'),
      title: tr('hide'),
      onClick: () => hide(true),
    }, h(CloseIcon))),
  h('div', {
    className: 'dsh-pomodoro-modes',
    role: 'group',
    'aria-label': tr('modesAria'),
  }, modes),
  h('div', {
    className: 'dsh-pomodoro-time',
    'data-dsh-pomodoro-clock': clock,
    'aria-label': `${tr('title')} ${clock}`,
  }, clock),
  h('div', {
    className: 'dsh-pomodoro-progress',
    role: 'progressbar',
    'aria-label': tr('progress'),
    'aria-valuemin': 0,
    'aria-valuemax': 100,
    'aria-valuenow': percent,
  }, h('span', { style: { width: `${percent}%` } })),
  h('p', { className: 'dsh-pomodoro-caption' }, tr(`caption.${state.mode}`)),
  notice && h('div', {
    className: 'dsh-pomodoro-notice',
    role: 'status',
    'data-dsh-pomodoro-notice': true,
  },
  h('span', { className: 'dsh-pomodoro-notice-text' }, tr(`notice.${state.mode}`)),
  h('button', {
    type: 'button',
    className: 'dsh-pomodoro-notice-action',
    'data-action': 'dismiss',
    onClick: () => store.dismiss(),
  }, tr('dismiss'))),
  h('div', { className: 'dsh-pomodoro-controls' },
    h('button', {
      type: 'button',
      className: 'dsh-pomodoro-control',
      'data-action': 'start',
      'data-primary': state.status === 'idle' || state.status === 'complete' ? 'true' : 'false',
      disabled: state.status !== 'idle' && state.status !== 'complete',
      onClick: () => store.start(),
    }, tr('start')),
    h('button', {
      type: 'button',
      className: 'dsh-pomodoro-control',
      'data-action': 'pause',
      'data-primary': state.status === 'running' ? 'true' : 'false',
      disabled: state.status !== 'running',
      onClick: () => store.pause(),
    }, tr('pause')),
    h('button', {
      type: 'button',
      className: 'dsh-pomodoro-control',
      'data-action': 'resume',
      'data-primary': state.status === 'paused' ? 'true' : 'false',
      disabled: state.status !== 'paused',
      onClick: () => store.resume(),
    }, tr('resume')),
    h('button', {
      type: 'button',
      className: 'dsh-pomodoro-control',
      'data-action': 'reset',
      title: tr('resetHint'),
      onClick: () => store.reset(),
    }, tr('reset'))),
  h('p', { className: 'dsh-pomodoro-hint' }, tr('hint'))) : null;

  return h('div', {
    ref: rootRef,
    className: wide ? 'dsh-pomodoro-layer' : 'dsh-pomodoro-layer dsh-pomodoro-rail',
  },
  h('style', { key: 'dsh-pomodoro-style' }, CSS),
  panel,
  h('div', { className: 'dsh-pomodoro-footer' },
    h('button', {
      ref: triggerRef,
      type: 'button',
      className: 'dsh-pomodoro-badge',
      'data-dsh-pomodoro-trigger': true,
      'data-status': state.status,
      'data-open': open ? 'true' : 'false',
      'aria-label': tr('openAria'),
      'aria-expanded': open,
      title: `${tr('title')} · ${badgeText}`,
      onClick: toggle,
    },
    h(TomatoIcon, { size: wide ? 18 : 20 }),
    wide && h('span', { className: 'dsh-pomodoro-label' }, tr('title')),
    wide && h('span', { className: 'dsh-pomodoro-clock' }, badgeText),
    h('span', {
      className: 'dsh-pomodoro-dot',
      'data-status': state.status,
      'aria-hidden': true,
    }))));
}

function apply(ctx) {
  ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'dsh-pomodoro: dictionary');
  ctx.effect(() => () => store.stop(), 'dsh-pomodoro: timer');
  ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
    name: 'sidebar.footer.action',
    id: 'dsh-pomodoro',
    order: -10,
    locale: NS,
  }, PomodoroAction));
}

return { inject: ['slots', 'locale'], apply };
  },
});
