/* =========================
WC TOOL — Scoped styles
========================= */
.wc-tool {
--wc-font-sans: Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, "Apple Color Emoji", "Segoe UI Emoji";
--wc-font-body: "Open Sans", var(--wc-font-sans);
/* Brand + calm palette */
--wc-brand: #4A7C59; /* primary evergreen */
--wc-brand-2: #87A96B; /* sage */
--wc-action: #52B788; /* action green */
--wc-trust: #4A90A4; /* trust blue */
--wc-danger: #B91C1C; /* restrained red */
/* Light theme surfaces */
--wc-page: transparent;
--wc-surface: #FFFFFF;
--wc-surface-2: #F4F7F5;
--wc-text: #111827;
--wc-muted: rgba(17, 24, 39, 0.72);
--wc-soft: rgba(17, 24, 39, 0.10);
--wc-border: rgba(17, 24, 39, 0.16);
/* Inputs */
--wc-input: #FFFFFF;
--wc-input-border: rgba(17, 24, 39, 0.18);
/* Focus */
--wc-focus: rgba(82, 183, 136, 0.38);
/* Radius + spacing */
--wc-r-lg: 18px;
--wc-r-md: 14px;
--wc-r-sm: 12px;
--wc-gap-1: 10px;
--wc-gap-2: 14px;
--wc-gap-3: 18px;
--wc-gap-4: 26px;
--wc-gap-5: 34px;
/* Typography */
--wc-title: clamp(18px, 2.3vw, 22px);
--wc-h2: clamp(22px, 3vw, 28px);
--wc-h3: clamp(16px, 2.2vw, 18px);
--wc-body: 15px;
--wc-small: 13px;
/* Motion */
--wc-ease: cubic-bezier(0.2, 0.8, 0.2, 1);
font-family: var(--wc-font-sans);
color: var(--wc-text);
background: var(--wc-page);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Dark theme (toggle via data-theme="dark") */
.wc-tool[data-theme="dark"] {
--wc-surface: #070B09; /* darker background */
--wc-surface-2: #0B1210;
--wc-text: rgba(255, 255, 255, 0.92);
--wc-muted: rgba(255, 255, 255, 0.70);
--wc-soft: rgba(255, 255, 255, 0.10);
--wc-border: rgba(255, 255, 255, 0.16);
--wc-input: #0B1210;
--wc-input-border: rgba(255, 255, 255, 0.18);
--wc-focus: rgba(135, 169, 107, 0.40);
}
.wc-tool * { box-sizing: border-box; }
.wc-tool a { color: inherit; text-decoration: none; }
.wc-tool button, .wc-tool input, .wc-tool textarea, .wc-tool select {
font: inherit;
color: inherit;
}
/* Layout shell */
.wc-shell {
max-width: 860px;
margin: 0 auto;
padding: clamp(14px, 2.8vw, 26px);
padding-top: clamp(10px, 2.2vw, 20px);
}
.wc-card {
background: var(--wc-surface);
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-lg);
overflow: visible; /* must stretch to full height of contents */
}
.wc-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--wc-gap-3);
padding: clamp(14px, 2.6vw, 22px);
border-bottom: 1px solid var(--wc-border);
}
.wc-brandline {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.wc-logo {
width: 32px;
height: 32px;
display: block;
object-fit: contain;
border-radius: 8px;
background: transparent;
flex: 0 0 auto;
}
.wc-titleblock {
display: flex;
flex-direction: column;
min-width: 0;
}
.wc-title {
font-size: var(--wc-title);
line-height: 1.2;
font-weight: 700;
letter-spacing: -0.01em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.wc-subtitle {
font-size: var(--wc-small);
color: var(--wc-muted);
line-height: 1.2;
margin-top: 4px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.wc-actions {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
}
.wc-iconbtn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border-radius: 12px;
border: 1px solid var(--wc-border);
background: transparent;
cursor: pointer;
transition: background 180ms var(--wc-ease), border-color 180ms var(--wc-ease);
}
.wc-iconbtn:hover {
background: var(--wc-surface-2);
border-color: color-mix(in srgb, var(--wc-border), var(--wc-brand) 18%);
}
.wc-iconbtn:focus-visible {
outline: 3px solid var(--wc-focus);
outline-offset: 2px;
}
.wc-icon {
width: 18px;
height: 18px;
stroke-width: 1.9;
color: currentColor;
opacity: 0.92;
}
.wc-main {
padding: clamp(16px, 2.8vw, 26px);
}
/* Pane system */
.wc-pane { display: none; }
.wc-pane[aria-hidden="false"] { display: block; }
.wc-panehead {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: var(--wc-gap-4);
}
.wc-h2 {
font-size: var(--wc-h2);
letter-spacing: -0.02em;
line-height: 1.15;
margin: 0;
font-weight: 800;
}
.wc-lead {
margin: 0;
color: var(--wc-muted);
line-height: 1.55;
font-family: var(--wc-font-body);
font-size: var(--wc-body);
}
.wc-grid {
display: grid;
gap: var(--wc-gap-4);
}
.wc-section {
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-md);
padding: clamp(14px, 2.5vw, 20px);
background: color-mix(in srgb, var(--wc-surface), var(--wc-brand-2) 2%);
}
.wc-sectiontitle {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--wc-gap-2);
margin-bottom: var(--wc-gap-2);
}
.wc-h3 {
font-size: var(--wc-h3);
margin: 0;
font-weight: 700;
letter-spacing: -0.01em;
}
.wc-minihelp {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--wc-muted);
font-size: var(--wc-small);
font-family: var(--wc-font-body);
}
.wc-why {
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: 999px;
border: 1px solid var(--wc-border);
background: transparent;
cursor: pointer;
transition: background 180ms var(--wc-ease);
}
.wc-why:hover { background: var(--wc-surface-2); }
.wc-why:focus-visible {
outline: 3px solid var(--wc-focus);
outline-offset: 2px;
}
.wc-why span {
font-size: 12px;
font-weight: 800;
letter-spacing: -0.02em;
opacity: 0.92;
}
/* Segmented choice */
.wc-seg {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.wc-segbtn {
border: 1px solid var(--wc-border);
border-radius: 14px;
padding: 12px 12px;
text-align: left;
background: transparent;
cursor: pointer;
transition: background 180ms var(--wc-ease), border-color 180ms var(--wc-ease);
display: flex;
flex-direction: column;
gap: 6px;
min-height: 74px;
}
.wc-segbtn:hover {
background: var(--wc-surface-2);
border-color: color-mix(in srgb, var(--wc-border), var(--wc-brand) 18%);
}
.wc-segbtn[aria-pressed="true"] {
border-color: color-mix(in srgb, var(--wc-brand), var(--wc-border) 35%);
background: color-mix(in srgb, var(--wc-surface), var(--wc-brand) 6%);
}
.wc-segname {
display: flex;
align-items: center;
gap: 10px;
font-weight: 800;
letter-spacing: -0.01em;
}
.wc-segdesc {
font-family: var(--wc-font-body);
color: var(--wc-muted);
font-size: var(--wc-small);
line-height: 1.35;
}
/* Controls */
.wc-row { display: grid; gap: var(--wc-gap-3); }
.wc-row2 { display: grid; gap: var(--wc-gap-3); grid-template-columns: 1fr 1fr; }
@media (max-width: 720px) { .wc-row2 { grid-template-columns: 1fr; } }
.wc-field {
display: grid;
gap: 8px;
}
.wc-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
font-size: var(--wc-small);
color: var(--wc-muted);
font-weight: 600;
letter-spacing: 0.01em;
}
.wc-input, .wc-textarea, .wc-select {
width: 100%;
background: var(--wc-input);
border: 1px solid var(--wc-input-border);
border-radius: 14px;
padding: 12px 12px;
font-family: var(--wc-font-body);
font-size: var(--wc-body);
line-height: 1.35;
transition: border-color 180ms var(--wc-ease), background 180ms var(--wc-ease);
}
.wc-textarea { min-height: 100px; resize: vertical; }
.wc-input:focus, .wc-textarea:focus, .wc-select:focus {
outline: 3px solid var(--wc-focus);
outline-offset: 2px;
border-color: color-mix(in srgb, var(--wc-brand), var(--wc-input-border) 45%);
}
.wc-sliderwrap {
display: grid;
gap: 10px;
}
.wc-slider {
width: 100%;
accent-color: var(--wc-action);
}
.wc-pillrow {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.wc-pill {
border: 1px solid var(--wc-border);
background: transparent;
border-radius: 999px;
padding: 9px 12px;
cursor: pointer;
font-size: var(--wc-small);
font-family: var(--wc-font-body);
color: var(--wc-text);
transition: background 180ms var(--wc-ease), border-color 180ms var(--wc-ease);
display: inline-flex;
align-items: center;
gap: 8px;
}
.wc-pill:hover { background: var(--wc-surface-2); }
.wc-pill[aria-pressed="true"] {
background: color-mix(in srgb, var(--wc-surface), var(--wc-brand) 7%);
border-color: color-mix(in srgb, var(--wc-brand), var(--wc-border) 35%);
}
.wc-pill svg { width: 16px; height: 16px; stroke-width: 1.8; opacity: 0.95; }
.wc-checklist {
display: grid;
gap: 10px;
margin-top: 6px;
}
.wc-check {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 10px 10px;
border: 1px solid var(--wc-border);
border-radius: 14px;
background: transparent;
}
.wc-check input { margin-top: 2px; accent-color: var(--wc-action); }
.wc-check b { font-weight: 700; }
.wc-check p {
margin: 2px 0 0 0;
color: var(--wc-muted);
font-family: var(--wc-font-body);
font-size: var(--wc-small);
line-height: 1.4;
}
/* Buttons */
.wc-btnrow {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: var(--wc-gap-4);
align-items: center;
justify-content: flex-end;
}
.wc-btn {
border-radius: 14px;
padding: 12px 14px;
border: 1px solid var(--wc-border);
background: transparent;
cursor: pointer;
font-weight: 700;
letter-spacing: -0.01em;
transition: background 180ms var(--wc-ease), border-color 180ms var(--wc-ease), transform 180ms var(--wc-ease);
display: inline-flex;
align-items: center;
gap: 10px;
min-height: 46px;
}
.wc-btn:hover { background: var(--wc-surface-2); }
.wc-btn:active { transform: translateY(1px); }
.wc-btn:focus-visible { outline: 3px solid var(--wc-focus); outline-offset: 2px; }
.wc-btnprimary {
border-color: color-mix(in srgb, var(--wc-brand), var(--wc-border) 35%);
background: linear-gradient(135deg,
color-mix(in srgb, var(--wc-action), #ffffff 0%) 0%,
color-mix(in srgb, var(--wc-brand), #ffffff 0%) 100%);
color: rgba(255, 255, 255, 0.96);
}
.wc-tool[data-theme="dark"] .wc-btnprimary {
color: rgba(255, 255, 255, 0.96);
}
.wc-btnprimary:hover {
background: linear-gradient(135deg,
color-mix(in srgb, var(--wc-action), #000000 6%) 0%,
color-mix(in srgb, var(--wc-brand), #000000 6%) 100%);
}
.wc-btndanger {
border-color: color-mix(in srgb, var(--wc-danger), var(--wc-border) 25%);
background: color-mix(in srgb, var(--wc-surface), var(--wc-danger) 10%);
color: var(--wc-text);
}
.wc-btndanger:hover {
background: color-mix(in srgb, var(--wc-surface), var(--wc-danger) 14%);
}
.wc-btnghost {
border-color: transparent;
background: transparent;
color: var(--wc-muted);
padding-left: 6px;
padding-right: 6px;
min-height: 42px;
}
.wc-btnghost:hover { background: transparent; color: var(--wc-text); }
.wc-note {
margin: 0;
font-family: var(--wc-font-body);
font-size: var(--wc-small);
color: var(--wc-muted);
line-height: 1.5;
}
.wc-divider {
height: 1px;
background: var(--wc-border);
margin: var(--wc-gap-4) 0;
}
/* Timer view */
.wc-timerwrap {
display: grid;
gap: var(--wc-gap-4);
}
.wc-timerface {
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-md);
padding: clamp(16px, 3vw, 26px);
background: color-mix(in srgb, var(--wc-surface), var(--wc-brand-2) 2%);
display: grid;
gap: 12px;
}
.wc-timerlabel {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: var(--wc-muted);
font-family: var(--wc-font-body);
font-size: var(--wc-small);
}
.wc-timerdigits {
font-variant-numeric: tabular-nums;
font-weight: 900;
letter-spacing: -0.03em;
font-size: clamp(44px, 7vw, 72px);
line-height: 1.05;
margin: 0;
}
.wc-timerhint {
display: grid;
gap: 6px;
color: var(--wc-muted);
font-family: var(--wc-font-body);
font-size: var(--wc-body);
line-height: 1.55;
}
.wc-inlinechip {
display: inline-flex;
align-items: center;
gap: 8px;
border: 1px solid var(--wc-border);
border-radius: 999px;
padding: 7px 10px;
font-size: var(--wc-small);
color: var(--wc-muted);
font-family: var(--wc-font-body);
background: transparent;
}
.wc-inlinechip svg { width: 16px; height: 16px; stroke-width: 1.8; opacity: 0.9; }
.wc-breathwrap {
border: 1px dashed var(--wc-border);
border-radius: var(--wc-r-md);
padding: 14px;
display: grid;
gap: 10px;
background: transparent;
}
.wc-breathrow {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
justify-content: space-between;
}
.wc-breathtitle {
margin: 0;
font-weight: 800;
letter-spacing: -0.01em;
font-size: var(--wc-h3);
}
.wc-breathmeta {
margin: 0;
color: var(--wc-muted);
font-family: var(--wc-font-body);
font-size: var(--wc-small);
line-height: 1.45;
}
.wc-breathbar {
height: 10px;
border-radius: 999px;
background: var(--wc-soft);
overflow: hidden;
border: 1px solid var(--wc-border);
}
.wc-breathfill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--wc-action), var(--wc-brand));
transition: width 120ms linear;
}
/* Modals (no shadows, extra top margin for sticky headers) */
.wc-modalbackdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.35);
display: none;
align-items: flex-start;
justify-content: center;
padding: 10vh 16px 16px; /* top margin so it isn't cut off */
z-index: 9999;
}
.wc-tool[data-theme="dark"] .wc-modalbackdrop { background: rgba(0, 0, 0, 0.55); }
.wc-modal {
width: min(820px, 100%);
background: var(--wc-surface);
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-lg);
overflow: hidden;
}
.wc-modalhead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 16px 18px;
border-bottom: 1px solid var(--wc-border);
}
.wc-modaltitle {
display: flex;
align-items: center;
gap: 10px;
margin: 0;
font-weight: 900;
letter-spacing: -0.02em;
font-size: 16px;
}
.wc-modalbody {
padding: 18px;
display: grid;
gap: var(--wc-gap-4);
}
.wc-modalftr {
padding: 16px 18px;
border-top: 1px solid var(--wc-border);
display: flex;
gap: 12px;
justify-content: flex-end;
flex-wrap: wrap;
}
/* Toast */
.wc-toast {
position: fixed;
left: 50%;
transform: translateX(-50%);
bottom: 18px;
z-index: 10000;
background: var(--wc-surface);
border: 1px solid var(--wc-border);
border-radius: 999px;
padding: 10px 14px;
display: none;
gap: 10px;
align-items: center;
max-width: min(720px, calc(100% - 22px));
}
.wc-toast p {
margin: 0;
font-family: var(--wc-font-body);
font-size: var(--wc-small);
color: var(--wc-muted);
line-height: 1.3;
}
/* Article below tool */
.wc-article {
margin-top: 24px;
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-lg);
overflow: visible;
background: var(--wc-surface);
}
.wc-article .wc-articleinner {
padding: clamp(16px, 2.8vw, 26px);
font-family: var(--wc-font-body);
}
.wc-article h2 {
font-family: var(--wc-font-sans);
font-size: clamp(20px, 3.2vw, 26px);
letter-spacing: -0.02em;
margin: 0 0 12px 0;
}
.wc-article h3 {
font-family: var(--wc-font-sans);
font-size: clamp(16px, 2.4vw, 18px);
letter-spacing: -0.01em;
margin: 26px 0 10px 0;
}
.wc-article p, .wc-article li {
color: var(--wc-muted);
line-height: 1.7;
font-size: 15px;
}
.wc-article a {
text-decoration: underline;
text-underline-offset: 3px;
}
.wc-article .wc-callout {
border: 1px solid var(--wc-border);
border-radius: var(--wc-r-md);
padding: 14px 14px;
background: color-mix(in srgb, var(--wc-surface), var(--wc-brand-2) 2%);
margin: 14px 0;
}
.wc-article .wc-callout b { color: var(--wc-text); }
.wc-refs {
border-top: 1px solid var(--wc-border);
margin-top: 24px;
padding-top: 18px;
}
.wc-refs ol {
margin: 10px 0 0 18px;
padding: 0;
}
.wc-refs li { margin: 10px 0; }
.wc-sup a {
font-family: var(--wc-font-sans);
font-weight: 700;
font-size: 12px;
text-decoration: none;
border-bottom: 1px solid color-mix(in srgb, var(--wc-border), var(--wc-brand) 22%);
padding-bottom: 1px;
margin-left: 2px;
}
/* Utility */
.wc-hidden { display: none !important; }
.wc-right { text-align: right; }
.wc-mono { font-variant-numeric: tabular-nums; }
(() => {
const root = document.getElementById('wc-tool-timeout');
if (!root || root.dataset.wcInitialized === '1') return;
root.dataset.wcInitialized = '1';
// Bundled decorative icons: no network or loading-order dependency.
const wcIconPaths = {"activity":"","alert-triangle":" ","arrow-left":" ","arrow-right":" ","check":"","check-circle-2":" ","chevron-right":"","circle-dot":" ","copy":" ","corner-up-left":" ","droplet":"","footprints":" ","hand":" ","history":" ","leaf":" ","list-checks":" ","moon":"","music":" ","pause":" ","pencil":" ","play":"","plus":" ","refresh-ccw":" ","rotate-ccw":" ","save":" ","settings":" ","shield":"","sliders-horizontal":" ","sparkles":" ","square":"","sun":" ","timer":" ","trash-2":" ","wind":" ","x":" ","zap":""};
const wcRenderIcons = () => {
try {
root.querySelectorAll('[data-lucide]').forEach((node) => {
const name = node.getAttribute('data-lucide');
const paths = wcIconPaths[name];
if (!paths || node.getAttribute('data-wc-rendered') === name) return;
const isSvg = node.namespaceURI === 'http://www.w3.org/2000/svg';
const svg = isSvg ? node : document.createElementNS('http://www.w3.org/2000/svg', 'svg');
if (!isSvg) {
Array.from(node.attributes).forEach((attr) => svg.setAttribute(attr.name, attr.value));
}
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', 'currentColor');
svg.setAttribute('stroke-width', '2');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
svg.setAttribute('data-wc-rendered', name);
svg.innerHTML = paths;
if (!isSvg) node.replaceWith(svg);
});
} catch (error) {
// An optional decoration must never prevent timer controls from starting.
}
};
/* ---------- Icons ---------- */
wcRenderIcons();
/* ---------- Storage ---------- */
const WC_KEYS = {
settings: 'wc_timeout_settings_v1',
history: 'wc_timeout_history_v1',
theme: 'wc_timeout_theme_v1'
};
const nowLocalTimeString = () => {
const d = new Date();
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
};
const addMinutesToTime = (minutes) => {
const d = new Date();
d.setMinutes(d.getMinutes() + minutes);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
};
const parseTimeToToday = (hhmm) => {
const [hh, mm] = hhmm.split(':').map(Number);
const d = new Date();
d.setHours(hh, mm, 0, 0);
return d;
};
const fmtClock = (date) => {
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
};
const fmtDuration = (sec) => {
if (sec {
if (sec {
return Math.random().toString(16).slice(2) + '-' + Date.now().toString(16);
};
const loadJSON = (key, fallback) => {
try {
const raw = localStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw);
} catch {
return fallback;
}
};
const saveJSON = (key, value) => {
try { localStorage.setItem(key, JSON.stringify(value)); } catch {}
};
/* ---------- Default Settings ---------- */
const defaultSettings = {
defaultResetSec: 1200, // 20 min
alertMode: 'sound' // sound | vibrate | both | off
};
let settings = { ...defaultSettings, ...(loadJSON(WC_KEYS.settings, {})) };
/* ---------- Theme ---------- */
const applyTheme = (theme) => {
root.setAttribute('data-theme', theme);
const themeIcon = document.querySelector('#wcThemeBtn i');
if (themeIcon) themeIcon.setAttribute('data-lucide', theme === 'dark' ? 'sun' : 'moon');
wcRenderIcons();
};
const initTheme = () => {
const saved = localStorage.getItem(WC_KEYS.theme);
if (saved === 'dark' || saved === 'light') {
applyTheme(saved);
return;
}
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(prefersDark ? 'dark' : 'light');
};
initTheme();
/* ---------- State ---------- */
const state = {
mode: 'quick', // quick | reset | custom
intensity: 6,
durationSec: 5,
returnTime: addMinutesToTime(20),
scriptCustom: null,
activities: new Set(['Breathing']),
note: '',
breathPreset: '4-6',
agreements: {
noRehearse: true,
noText: true,
returnOnTime: true
},
timer: {
running: false,
endAt: null,
remainingMs: null,
interval: null,
startedAtISO: null
},
reEntry: {
topic: '',
feeling: '',
need: '',
request: ''
}
};
/* ---------- Panes ---------- */
const panes = {
start: document.getElementById('wcPaneStart'),
choose: document.getElementById('wcPaneChoose'),
plan: document.getElementById('wcPanePlan'),
timer: document.getElementById('wcPaneTimer'),
ret: document.getElementById('wcPaneReturn')
};
const showPane = (key) => {
Object.values(panes).forEach(p => p.setAttribute('aria-hidden', 'true'));
panes[key].setAttribute('aria-hidden', 'false');
// keep view stable in-page
try { panes[key].scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } catch {}
};
/* ---------- Elements ---------- */
const el = {
startBtn: document.getElementById('wcStartBtn'),
resetBtn: document.getElementById('wcResetBtn'),
// Choose
modeQuick: document.getElementById('wcModeQuick'),
modeReset: document.getElementById('wcModeReset'),
modeCustom: document.getElementById('wcModeCustom'),
intensity: document.getElementById('wcIntensity'),
intensityLabel: document.getElementById('wcIntensityLabel'),
suggestionChip: document.getElementById('wcSuggestionChip'),
durationSelect: document.getElementById('wcDurationSelect'),
returnTime: document.getElementById('wcReturnTime'),
script: document.getElementById('wcScript'),
copyScriptBtn: document.getElementById('wcCopyScriptBtn'),
editScriptBtn: document.getElementById('wcEditScriptBtn'),
backToStart: document.getElementById('wcBackToStartBtn'),
contToPlan: document.getElementById('wcContinueToPlanBtn'),
// Plan
actBreath: document.getElementById('wcActBreath'),
actWalk: document.getElementById('wcActWalk'),
actWater: document.getElementById('wcActWater'),
actMusic: document.getElementById('wcActMusic'),
actStretch: document.getElementById('wcActStretch'),
actGround: document.getElementById('wcActGround'),
agreeNoRehearse: document.getElementById('wcAgreeNoRehearse'),
agreeNoText: document.getElementById('wcAgreeNoText'),
agreeReturn: document.getElementById('wcAgreeReturn'),
note: document.getElementById('wcNote'),
breathPreset: document.getElementById('wcBreathPreset'),
backToChoose: document.getElementById('wcBackToChooseBtn'),
beginTimer: document.getElementById('wcBeginTimerBtn'),
// Timer
timerMetaLeft: document.getElementById('wcTimerMetaLeft'),
timerDigits: document.getElementById('wcTimerDigits'),
returnChipTime: document.getElementById('wcReturnChipTime'),
actsChip: document.getElementById('wcActsChip'),
breathChip: document.getElementById('wcBreathChip'),
breathWrap: document.getElementById('wcBreathWrap'),
breathMeta: document.getElementById('wcBreathMeta'),
breathPhase: document.getElementById('wcBreathPhase'),
breathPhaseChip: document.getElementById('wcBreathPhaseChip'),
breathFill: document.getElementById('wcBreathFill'),
pauseBtn: document.getElementById('wcPauseBtn'),
addMinuteBtn: document.getElementById('wcAddMinuteBtn'),
endEarlyBtn: document.getElementById('wcEndEarlyBtn'),
doneBtn: document.getElementById('wcDoneBtn'),
// Return
topic: document.getElementById('wcTopic'),
feeling: document.getElementById('wcFeeling'),
need: document.getElementById('wcNeed'),
request: document.getElementById('wcRequest'),
reEntryScript: document.getElementById('wcReEntryScript'),
copyReEntryBtn: document.getElementById('wcCopyReEntryBtn'),
backToTimer: document.getElementById('wcBackToTimerBtn'),
saveBtn: document.getElementById('wcSaveBtn'),
newBtn: document.getElementById('wcNewBtn'),
// Modals
settingsBtn: document.getElementById('wcSettingsBtn'),
settingsModal: document.getElementById('wcSettingsModal'),
closeSettings: document.getElementById('wcCloseSettings'),
closeSettings2: document.getElementById('wcCloseSettings2'),
defaultReset: document.getElementById('wcDefaultReset'),
alertMode: document.getElementById('wcAlertMode'),
saveSettings: document.getElementById('wcSaveSettings'),
historyBtn: document.getElementById('wcHistoryBtn'),
historyModal: document.getElementById('wcHistoryModal'),
closeHistory: document.getElementById('wcCloseHistory'),
closeHistory2: document.getElementById('wcCloseHistory2'),
historyList: document.getElementById('wcHistoryList'),
historyEmpty: document.getElementById('wcHistoryEmpty'),
historyCount: document.getElementById('wcHistoryCount'),
historyDetail: document.getElementById('wcHistoryDetail'),
historySummary: document.getElementById('wcHistorySummary'),
historyCopy: document.getElementById('wcHistoryCopy'),
historyLoad: document.getElementById('wcHistoryLoad'),
historyDelete: document.getElementById('wcHistoryDelete'),
scriptModal: document.getElementById('wcScriptModal'),
closeScript: document.getElementById('wcCloseScript'),
scriptEditor: document.getElementById('wcScriptEditor'),
scriptSave: document.getElementById('wcScriptSave'),
scriptDone: document.getElementById('wcScriptDone'),
confirmModal: document.getElementById('wcConfirmModal'),
closeConfirm: document.getElementById('wcCloseConfirm'),
cancelEndEarly: document.getElementById('wcCancelEndEarly'),
confirmEndEarly: document.getElementById('wcConfirmEndEarly'),
calmCheck: document.getElementById('wcCalmCheck'),
readyCheck: document.getElementById('wcReadyCheck'),
// Theme
themeBtn: document.getElementById('wcThemeBtn'),
// Toast
toast: document.getElementById('wcToast'),
toastText: document.getElementById('wcToastText')
};
/* ---------- Toast ---------- */
let toastTimer = null;
const toast = (msg) => {
el.toastText.textContent = msg;
el.toast.style.display = 'flex';
wcRenderIcons();
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
el.toast.style.display = 'none';
}, 2100);
};
/* ---------- Modal helpers ---------- */
const openModal = (node) => {
node.style.display = 'flex';
node.focus?.();
// prevent background scroll (site-wide)
document.documentElement.style.overflow = 'hidden';
document.body.style.overflow = 'hidden';
};
const closeModal = (node) => {
node.style.display = 'none';
document.documentElement.style.overflow = '';
document.body.style.overflow = '';
};
// click backdrop to close
[el.settingsModal, el.historyModal, el.scriptModal, el.confirmModal].forEach(modal => {
modal.addEventListener('mousedown', (e) => {
if (e.target === modal) closeModal(modal);
});
});
/* ---------- Mode + suggestions ---------- */
const setMode = (mode) => {
state.mode = mode;
const btns = [
[el.modeQuick, 'quick'],
[el.modeReset, 'reset'],
[el.modeCustom, 'custom'],
];
btns.forEach(([b, key]) => b.setAttribute('aria-pressed', String(key === mode)));
// duration defaults by mode
if (mode === 'quick') {
state.durationSec = 5;
el.durationSelect.value = '5';
} else if (mode === 'reset') {
state.durationSec = settings.defaultResetSec;
el.durationSelect.value = String(settings.defaultResetSec);
} else {
// custom: keep current selection, but nudge to a reasonable default
if (![120,300,900,1200,1800,2700].includes(state.durationSec)) {
state.durationSec = 900;
el.durationSelect.value = '900';
}
}
syncReturnTime();
syncScript();
syncSuggestionChip();
};
const recommendByIntensity = (x) => {
// Simple, user-friendly heuristic:
// 0-3 -> quick (5-15 sec)
// 4-6 -> short (2-5 min)
// 7-10 -> reset (20+)
if (x <= 3) return { mode: 'quick', duration: 10, label: 'Quick micro‑break' };
if (x {
const rec = recommendByIntensity(state.intensity);
const labelMap = {
quick: '5‑second break',
reset: 'Reset break',
custom: 'Custom'
};
const recLabel = (state.intensity <= 3)
? 'Suggested: 5‑10s pause'
: (state.intensity <= 6)
? 'Suggested: 2–5 min reset'
: 'Suggested: Reset break';
el.suggestionChip.querySelector('span')?.remove?.();
// chip already has icon; set its text safely:
el.suggestionChip.innerHTML = '
' + recLabel;
wcRenderIcons();
};
const syncReturnTime = () => {
const mins = Math.max(1, Math.round(state.durationSec / 60));
const suggested = addMinutesToTime(mins);
// For quick breaks, keep return time immediate-ish (but still explicit)
const t = (state.durationSec {
const durText = state.durationSec {
const script = state.scriptCustom ?? buildScript();
el.script.value = script;
};
/* ---------- Activity pills ---------- */
const toggleActivity = (name, btn) => {
if (state.activities.has(name)) {
// keep at least one activity
if (state.activities.size === 1) return;
state.activities.delete(name);
btn.setAttribute('aria-pressed', 'false');
} else {
state.activities.add(name);
btn.setAttribute('aria-pressed', 'true');
}
syncTimerChips();
};
/* ---------- Breathing UI ---------- */
let breath = {
active: false,
inSec: 4,
outSec: 6,
phase: 'inhale',
phaseStart: 0,
phaseMs: 4000
};
const setBreathPreset = (preset) => {
state.breathPreset = preset;
if (preset === 'off') {
breath.active = false;
el.breathWrap.classList.add('wc-hidden');
return;
}
const [i, o] = preset.split('-').map(Number);
breath = {
active: true,
inSec: i,
outSec: o,
phase: 'inhale',
phaseStart: Date.now(),
phaseMs: i * 1000
};
el.breathWrap.classList.remove('wc-hidden');
el.breathMeta.textContent = `Inhale • ${i}s — Exhale • ${o}s`;
el.breathPhase.textContent = 'Inhale';
el.breathFill.style.width = '0%';
};
const tickBreath = () => {
if (!breath.active) return;
const now = Date.now();
const elapsed = now - breath.phaseStart;
const pct = Math.max(0, Math.min(1, elapsed / breath.phaseMs));
el.breathFill.style.width = `${Math.round(pct * 100)}%`;
if (elapsed >= breath.phaseMs) {
// switch phase
breath.phase = breath.phase === 'inhale' ? 'exhale' : 'inhale';
breath.phaseStart = now;
breath.phaseMs = (breath.phase === 'inhale' ? breath.inSec : breath.outSec) * 1000;
el.breathPhase.textContent = breath.phase === 'inhale' ? 'Inhale' : 'Exhale';
el.breathFill.style.width = '0%';
}
};
const syncTimerChips = () => {
const modeLabel = state.mode === 'quick' ? '5‑second break' : state.mode === 'reset' ? 'Reset break' : 'Custom break';
const durLabel = fmtDigits(state.durationSec);
el.timerMetaLeft.textContent = `${modeLabel} • ${durLabel}`;
// activities chip
const acts = Array.from(state.activities);
const planText = acts.length <= 2 ? acts.join(' + ') : `${acts[0]} + ${acts.length - 1} more`;
el.actsChip.innerHTML = `
Plan: ${escapeHtml(planText)}`;
// breathing chip
if (state.breathPreset === 'off') {
el.breathChip.classList.add('wc-hidden');
} else {
el.breathChip.classList.remove('wc-hidden');
el.breathChip.innerHTML = `
Guided: ${state.breathPreset.replace('-', ' / ')}`;
}
wcRenderIcons();
};
/* ---------- Timer ---------- */
const clearTimerInterval = () => {
if (state.timer.interval) clearInterval(state.timer.interval);
state.timer.interval = null;
};
const computeReturnAt = () => {
// Return time field represents a clock time today.
const hhmm = el.returnTime.value || state.returnTime || nowLocalTimeString();
const d = parseTimeToToday(hhmm);
// If return time is earlier than now and duration is longer, bump to next day only if clearly intended.
// Keep simple: if return time is > 6 hours behind, assume next day.
const now = new Date();
const diff = d.getTime() - now.getTime();
if (diff {
// Validate agreements gently
state.agreements.noRehearse = !!el.agreeNoRehearse.checked;
state.agreements.noText = !!el.agreeNoText.checked;
state.agreements.returnOnTime = !!el.agreeReturn.checked;
state.note = el.note.value.trim();
state.breathPreset = el.breathPreset.value;
// update return time from control
state.returnTime = el.returnTime.value || state.returnTime;
const durationMs = state.durationSec * 1000;
state.timer.running = true;
state.timer.remainingMs = durationMs;
state.timer.endAt = Date.now() + durationMs;
state.timer.startedAtISO = new Date().toISOString();
// Timer UI
el.timerDigits.textContent = fmtDigits(state.durationSec);
el.pauseBtn.innerHTML = '
Pause';
wcRenderIcons();
syncTimerChips();
// Return chip
const returnAt = computeReturnAt();
el.returnChipTime.textContent = fmtClock(returnAt);
// Breathing
setBreathPreset(state.breathPreset);
// interval tick
clearTimerInterval();
state.timer.interval = setInterval(() => {
if (!state.timer.running) return;
const remaining = Math.max(0, state.timer.endAt - Date.now());
state.timer.remainingMs = remaining;
const sec = Math.ceil(remaining / 1000);
el.timerDigits.textContent = fmtDigits(sec);
tickBreath();
if (remaining {
if (!state.timer.running) return;
state.timer.running = false;
const remaining = Math.max(0, state.timer.endAt - Date.now());
state.timer.remainingMs = remaining;
el.pauseBtn.innerHTML = '
Resume';
wcRenderIcons();
};
const resumeTimer = () => {
if (state.timer.running) return;
state.timer.running = true;
state.timer.endAt = Date.now() + state.timer.remainingMs;
el.pauseBtn.innerHTML = '
Pause';
wcRenderIcons();
};
const addMinute = () => {
const add = 60 * 1000;
if (state.timer.running) {
state.timer.endAt += add;
} else {
state.timer.remainingMs += add;
}
toast('Added 1 minute.');
};
const stopTimer = () => {
clearTimerInterval();
state.timer.running = false;
state.timer.endAt = null;
state.timer.remainingMs = null;
};
/* ---------- Alerts ---------- */
const beep = () => {
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
const ctx = new AudioCtx();
const o = ctx.createOscillator();
const g = ctx.createGain();
o.type = 'sine';
o.frequency.value = 660;
g.gain.value = 0.04;
o.connect(g);
g.connect(ctx.destination);
o.start();
setTimeout(() => {
o.stop();
ctx.close();
}, 240);
} catch {}
};
const vibrate = () => {
try {
if (navigator.vibrate) navigator.vibrate([120, 80, 120]);
} catch {}
};
const doAlert = () => {
const mode = settings.alertMode;
if (mode === 'off') return;
if (mode === 'sound' || mode === 'both') beep();
if (mode === 'vibrate' || mode === 'both') vibrate();
};
const finishTimer = (early) => {
stopTimer();
doAlert();
// prepare re-entry script
syncReEntryScript();
showPane('ret');
if (!early) toast('Time‑out complete. Ready to return.');
};
/* ---------- Re-entry script ---------- */
const syncReEntryScript = () => {
state.reEntry.topic = el.topic.value.trim();
state.reEntry.feeling = el.feeling.value.trim();
state.reEntry.need = el.need.value.trim();
state.reEntry.request = el.request.value.trim();
const topic = state.reEntry.topic ? `About: ${state.reEntry.topic}. ` : '';
const feeling = state.reEntry.feeling ? `I’m feeling ${state.reEntry.feeling}. ` : 'I’m feeling overwhelmed. ';
const need = state.reEntry.need ? `What I need is ${state.reEntry.need}. ` : '';
const request = state.reEntry.request ? `My request is: ${state.reEntry.request}` : 'My request is: can we take turns and reflect first?';
el.reEntryScript.value = `${topic}${feeling}${need}${request}`.trim();
};
/* ---------- History ---------- */
let history = loadJSON(WC_KEYS.history, []);
let selectedHistoryId = null;
const buildHistorySummary = (item) => {
const created = new Date(item.createdAtISO);
const lines = [];
lines.push(`Time‑out saved: ${created.toLocaleString()}`);
lines.push(`Style: ${item.modeLabel}`);
lines.push(`Duration: ${fmtDuration(item.durationSec)}`);
if (item.returnAtISO) {
const rt = new Date(item.returnAtISO);
lines.push(`Return time: ${rt.toLocaleString()}`);
}
if (item.activities?.length) lines.push(`Plan: ${item.activities.join(', ')}`);
if (item.note) lines.push(`Note: ${item.note}`);
if (item.reEntry) {
const re = item.reEntry;
const parts = [];
if (re.topic) parts.push(`Topic: ${re.topic}`);
if (re.feeling) parts.push(`Feeling: ${re.feeling}`);
if (re.need) parts.push(`Need: ${re.need}`);
if (re.request) parts.push(`Request: ${re.request}`);
if (parts.length) lines.push(`Re‑entry: ${parts.join(' • ')}`);
}
return lines.join('\n');
};
const renderHistory = () => {
el.historyList.innerHTML = '';
el.historyDetail.classList.add('wc-hidden');
el.historyEmpty.style.display = history.length ? 'none' : 'block';
el.historyCount.textContent = `${history.length} saved`;
if (!history.length) return;
history
.slice()
.sort((a, b) => (b.createdAtISO > a.createdAtISO ? 1 : -1))
.forEach(item => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'wc-btn';
btn.style.width = '100%';
btn.style.justifyContent = 'space-between';
btn.style.alignItems = 'center';
const left = document.createElement('div');
left.style.display = 'grid';
left.style.gap = '4px';
left.style.textAlign = 'left';
const title = document.createElement('div');
title.style.fontWeight = '900';
title.style.letterSpacing = '-0.01em';
title.textContent = item.modeLabel + ' • ' + fmtDuration(item.durationSec);
const meta = document.createElement('div');
meta.style.color = 'var(--wc-muted)';
meta.style.fontFamily = 'var(--wc-font-body)';
meta.style.fontSize = '13px';
meta.textContent = new Date(item.createdAtISO).toLocaleString();
left.appendChild(title);
left.appendChild(meta);
const right = document.createElement('div');
right.style.display = 'inline-flex';
right.style.alignItems = 'center';
right.style.gap = '10px';
right.innerHTML = '
';
btn.appendChild(left);
btn.appendChild(right);
btn.addEventListener('click', () => {
selectedHistoryId = item.id;
el.historyDetail.classList.remove('wc-hidden');
el.historySummary.value = buildHistorySummary(item);
toast('Opened saved time‑out.');
wcRenderIcons();
});
el.historyList.appendChild(btn);
});
wcRenderIcons();
};
const saveCurrentToHistory = () => {
const modeLabel = state.mode === 'quick' ? '5‑second break' : state.mode === 'reset' ? 'Reset break' : 'Custom break';
const returnAt = computeReturnAt();
const item = {
id: uid(),
createdAtISO: new Date().toISOString(),
mode: state.mode,
modeLabel,
durationSec: state.durationSec,
returnAtISO: (state.durationSec {
if (!selectedHistoryId) return;
history = history.filter(x => x.id !== selectedHistoryId);
saveJSON(WC_KEYS.history, history);
selectedHistoryId = null;
renderHistory();
toast('Deleted.');
};
const loadSelectedHistoryIntoState = () => {
if (!selectedHistoryId) return;
const item = history.find(x => x.id === selectedHistoryId);
if (!item) return;
state.mode = item.mode;
state.durationSec = item.durationSec;
el.durationSelect.value = String(item.durationSec);
// Set mode UI
setMode(item.mode);
// Return time
if (item.returnAtISO) {
const d = new Date(item.returnAtISO);
const hh = String(d.getHours()).padStart(2,'0');
const mm = String(d.getMinutes()).padStart(2,'0');
el.returnTime.value = `${hh}:${mm}`;
state.returnTime = el.returnTime.value;
} else {
el.returnTime.value = nowLocalTimeString();
state.returnTime = el.returnTime.value;
}
// Activities
state.activities = new Set(item.activities?.length ? item.activities : ['Breathing']);
const mapBtn = (name) => ({
'Breathing': el.actBreath,
'Walk': el.actWalk,
'Water / tea': el.actWater,
'Music': el.actMusic,
'Stretch': el.actStretch,
'Grounding': el.actGround
})[name];
// reset all buttons
[el.actBreath, el.actWalk, el.actWater, el.actMusic, el.actStretch, el.actGround].forEach(b => b.setAttribute('aria-pressed','false'));
state.activities.forEach(name => {
const b = mapBtn(name);
if (b) b.setAttribute('aria-pressed','true');
});
// Note + agreements + breath
el.note.value = item.note || '';
el.agreeNoRehearse.checked = !!item.agreements?.noRehearse;
el.agreeNoText.checked = !!item.agreements?.noText;
el.agreeReturn.checked = !!item.agreements?.returnOnTime;
el.breathPreset.value = item.breathPreset || '4-6';
// Re-entry
el.topic.value = item.reEntry?.topic || '';
el.feeling.value = item.reEntry?.feeling || '';
el.need.value = item.reEntry?.need || '';
el.request.value = item.reEntry?.request || '';
state.scriptCustom = null;
syncScript();
syncTimerChips();
syncReEntryScript();
closeModal(el.historyModal);
showPane('choose');
toast('Loaded. Adjust anything you like, then continue.');
};
/* ---------- Escape HTML for chips ---------- */
function escapeHtml(str) {
return String(str)
.replaceAll('&', '&')
.replaceAll('', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
/* ---------- Copy helpers ---------- */
const copyText = async (text) => {
try {
await navigator.clipboard.writeText(text);
toast('Copied.');
} catch {
// fallback
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); toast('Copied.'); } catch { toast('Copy failed.'); }
document.body.removeChild(ta);
}
};
/* ---------- Settings ---------- */
const openSettings = () => {
el.defaultReset.value = String(settings.defaultResetSec);
el.alertMode.value = settings.alertMode;
openModal(el.settingsModal);
};
const persistSettings = () => {
settings.defaultResetSec = Number(el.defaultReset.value);
settings.alertMode = el.alertMode.value;
saveJSON(WC_KEYS.settings, settings);
toast('Settings saved.');
};
/* ---------- Reset ---------- */
const hardReset = () => {
stopTimer();
state.mode = 'quick';
state.intensity = 6;
state.durationSec = 5;
state.scriptCustom = null;
state.activities = new Set(['Breathing']);
state.note = '';
state.breathPreset = '4-6';
state.agreements = { noRehearse: true, noText: true, returnOnTime: true };
state.reEntry = { topic:'', feeling:'', need:'', request:'' };
el.intensity.value = '6';
el.intensityLabel.textContent = '6 / 10';
el.durationSelect.value = '5';
el.returnTime.value = addMinutesToTime(20);
el.note.value = '';
el.breathPreset.value = '4-6';
el.agreeNoRehearse.checked = true;
el.agreeNoText.checked = true;
el.agreeReturn.checked = true;
el.topic.value = '';
el.feeling.value = '';
el.need.value = '';
el.request.value = '';
// pills
[el.actBreath, el.actWalk, el.actWater, el.actMusic, el.actStretch, el.actGround].forEach(b => b.setAttribute('aria-pressed','false'));
el.actBreath.setAttribute('aria-pressed','true');
setMode('quick');
syncScript();
syncTimerChips();
syncReEntryScript();
showPane('start');
toast('Reset.');
};
/* ---------- Wire up events ---------- */
el.startBtn.addEventListener('click', () => {
showPane('choose');
});
el.backToStart.addEventListener('click', () => showPane('start'));
el.contToPlan.addEventListener('click', () => showPane('plan'));
el.backToChoose.addEventListener('click', () => showPane('choose'));
el.beginTimer.addEventListener('click', startTimer);
el.resetBtn.addEventListener('click', hardReset);
// Mode selection
el.modeQuick.addEventListener('click', () => setMode('quick'));
el.modeReset.addEventListener('click', () => setMode('reset'));
el.modeCustom.addEventListener('click', () => setMode('custom'));
// Intensity
el.intensity.addEventListener('input', () => {
state.intensity = Number(el.intensity.value);
el.intensityLabel.textContent = `${state.intensity} / 10`;
syncSuggestionChip();
// Gentle auto-suggest only (don’t force): if user hasn't changed mode recently, nudge duration.
const rec = recommendByIntensity(state.intensity);
if (state.mode === 'quick' && state.intensity >= 7) setMode('reset');
if (state.mode === 'reset' && state.intensity {
state.durationSec = Number(el.durationSelect.value);
// if user picks > 15s, treat as custom unless in reset mode
if (state.durationSec > 15 && state.mode === 'quick') setMode('custom');
if (state.durationSec {
state.returnTime = el.returnTime.value;
// keep script aligned unless customized
if (!state.scriptCustom) syncScript();
});
// Script copy + edit
el.copyScriptBtn.addEventListener('click', () => copyText(el.script.value));
el.editScriptBtn.addEventListener('click', () => {
el.scriptEditor.value = el.script.value;
openModal(el.scriptModal);
});
el.closeScript.addEventListener('click', () => closeModal(el.scriptModal));
el.scriptDone.addEventListener('click', () => closeModal(el.scriptModal));
el.scriptSave.addEventListener('click', () => {
state.scriptCustom = el.scriptEditor.value.trim() || buildScript();
el.script.value = state.scriptCustom;
toast('Script saved.');
});
// Activity pills
el.actBreath.addEventListener('click', () => toggleActivity('Breathing', el.actBreath));
el.actWalk.addEventListener('click', () => toggleActivity('Walk', el.actWalk));
el.actWater.addEventListener('click', () => toggleActivity('Water / tea', el.actWater));
el.actMusic.addEventListener('click', () => toggleActivity('Music', el.actMusic));
el.actStretch.addEventListener('click', () => toggleActivity('Stretch', el.actStretch));
el.actGround.addEventListener('click', () => toggleActivity('Grounding', el.actGround));
// Plan fields
el.note.addEventListener('input', () => state.note = el.note.value);
el.breathPreset.addEventListener('change', () => state.breathPreset = el.breathPreset.value);
// Timer controls
el.pauseBtn.addEventListener('click', () => {
if (state.timer.running) pauseTimer();
else resumeTimer();
});
el.addMinuteBtn.addEventListener('click', addMinute);
el.endEarlyBtn.addEventListener('click', () => {
el.calmCheck.checked = false;
el.readyCheck.checked = false;
openModal(el.confirmModal);
});
el.closeConfirm.addEventListener('click', () => closeModal(el.confirmModal));
el.cancelEndEarly.addEventListener('click', () => closeModal(el.confirmModal));
el.confirmEndEarly.addEventListener('click', () => {
const ok = el.calmCheck.checked && el.readyCheck.checked;
closeModal(el.confirmModal);
if (!ok) {
toast('If either box is unchecked, it’s usually better to keep the pause going.');
return;
}
finishTimer(true);
});
el.doneBtn.addEventListener('click', () => finishTimer(true));
// Return pane
[el.topic, el.feeling, el.need, el.request].forEach(inp => {
inp.addEventListener('input', syncReEntryScript);
});
el.copyReEntryBtn.addEventListener('click', () => copyText(el.reEntryScript.value));
el.backToTimer.addEventListener('click', () => showPane('timer'));
el.newBtn.addEventListener('click', () => {
stopTimer();
showPane('choose');
});
el.saveBtn.addEventListener('click', () => {
saveCurrentToHistory();
});
// Settings modal
el.settingsBtn.addEventListener('click', openSettings);
el.closeSettings.addEventListener('click', () => closeModal(el.settingsModal));
el.closeSettings2.addEventListener('click', () => closeModal(el.settingsModal));
el.saveSettings.addEventListener('click', persistSettings);
// History modal
el.historyBtn.addEventListener('click', () => {
renderHistory();
openModal(el.historyModal);
});
el.closeHistory.addEventListener('click', () => closeModal(el.historyModal));
el.closeHistory2.addEventListener('click', () => closeModal(el.historyModal));
el.historyCopy.addEventListener('click', () => {
copyText(el.historySummary.value);
});
el.historyDelete.addEventListener('click', deleteSelectedHistory);
el.historyLoad.addEventListener('click', loadSelectedHistoryIntoState);
// Theme toggle
el.themeBtn.addEventListener('click', () => {
const cur = root.getAttribute('data-theme') || 'light';
const next = cur === 'dark' ? 'light' : 'dark';
localStorage.setItem(WC_KEYS.theme, next);
applyTheme(next);
toast(next === 'dark' ? 'Dark mode on.' : 'Light mode on.');
});
/* ---------- Initialize UI ---------- */
const init = () => {
// Set default return time and script
el.returnTime.value = addMinutesToTime(Math.round(settings.defaultResetSec / 60));
el.intensity.value = String(state.intensity);
el.intensityLabel.textContent = `${state.intensity} / 10`;
// Default duration options based on quick mode
el.durationSelect.value = '5';
setMode('quick');
syncScript();
syncSuggestionChip();
syncTimerChips();
syncReEntryScript();
// hide breathing on timer until started
el.breathWrap.classList.add('wc-hidden');
// Set settings UI defaults
el.defaultReset.value = String(settings.defaultResetSec);
el.alertMode.value = settings.alertMode;
// Update lucide icons if some were swapped
wcRenderIcons();
};
init();
})();