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 };
