← Calendar results

Calendar

muse spark 1.2 · basic

Initial view of Calendar

Browser check: Artifact runtime error. This is a technical check, not a quality review.

Reviews & generation details

Reviews

No human review yet. Unreviewed does not mean unsuccessful.

Generation context

Imported historical artifact. Its exact original instructions and lineage are not known.

Generation prompt · exact text unavailable

See the current prompt for reference. It may differ from the instructions used to generate this artifact.

Inspect original source 64,009 bytes · SHA-256 6345df070c84
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendar & Event Planner</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#f8fafc;
  --surface:#ffffff;
  --border:#e2e8f0;
  --border-2:#edf2f7;
  --text:#0f172a;
  --muted:#64748b;
  --muted2:#94a3b8;
  --primary:#2563eb;
  --primary-hover:#1d4ed8;
  --accent:#0ea5e9;
  --radius:12px;
  --shadow:0 1px 3px rgba(0,0,0,.08),0 8px 24px rgba(0,0,0,.06);
  --shadow2:0 8px 32px rgba(0,0,0,.12);
}
body{font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;color:var(--text);background:var(--bg);line-height:1.5}
button{font:inherit}
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:99px}
/* Header */
.header{position:sticky;top:0;z-index:30;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:16px;padding:10px 16px}
.logo{display:flex;align-items:center;gap:10px;font-weight:700;font-size:18px;letter-spacing:-.02em}
.logo-badge{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#2563eb,#0ea5e9);display:grid;place-items:center;color:white;font-size:16px}
.header-mid{flex:1;display:flex;align-items:center;gap:12px;justify-content:center}
.today-btn{border:1px solid var(--border);background:var(--surface);padding:7px 16px;border-radius:999px;font-weight:600;font-size:13px;cursor:pointer;box-shadow:0 1px 2px rgba(0,0,0,.05)}
.today-btn:hover{border-color:#cbd5e1;background:#f8fafc}
.nav-arrows{display:flex;gap:6px}
.icon-btn{width:34px;height:34px;border-radius:999px;border:1px solid var(--border);background:var(--surface);display:grid;place-items:center;cursor:pointer;color:var(--muted)}
.icon-btn:hover{background:#f1f5f9;color:var(--text)}
.title{font-size:20px;font-weight:700;letter-spacing:-.02em;min-width:200px;text-align:center}
.view-switch{display:flex;background:#f1f5f9;padding:4px;border-radius:999px;gap:2px}
.vbtn{padding:7px 16px;border-radius:999px;border:0;background:transparent;font-size:13px;font-weight:600;color:var(--muted);cursor:pointer}
.vbtn.active{background:var(--surface);color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.1)}
.header-right{display:flex;align-items:center;gap:8px}
.settings-btn{width:38px;height:38px;border-radius:10px;border:1px solid var(--border);background:var(--surface);cursor:pointer;display:grid;place-items:center;color:var(--muted)}
/* Layout */
.app{display:flex;max-width:1440px;margin:0 auto;min-height:calc(100vh - 61px)}
.sidebar{width:280px;flex-shrink:0;padding:16px;border-right:1px solid var(--border);background:var(--surface);display:flex;flex-direction:column;gap:16px}
.create-btn{width:100%;background:var(--surface);border:0;border-radius:999px;padding:14px 16px;display:flex;align-items:center;gap:10px;font-weight:600;box-shadow:0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.08);cursor:pointer}
.create-btn span:first-child{width:36px;height:36px;border-radius:999px;background:#2563eb;color:white;display:grid;place-items:center;font-size:18px}
.mini-card{border:1px solid var(--border);border-radius:16px;padding:12px;background:var(--surface)}
.mini-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
.mini-title{font-weight:700;font-size:13px}
.mini-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:2px;text-align:center;font-size:11px}
.mini-dow{color:var(--muted);font-weight:600;padding:4px 0}
.mini-day{aspect-ratio:1;display:grid;place-items:center;border-radius:999px;cursor:pointer;font-size:11px}
.mini-day:hover{background:#f1f5f9}
.mini-day.is-today{background:var(--primary);color:white}
.mini-day.is-other{color:var(--muted2)}
.mini-day.is-selected{outline:2px solid var(--primary);outline-offset:-1px}
.filters{display:flex;flex-direction:column;gap:8px}
.filter-item{display:flex;align-items:center;gap:8px;font-size:13px}
.dot{width:10px;height:10px;border-radius:999px;flex-shrink:0}
.main{flex:1;min-width:0;background:var(--bg);display:flex;flex-direction:column}
.view{flex:1;display:none;padding:0}
.view.active{display:flex;flex-direction:column}
/* Month */
.month-head{display:grid;grid-template-columns:repeat(7,1fr);background:var(--surface);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:2}
.month-head div{padding:10px 12px;font-size:11px;font-weight:700;letter-spacing:.08em;color:var(--muted);text-transform:uppercase}
.month-grid{background:var(--surface);display:grid;grid-template-columns:repeat(7,1fr);grid-template-rows:repeat(6, minmax(118px, 1fr));border-left:1px solid var(--border);border-top:1px solid var(--border);flex:1;transition:opacity .2s}
.cell{border-right:1px solid var(--border);border-bottom:1px solid var(--border);padding:8px 6px 6px;position:relative;background:var(--surface);display:flex;flex-direction:column;gap:4px;overflow:hidden;cursor:pointer}
.cell.dimmed{background:#f8fafc}
.cell.dimmed .cell-num{color:var(--muted2)}
.cell.is-today{background:#eff6ff}
.cell.is-today .cell-num{background:var(--primary);color:white;width:26px;height:26px;display:grid;place-items:center;border-radius:999px}
.cell-num{font-size:12px;font-weight:600;width:26px;height:26px;display:grid;place-items:center;border-radius:999px}
.events-stack{display:flex;flex-direction:column;gap:3px;overflow:hidden}
.chip{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:500;padding:3px 6px;border-radius:6px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border-left:3px solid transparent;line-height:1.2}
.chip:hover{filter:brightness(.97)}
.chip.allday{font-weight:600}
.more{font-size:11px;font-weight:600;color:var(--muted);cursor:pointer;padding:2px 6px}
.more:hover{color:var(--text)}
/* Week */
.week-wrap{flex:1;display:flex;flex-direction:column;background:var(--surface);overflow:hidden}
.week-header{display:grid;grid-template-columns:56px repeat(7,1fr);border-bottom:1px solid var(--border);background:var(--surface);position:sticky;top:0;z-index:2}
.week-header .gutter{border-right:1px solid var(--border)}
.week-day-head{padding:10px 6px;text-align:center;border-right:1px solid var(--border)}
.week-day-head.is-today .wd-num{background:var(--primary);color:white}
.wd-name{font-size:11px;font-weight:700;letter-spacing:.08em;color:var(--muted);text-transform:uppercase}
.wd-num{font-size:18px;font-weight:700;width:34px;height:34px;display:grid;place-items:center;margin:2px auto 0;border-radius:999px}
.wd-date{font-size:11px;color:var(--muted)}
.all-day-row{display:grid;grid-template-columns:56px repeat(7,1fr);border-bottom:1px solid var(--border);background:#f8fafc;min-height:36px}
.all-day-row .label{font-size:11px;font-weight:700;color:var(--muted);padding:10px 6px;border-right:1px solid var(--border)}
.all-day-cell{border-right:1px solid var(--border);padding:4px;display:flex;flex-direction:column;gap:2px}
.week-body{flex:1;overflow:auto;position:relative;display:grid;grid-template-columns:56px repeat(7,1fr)}
.time-col{border-right:1px solid var(--border);background:var(--surface)}
.time-slot{height:48px;border-bottom:1px solid var(--border-2);position:relative}
.time-label{position:absolute;top:-7px;right:6px;font-size:10px;color:var(--muted);background:var(--surface);padding:0 2px}
.day-col{position:relative;border-right:1px solid var(--border)}
.hour-line{position:absolute;left:0;right:0;height:1px;background:var(--border-2)}
.event-block{position:absolute;left:4px;right:4px;border-radius:8px;padding:6px 8px;font-size:11px;font-weight:600;overflow:hidden;cursor:grab;box-shadow:0 1px 3px rgba(0,0,0,.12);border-left:3px solid rgba(0,0,0,.15)}
.event-block:active{cursor:grabbing}
.now-line{position:absolute;left:0;right:0;height:2px;background:#ef4444;z-index:5;pointer-events:none}
.now-line::before{content:"";position:absolute;left:-4px;top:-4px;width:8px;height:8px;background:#ef4444;border-radius:999px}
/* Agenda */
.agenda{padding:16px;max-width:760px;margin:0 auto;width:100%;display:flex;flex-direction:column;gap:18px}
.agenda-group{border:1px solid var(--border);border-radius:16px;background:var(--surface);overflow:hidden}
.agenda-head{padding:12px 16px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--border);background:#f8fafc}
.ag-date{width:44px;height:44px;border-radius:12px;background:var(--primary);color:white;display:flex;flex-direction:column;align-items:center;justify-content:center;line-height:1}
.ag-date b{font-size:16px}
.ag-date span{font-size:10px;letter-spacing:.08em;font-weight:700}
.agenda-list{display:flex;flex-direction:column}
.agenda-item{display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--border-2);cursor:pointer}
.agenda-item:last-child{border:0}
.agenda-item:hover{background:#f8fafc}
.ag-time{font-size:12px;font-weight:700;color:var(--muted);min-width:110px}
.ag-title{font-weight:600;font-size:14px}
.ag-notes{font-size:12px;color:var(--muted)}
.ag-color{width:8px;height:8px;border-radius:999px;flex-shrink:0}
/* Modal */
.overlay{position:fixed;inset:0;background:rgba(15,23,42,.45);backdrop-filter:blur(4px);display:none;align-items:center;justify-content:center;z-index:50;padding:16px}
.overlay.open{display:flex}
.modal{width:min(560px,100%);background:var(--surface);border-radius:20px;box-shadow:var(--shadow2);overflow:hidden;max-height:90vh;display:flex;flex-direction:column}
.modal-head{padding:20px 20px 0;display:flex;align-items:center;justify-content:space-between}
.modal-head h2{font-size:18px;letter-spacing:-.02em}
.close-btn{width:36px;height:36px;border-radius:999px;border:1px solid var(--border);background:var(--surface);cursor:pointer;display:grid;place-items:center}
.modal-body{padding:16px 20px;overflow:auto;display:flex;flex-direction:column;gap:14px}
.field{display:flex;flex-direction:column;gap:6px}
.field label{font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
.input, .select, .textarea{width:100%;border:1px solid var(--border);border-radius:12px;padding:10px 12px;font-size:14px;background:var(--surface);outline:0}
.input:focus, .select:focus, .textarea:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.12)}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.inline-error{font-size:12px;color:#dc2626;display:none}
.inline-error.show{display:block}
.palette{display:flex;gap:8px;flex-wrap:wrap}
.pdot{width:28px;height:28px;border-radius:999px;cursor:pointer;border:2px solid transparent;display:grid;place-items:center}
.pdot.active{border-color:var(--text);box-shadow:0 0 0 2px white inset}
.recurrence-box{border:1px solid var(--border);border-radius:12px;padding:12px;display:flex;flex-direction:column;gap:10px;background:#f8fafc}
.weekday-pills{display:flex;gap:6px;flex-wrap:wrap}
.wpill{width:32px;height:32px;border-radius:999px;border:1px solid var(--border);background:var(--surface);font-size:11px;font-weight:700;cursor:pointer;display:grid;place-items:center}
.wpill.active{background:var(--primary);color:white;border-color:var(--primary)}
.modal-foot{padding:12px 20px 20px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-top:1px solid var(--border)}
.btn{padding:10px 16px;border-radius:999px;border:0;font-weight:700;font-size:13px;cursor:pointer}
.btn-ghost{background:transparent;color:var(--muted);border:1px solid var(--border)}
.btn-danger{background:#fee2e2;color:#b91c1c}
.btn-primary{background:var(--primary);color:white}
.btn-primary:hover{background:var(--primary-hover)}
/* Popover */
.popover{position:fixed;z-index:40;background:var(--surface);border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow2);width:320px;overflow:hidden;display:none}
.popover.open{display:block}
.pop-head{padding:12px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.pop-list{max-height:320px;overflow:auto;display:flex;flex-direction:column}
.pop-item{padding:10px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--border-2);cursor:pointer}
.pop-item:hover{background:#f8fafc}
/* Toast */
.toast{position:fixed;left:50%;bottom:20px;transform:translateX(-50%) translateY(80px);background:#0f172a;color:white;padding:12px 16px;border-radius:999px;display:flex;align-items:center;gap:12px;box-shadow:var(--shadow2);transition:.25s;z-index:60}
.toast.show{transform:translateX(-50%) translateY(0)}
.toast button{background:white;color:#0f172a;border:0;padding:6px 12px;border-radius:999px;font-weight:700;cursor:pointer;font-size:12px}
/* Responsive */
@media (max-width:900px){
  .sidebar{display:none}
  .title{min-width:0;font-size:16px}
  .header-mid{gap:8px}
  .month-grid{grid-template-rows:repeat(6, minmax(86px,1fr))}
}
@media (max-width:640px){
  .row2{grid-template-columns:1fr}
}
</style>
</head>
<body>
<header class="header">
  <div class="logo"><div class="logo-badge">◈</div><span style="display:flex;flex-direction:column;line-height:1"><span>Calendar</span><span style="font-size:11px;color:var(--muted);font-weight:600;letter-spacing:.06em;text-transform:uppercase">Planner</span></span></div>
  <div class="header-mid">
    <button class="today-btn" id="todayBtn">Today</button>
    <div class="nav-arrows">
      <button class="icon-btn" id="prevBtn">‹</button>
      <button class="icon-btn" id="nextBtn">›</button>
    </div>
    <div class="title" id="headerTitle"></div>
  </div>
  <div class="view-switch" id="viewSwitch">
    <button class="vbtn active" data-view="month">Month</button>
    <button class="vbtn" data-view="week">Week</button>
    <button class="vbtn" data-view="agenda">Agenda</button>
  </div>
  <button class="settings-btn" id="settingsBtn" title="Toggle week start">≡</button>
</header>

<div class="app">
  <aside class="sidebar">
    <button class="create-btn" id="createBtn"><span>+</span> Create event</button>
    <div class="mini-card">
      <div class="mini-header"><span class="mini-title" id="miniTitle"></span><span style="display:flex;gap:6px"><button class="icon-btn" id="miniPrev" style="width:26px;height:26px">‹</button><button class="icon-btn" id="miniNext" style="width:26px;height:26px">›</button></span></div>
      <div class="mini-grid" id="miniGrid"></div>
    </div>
    <div class="mini-card">
      <div style="font-weight:700;font-size:13px;margin-bottom:8px">Week start</div>
      <div style="display:flex;gap:8px">
        <button class="btn btn-ghost" id="wsMon" style="flex:1">Monday</button>
        <button class="btn btn-ghost" id="wsSun" style="flex:1">Sunday</button>
      </div>
      <div style="font-size:11px;color:var(--muted);margin-top:8px">Drag events to reschedule. 15-min snap in week view.</div>
    </div>
    <div class="mini-card">
      <div style="font-weight:700;font-size:13px;margin-bottom:6px">Legend</div>
      <div class="filters" id="legend"></div>
      <div style="margin-top:10px;font-size:11px;color:var(--muted)">Monthly on 31st skips short months (e.g. Feb).</div>
    </div>
  </aside>
  <main class="main">
    <div class="view active" id="monthView">
      <div class="month-head" id="monthHead"></div>
      <div class="month-grid" id="monthGrid"></div>
    </div>
    <div class="view" id="weekView">
      <div class="week-wrap">
        <div class="week-header" id="weekHeader"></div>
        <div class="all-day-row" id="allDayRow"></div>
        <div class="week-body" id="weekBody"></div>
      </div>
    </div>
    <div class="view" id="agendaView"><div class="agenda" id="agendaList"></div></div>
  </main>
</div>

<div class="popover" id="dayPopover">
  <div class="pop-head"><b id="popTitle" style="font-size:13px"></b><button class="close-btn" id="popClose" style="width:28px;height:28px">×</button></div>
  <div class="pop-list" id="popList"></div>
</div>

<div class="overlay" id="eventOverlay">
  <div class="modal">
    <div class="modal-head"><h2 id="modalTitle">New event</h2><button class="close-btn" id="modalClose">×</button></div>
    <div class="modal-body">
      <div class="field"><label>Title</label><input class="input" id="fTitle" placeholder="Add title"><span class="inline-error" id="eTitle">Title is required</span></div>
      <div class="row2">
        <div class="field"><label>Date</label><input class="input" id="fDate" type="date"></div>
        <div class="field"><label>Color</label><div class="palette" id="palette"></div></div>
      </div>
      <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600"><input type="checkbox" id="fAllDay"> All-day</label>
      <div class="row2" id="timeRow">
        <div class="field"><label>Start</label><input class="input" id="fStart" type="time" value="09:00"></div>
        <div class="field"><label>End</label><input class="input" id="fEnd" type="time" value="10:00"></div>
      </div>
      <span class="inline-error" id="eTime">End time must be after start time</span>
      <div class="field"><label>Notes</label><textarea class="textarea" id="fNotes" rows="3" placeholder="Optional description"></textarea></div>
      <div class="recurrence-box">
        <div class="field"><label>Recurrence</label>
          <select class="select" id="fRecur">
            <option value="none">Does not repeat</option>
            <option value="daily">Daily</option>
            <option value="weekly">Weekly</option>
            <option value="monthly">Monthly (same day)</option>
            <option value="yearly">Yearly</option>
          </select>
        </div>
        <div id="weeklyPick" style="display:none">
          <div style="font-size:12px;font-weight:700;color:var(--muted);margin-bottom:6px">Repeat on</div>
          <div class="weekday-pills" id="weekdayPills"></div>
        </div>
      </div>
    </div>
    <div class="modal-foot">
      <button class="btn btn-danger" id="deleteBtn" style="display:none">Delete</button>
      <div style="flex:1"></div>
      <button class="btn btn-ghost" id="cancelBtn">Cancel</button>
      <button class="btn btn-primary" id="saveBtn">Save</button>
    </div>
  </div>
</div>

<div class="overlay" id="choiceOverlay">
  <div class="modal" style="width:420px">
    <div class="modal-head"><h2>Edit recurring event</h2><button class="close-btn" id="choiceClose">×</button></div>
    <div class="modal-body">
      <p style="font-size:13px;color:var(--muted)">This event is part of a series. How would you like to apply the change?</p>
      <button class="btn btn-ghost" id="choiceOne" style="width:100%;justify-content:flex-start;display:flex">This event only</button>
      <button class="btn btn-ghost" id="choiceFollowing" style="width:100%;justify-content:flex-start;display:flex">This and following events</button>
      <button class="btn btn-primary" id="choiceAll" style="width:100%">Entire series</button>
    </div>
  </div>
</div>

<div class="toast" id="toast"><span id="toastMsg">Event deleted</span><button id="undoBtn">Undo</button></div>

<script>
// ================= CONFIG =================
const CONFIG = {
  COLORS: [
    {id:'blue',bg:'#dbeafe',border:'#2563eb',dot:'#2563eb'},
    {id:'violet',bg:'#ede9fe',border:'#7c3aed',dot:'#7c3aed'},
    {id:'emerald',bg:'#d1fae5',border:'#059669',dot:'#059669'},
    {id:'amber',bg:'#fef3c7',border:'#d97706',dot:'#d97706'},
    {id:'rose',bg:'#ffe4e6',border:'#e11d48',dot:'#e11d48'},
    {id:'cyan',bg:'#cffafe',border:'#0891b2',dot:'#0891b2'},
  ],
  HOUR_START:6,
  HOUR_END:22,
  SNAP_MINUTES:15,
  WEEK_START_DEFAULT:'monday',
  STORAGE_KEY:'cal.planner.v2'
};

// ================= DATE UTIL (pure, no ms hacks) =================
const DateUtil = {
  isLeapYear(y){ return (y%4===0 && y%100!==0) || (y%400===0); },
  daysInMonth(y,m){ // m 0-11
    const dim=[31, DateUtil.isLeapYear(y)?29:28,31,30,31,30,31,31,30,31,30,31];
    return dim[m];
  },
  formatDate(y,m,d){ // m 0-11
    const mm=String(m+1).padStart(2,'0'), dd=String(d).padStart(2,'0');
    return `${y}-${mm}-${dd}`;
  },
  parseDate(s){
    const [y,mo,da]=s.split('-').map(Number);
    return {y, m:mo-1, d:da};
  },
  toDateObj(y,m,d){ return new Date(y,m,d); },
  fromDate(dt){ return {y:dt.getFullYear(), m:dt.getMonth(), d:dt.getDate()}; },
  addDays(dateStr, n){
    const {y,m,d}=DateUtil.parseDate(dateStr);
    const dt=new Date(y,m,d+n);
    return DateUtil.formatDate(dt.getFullYear(), dt.getMonth(), dt.getDate());
  },
  addMonths(y,m,d, delta){
    // keep day, clamp not used for navigation (use day 1)
    let total=m+delta; let ny=y+Math.floor(total/12); let nm=((total%12)+12)%12;
    // for navigation we use d=1 so no clamp needed, but handle generic
    const dim=DateUtil.daysInMonth(ny,nm);
    const nd=Math.min(d,dim);
    return {y:ny,m:nm,d:nd, str:DateUtil.formatDate(ny,nm,nd)};
  },
  dayOfWeek(y,m,d){ return new Date(y,m,d).getDay(); }, //0 Sun
  compare(a,b){ return a.localeCompare(b); },
  diffDays(a,b){ // b - a in days, iterative but small ranges only; fallback to UTC math without DST issue using noon
    // use UTC noon to avoid DST ms hack issues though we avoid 86400000 per spec for grid math – here only for diff counting in expansion, use iteration for correctness
    let count=0; let cur=a;
    if(cur===b) return 0;
    if(cur<b){
      while(cur<b){ cur=DateUtil.addDays(cur,1); count++; if(count>5000) break; }
      return count;
    } else {
      while(cur>b){ cur=DateUtil.addDays(cur,-1); count--; if(count<-5000) break;}
      return count;
    }
  },
  monthGrid(y,m, weekStart){ // returns 42 cells
    const firstDow=DateUtil.dayOfWeek(y,m,1); //0 Sun
    const startOffset = weekStart==='monday' ? (firstDow===0?6:firstDow-1) : firstDow;
    const daysPrev = startOffset;
    const dim=DateUtil.daysInMonth(y,m);
    const prevM = m===0?11:m-1, prevY=m===0?y-1:y;
    const dimPrev=DateUtil.daysInMonth(prevY,prevM);
    const cells=[];
    for(let i=0;i<42;i++){
      let cy,cm,cd, isCurrent;
      const idx=i - daysPrev;
      if(idx<0){ cy=prevY; cm=prevM; cd=dimPrev+idx+1; isCurrent=false; }
      else if(idx>=dim){ cy= m===11?y+1:y; cm=m===11?0:m+1; cd=idx-dim+1; isCurrent=false; }
      else { cy=y; cm=m; cd=idx+1; isCurrent=true; }
      cells.push({y:cy,m:cm,d:cd,str:DateUtil.formatDate(cy,cm,cd), isCurrent});
    }
    return cells;
  },
  weekRange(dateStr, weekStart){
    const {y,m,d}=DateUtil.parseDate(dateStr);
    const dow=DateUtil.dayOfWeek(y,m,d);
    const offset= weekStart==='monday' ? (dow===0?6:dow-1) : dow;
    const start=DateUtil.addDays(dateStr,-offset);
    const end=DateUtil.addDays(start,6);
    return {start,end};
  },
  isOccurrenceOnDate(master, candidateStr){
    const rec=master.recurrence; if(!rec) return master.date===candidateStr;
    const start=master.date;
    if(candidateStr < start) return false;
    if(rec.until && candidateStr > rec.until) return false;
    if(rec.freq==='daily'){
      const diff=DateUtil.diffDays(start,candidateStr);
      return diff % (rec.interval||1)===0;
    }
    if(rec.freq==='weekly'){
      const weekdays=rec.weekdays||[];
      const {y,m,d}=DateUtil.parseDate(candidateStr);
      const dow=DateUtil.dayOfWeek(y,m,d);
      if(!weekdays.includes(dow)) return false;
      const diff=DateUtil.diffDays(start,candidateStr);
      const weeks=Math.floor(diff/7);
      return weeks % (rec.interval||1)===0;
    }
    if(rec.freq==='monthly'){
      const s=DateUtil.parseDate(start), c=DateUtil.parseDate(candidateStr);
      if(c.d !== s.d) return false; // same day-of-month, skips short months
      const months=(c.y - s.y)*12 + (c.m - s.m);
      if(months <0) return false;
      return months % (rec.interval||1)===0;
    }
    if(rec.freq==='yearly'){
      const s=DateUtil.parseDate(start), c=DateUtil.parseDate(candidateStr);
      if(c.m!==s.m || c.d!==s.d) return false;
      const years=c.y - s.y;
      return years % (rec.interval||1)===0;
    }
    return false;
  }
};

// ================= STORE =================
let state={
  currentDate: new Date(), // Date object for navigation
  view:'month',
  weekStart: localStorage.getItem(CONFIG.STORAGE_KEY+'_ws') || CONFIG.WEEK_START_DEFAULT,
  events: [],
  miniDate: new Date()
};
function loadStore(){
  try{
    const raw=localStorage.getItem(CONFIG.STORAGE_KEY);
    if(raw){ const p=JSON.parse(raw); if(Array.isArray(p.events)) state.events=p.events; if(p.weekStart) state.weekStart=p.weekStart; if(p.view) state.view=p.view; }
  }catch(e){}
  if(state.events.length===0){
    // seed demo
    const todayStr=DateUtil.formatDate(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
    const y=new Date().getFullYear(), m=new Date().getMonth();
    const mk=(o)=>({id:'e'+Math.random().toString(36).slice(2,7), color:'blue', allDay:false, notes:'', recurrence:null, masterId:null, originalDate:null, deleted:false, ...o});
    state.events=[
      mk({title:'Team standup', date:todayStr, startTime:'09:00', endTime:'09:45', color:'blue'}),
      mk({title:'Design review', date:todayStr, startTime:'11:00', endTime:'12:00', color:'violet'}),
      mk({title:'Gym', date:DateUtil.addDays(todayStr,1), startTime:'18:00', endTime:'19:00', color:'emerald'}),
      mk({title:'Monthly report', date:DateUtil.formatDate(y,m,31> DateUtil.daysInMonth(y,m)?DateUtil.daysInMonth(y,m):31), startTime:'14:00', endTime:'15:00', color:'amber', recurrence:{freq:'monthly', interval:1}}),
      mk({title:'Yoga (weekly)', date:DateUtil.addDays(todayStr, - (DateUtil.toDateObj(...Object.values(DateUtil.parseDate(todayStr))).getDay()===1?0:1)), startTime:'07:30', endTime:'08:15', color:'cyan', recurrence:{freq:'weekly', interval:1, weekdays:[1,3,5]}}),
      mk({title:'Lunch with Alex', date:todayStr, startTime:null, endTime:null, color:'rose', allDay:true}),
    ];
    // fix yoga start to Monday
    const {start}=DateUtil.weekRange(todayStr, state.weekStart);
    state.events[4].date=start; // Monday
  }
}
function saveStore(){
  localStorage.setItem(CONFIG.STORAGE_KEY, JSON.stringify({events:state.events, weekStart:state.weekStart, view:state.view}));
  localStorage.setItem(CONFIG.STORAGE_KEY+'_ws', state.weekStart);
}

// ================= HELPERS =================
function colorById(id){ return CONFIG.COLORS.find(c=>c.id===id) || CONFIG.COLORS[0]; }
function todayStr(){ const n=new Date(); return DateUtil.formatDate(n.getFullYear(), n.getMonth(), n.getDate()); }
function fmtHeaderTitle(d){
  return d.toLocaleDateString('en-US',{month:'long', year:'numeric'});
}
function expandForRange(rangeStart, rangeEnd){
  // returns occurrences [{id, master, date, startTime, endTime, allDay, title, color, notes, isException, occurrenceKey, deleted}]
  const masters=state.events.filter(e=>e.recurrence && !e.masterId && !e.deleted);
  const singles=state.events.filter(e=>!e.recurrence && !e.masterId && !e.deleted);
  const exceptions=state.events.filter(e=>e.masterId);
  const excByMaster={};
  exceptions.forEach(ex=>{
    if(!excByMaster[ex.masterId]) excByMaster[ex.masterId]=[];
    excByMaster[ex.masterId].push(ex);
  });
  const result=[];
  // singles directly
  singles.forEach(ev=>{
    if(ev.date>=rangeStart && ev.date<=rangeEnd) result.push({...ev, occurrenceKey: ev.id+'_'+ev.date, isException:false, displayDate:ev.date});
  });
  // masters expansion via brute date iteration
  masters.forEach(master=>{
    const excs=excByMaster[master.id]||[];
    const deletedSet=new Set(excs.filter(e=>e.deleted).map(e=>e.originalDate));
    const modifiedMap=new Map(excs.filter(e=>!e.deleted).map(e=>[e.originalDate,e]));
    let cur=rangeStart;
    while(cur<=rangeEnd){
      if(DateUtil.isOccurrenceOnDate(master, cur)){
        if(deletedSet.has(cur)){
          // skip
        } else if(modifiedMap.has(cur)){
          const ex=modifiedMap.get(cur);
          // ex may have new date different from original; display at ex.date if within range
          // but original date is cur; we will handle ex's new date separately later.
          // For this cur, we display exception at ex.date? If ex moved, cur occurrence replaced.
          // We'll push exception occurrence at its new date (if within range) instead of cur
          // Yet to avoid duplicate, push now at ex.date
          // If ex.date !== cur, we should not push at cur but at ex.date. But brute will also encounter ex.date later as candidate that may not match rule – so we handle moved exceptions separately after loop.
          if(ex.date===cur){
            result.push({...master, ...ex, id:ex.id, occurrenceKey: ex.id+'_'+cur, isException:true, displayDate:cur, title:ex.title||master.title, color:ex.color||master.color});
          } else {
            // suppress original, exception will be added as standalone below if within range
          }
        } else {
          result.push({...master, occurrenceKey: master.id+'_'+cur, isException:false, displayDate:cur, date:cur});
        }
      }
      cur=DateUtil.addDays(cur,1);
    }
    // add moved exceptions where new date within range but original not necessarily in range? Also add those whose new date is in range
    excs.filter(e=>!e.deleted && e.date!==e.originalDate).forEach(ex=>{
      if(ex.date>=rangeStart && ex.date<=rangeEnd){
        // ensure not already added (if original date == new date handled above)
        if(!result.some(r=>r.occurrenceKey===ex.id+'_'+ex.originalDate)){
          result.push({...master, ...ex, id:ex.id, occurrenceKey: ex.id+'_'+ex.date, isException:true, displayDate:ex.date});
        }
      }
    });
  });
  // also exceptions that are not moved but date==original already handled; deleted handled.
  // Also need to include exceptions whose originalDate outside range but new date inside (already handled). And standalone exceptions that were moved? done.
  // Also need to include exceptions for masters that were created via split? They are separate masters.
  // Add non-master exceptions that are orphan? already.
  // Sort
  result.sort((a,b)=>{
    if(a.displayDate!==b.displayDate) return a.displayDate.localeCompare(b.displayDate);
    const at=a.allDay? '00:00': (a.startTime||'00:00'), bt=b.allDay? '00:00': (b.startTime||'00:00');
    return at.localeCompare(bt);
  });
  return result;
}

// ================= RENDER =================
function render(){
  document.querySelectorAll('.vbtn').forEach(b=>b.classList.toggle('active', b.dataset.view===state.view));
  document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));
  document.getElementById(state.view+'View').classList.add('active');
  const titleEl=document.getElementById('headerTitle');
  if(state.view==='month') titleEl.textContent=fmtHeaderTitle(state.currentDate);
  else if(state.view==='week'){ const ws=DateUtil.weekRange(DateUtil.formatDate(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate()), state.weekStart); titleEl.textContent= ws.start.slice(0,7)===ws.end.slice(0,7)? fmtHeaderTitle(state.currentDate) : ws.start+' – '+ws.end; }
  else titleEl.textContent='Agenda';
  updateWeekStartButtons();
  if(state.view==='month') renderMonth();
  if(state.view==='week') renderWeek();
  if(state.view==='agenda') renderAgenda();
  renderMini();
  renderLegend();
}
function updateWeekStartButtons(){
  document.getElementById('wsMon').style.background = state.weekStart==='monday' ? 'var(--primary)' : '';
  document.getElementById('wsMon').style.color = state.weekStart==='monday' ? 'white' : '';
  document.getElementById('wsSun').style.background = state.weekStart==='sunday' ? 'var(--primary)' : '';
  document.getElementById('wsSun').style.color = state.weekStart==='sunday' ? 'white' : '';
}
function renderMonth(){
  const y=state.currentDate.getFullYear(), m=state.currentDate.getMonth();
  const weekNames = state.weekStart==='monday' ? ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  document.getElementById('monthHead').innerHTML=weekNames.map(d=>`<div>${d}</div>`).join('');
  const cells=DateUtil.monthGrid(y,m, state.weekStart);
  const rangeStart=cells[0].str, rangeEnd=cells[cells.length-1].str;
  const occ=expandForRange(rangeStart, rangeEnd);
  const byDate={}; occ.forEach(o=>{ (byDate[o.displayDate]=byDate[o.displayDate]||[]).push(o); });
  const grid=document.getElementById('monthGrid');
  grid.style.opacity='.5'; setTimeout(()=>grid.style.opacity='1', 60);
  grid.innerHTML=cells.map(c=>{
    const isToday=c.str===todayStr();
    const list=byDate[c.str]||[];
    const show=list.slice(0,3);
    const more=list.length>3? `<div class="more" data-more="${c.str}">+${list.length-3} more</div>` : '';
    return `<div class="cell ${c.isCurrent?'':'dimmed'} ${isToday?'is-today':''}" data-date="${c.str}" draggable="false">
      <div class="cell-num">${c.d}</div>
      <div class="events-stack">${show.map(ev=>{
        const col=colorById(ev.color);
        return `<div class="chip" draggable="true" data-occ="${ev.occurrenceKey}" data-id="${ev.id}" style="background:${col.bg};border-left-color:${col.border};color:#0f172a">${ev.allDay?'':(ev.startTime||'')+' '} ${ev.title}</div>`;
      }).join('')}${more}</div>
    </div>`;
  }).join('');
  // drag handlers
  grid.querySelectorAll('.chip').forEach(ch=>{
    ch.addEventListener('dragstart', e=>{
      e.dataTransfer.setData('text/plain', ch.dataset.occ);
      e.dataTransfer.effectAllowed='move';
    });
    ch.addEventListener('click', e=>{ e.stopPropagation(); openEventByOccurrence(ch.dataset.occ); });
  });
  grid.querySelectorAll('.cell').forEach(cell=>{
    cell.addEventListener('click', e=>{
      if(e.target.closest('.chip')||e.target.closest('.more')) return;
      openCreateModal(cell.dataset.date);
    });
    cell.addEventListener('dragover', e=>{ e.preventDefault(); cell.style.outline='2px dashed var(--primary)'; });
    cell.addEventListener('dragleave', ()=> cell.style.outline='');
    cell.addEventListener('drop', e=>{
      e.preventDefault(); cell.style.outline='';
      const occKey=e.dataTransfer.getData('text/plain');
      if(!occKey) return;
      handleDropToDate(occKey, cell.dataset.date);
    });
  });
  grid.querySelectorAll('[data-more]').forEach(b=> b.addEventListener('click', e=>{
    e.stopPropagation(); openDayPopover(b.dataset.more, b);
  }));
}
function renderWeek(){
  const curStr=DateUtil.formatDate(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate());
  const {start,end}=DateUtil.weekRange(curStr, state.weekStart);
  // header
  const header=document.getElementById('weekHeader');
  const body=document.getElementById('weekBody');
  const allDayRow=document.getElementById('allDayRow');
  const days=[]; let d=start; while(d<=end){ days.push(d); d=DateUtil.addDays(d,1); }
  header.innerHTML=`<div class="gutter"></div>`+days.map(ds=>{
    const {y,m,d:day}=DateUtil.parseDate(ds);
    const dow=new Date(y,m,day).toLocaleDateString('en-US',{weekday:'short'});
    const isToday=ds===todayStr();
    return `<div class="week-day-head ${isToday?'is-today':''}"><div class="wd-name">${dow}</div><div class="wd-num">${day}</div><div class="wd-date">${String(m+1).padStart(2,'0')}/${String(day).padStart(2,'0')}</div></div>`;
  }).join('');
  const occ=expandForRange(start,end);
  const allDayEvents=occ.filter(o=>o.allDay);
  const timedEvents=occ.filter(o=>!o.allDay);
  allDayRow.innerHTML=`<div class="label">all-day</div>`+days.map(ds=>{
    const evs=allDayEvents.filter(e=>e.displayDate===ds);
    return `<div class="all-day-cell" data-date="${ds}">${evs.map(ev=>{
      const col=colorById(ev.color);
      return `<div class="chip allday" data-occ="${ev.occurrenceKey}" style="background:${col.bg};border-left-color:${col.border}">${ev.title}</div>`;
    }).join('')}</div>`;
  }).join('');
  // body grid
  const hours=[]; for(let h=CONFIG.HOUR_START; h<=CONFIG.HOUR_END; h++) hours.push(h);
  body.innerHTML=`
    <div class="time-col">${hours.map(h=>`<div class="time-slot"><span class="time-label">${String(h).padStart(2,'0')}:00</span></div>`).join('')}</div>
    ${days.map(ds=>`<div class="day-col" data-date="${ds}" style="position:relative">${hours.map(()=>`<div class="hour-line" style="top:48px"></div>`).join('')}${hours.map(h=>`<div class="time-slot" data-hour="${h}"></div>`).join('')}</div>`).join('')}
  `;
  // fix hour lines positions via css: compute top per slot
  body.querySelectorAll('.day-col').forEach(col=>{
    col.querySelectorAll('.hour-line').forEach((el,i)=> el.style.top=(i*48+48)+'px');
  });
  // place timed events
  const dayCols=body.querySelectorAll('.day-col');
  const colMap={}; days.forEach((ds,i)=> colMap[ds]=dayCols[i]);
  timedEvents.forEach(ev=>{
    const col=colMap[ev.displayDate]; if(!col) return;
    const [sh,sm]= (ev.startTime||'09:00').split(':').map(Number);
    const [eh,em]= (ev.endTime||'10:00').split(':').map(Number);
    const startMin=sh*60+sm, endMin=eh*60+em;
    const top = ((startMin - CONFIG.HOUR_START*60)/60)*48;
    const height = Math.max(22, ((endMin - startMin)/60)*48);
    const colc=colorById(ev.color);
    const el=document.createElement('div');
    el.className='event-block';
    el.dataset.occ=ev.occurrenceKey;
    el.style.top=top+'px'; el.style.height=height+'px'; el.style.background=colc.bg; el.style.borderLeftColor=colc.border;
    el.draggable=true;
    el.innerHTML=`<div style="font-size:12px;line-height:1.1">${ev.title}</div><div style="font-size:10px;opacity:.7">${ev.startTime}–${ev.endTime}</div>`;
    el.addEventListener('click', ()=> openEventByOccurrence(ev.occurrenceKey));
    el.addEventListener('dragstart', e=>{ e.dataTransfer.setData('text/plain', ev.occurrenceKey); });
    col.appendChild(el);
  });
  // now line
  if(days.includes(todayStr())){
    const now=new Date();
    const mins=now.getHours()*60+now.getMinutes();
    if(mins>=CONFIG.HOUR_START*60 && mins<=CONFIG.HOUR_END*60){
      const top=((mins - CONFIG.HOUR_START*60)/60)*48;
      const col=colMap[todayStr()];
      if(col){ const line=document.createElement('div'); line.className='now-line'; line.style.top=top+'px'; col.appendChild(line); }
    }
  }
  // week drag to change time
  body.querySelectorAll('.day-col').forEach(col=>{
    col.addEventListener('dragover', e=>{ e.preventDefault(); });
    col.addEventListener('drop', e=>{
      e.preventDefault();
      const occKey=e.dataTransfer.getData('text/plain'); if(!occKey) return;
      const rect=col.getBoundingClientRect();
      const y=e.clientY - rect.top;
      let mins = Math.round((y/48)*60 + CONFIG.HOUR_START*60);
      // snap 15
      mins=Math.round(mins/CONFIG.SNAP_MINUTES)*CONFIG.SNAP_MINUTES;
      mins=Math.max(CONFIG.HOUR_START*60, Math.min(CONFIG.HOUR_END*60 -15, mins));
      const hh=String(Math.floor(mins/60)).padStart(2,'0'), mm=String(mins%60).padStart(2,'0');
      handleWeekDrop(occKey, col.dataset.date, hh+':'+mm);
    });
    // click empty to create
    col.addEventListener('click', e=>{
      if(e.target!==col && !e.target.classList.contains('time-slot')) return;
      const rect=col.getBoundingClientRect(); const y=e.clientY-rect.top;
      let mins=Math.round((y/48)*60 + CONFIG.HOUR_START*60); mins=Math.round(mins/15)*15;
      const hh=String(Math.floor(mins/60)).padStart(2,'0'), mm=String(mins%60).padStart(2,'0');
      openCreateModal(col.dataset.date, hh+':'+mm);
    });
  });
  allDayRow.querySelectorAll('.chip').forEach(ch=> ch.addEventListener('click', ()=> openEventByOccurrence(ch.dataset.occ)));
}
function renderAgenda(){
  const start=todayStr();
  const end=DateUtil.addDays(start, 60);
  const occ=expandForRange(start,end);
  const byDate={}; occ.forEach(o=>{ (byDate[o.displayDate]=byDate[o.displayDate]||[]).push(o); });
  const container=document.getElementById('agendaList');
  if(occ.length===0){ container.innerHTML=`<div style="text-align:center;color:var(--muted);padding:40px">No upcoming events</div>`; return; }
  container.innerHTML=Object.keys(byDate).sort().map(ds=>{
    const {y,m,d}=DateUtil.parseDate(ds);
    const dt=new Date(y,m,d);
    const w=dt.toLocaleDateString('en-US',{weekday:'long'});
    return `<div class="agenda-group">
      <div class="agenda-head"><div class="ag-date"><b>${d}</b><span>${dt.toLocaleDateString('en-US',{month:'short'}).toUpperCase()}</span></div><div><div style="font-weight:700">${w}</div><div style="font-size:12px;color:var(--muted)">${ds}</div></div></div>
      <div class="agenda-list">${byDate[ds].map(ev=>{
        const col=colorById(ev.color);
        return `<div class="agenda-item" data-occ="${ev.occurrenceKey}"><span class="ag-color" style="background:${col.dot}"></span><span class="ag-time">${ev.allDay?'All day': ev.startTime+' – '+ev.endTime}</span><div style="flex:1"><div class="ag-title">${ev.title}</div>${ev.notes?`<div class="ag-notes">${ev.notes}</div>`:''}</div></div>`;
      }).join('')}</div>
    </div>`;
  }).join('');
  container.querySelectorAll('.agenda-item').forEach(el=> el.addEventListener('click', ()=> openEventByOccurrence(el.dataset.occ)));
}
function renderMini(){
  const y=state.miniDate.getFullYear(), m=state.miniDate.getMonth();
  document.getElementById('miniTitle').textContent= new Date(y,m,1).toLocaleDateString('en-US',{month:'long', year:'numeric'});
  const weekNames = state.weekStart==='monday'? ['M','T','W','T','F','S','S'] : ['S','M','T','W','T','F','S'];
  const grid=document.getElementById('miniGrid');
  const cells=DateUtil.monthGrid(y,m, state.weekStart);
  const curStr=DateUtil.formatDate(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate());
  const tStr=todayStr();
  let html=weekNames.map(w=>`<div class="mini-dow">${w}</div>`).join('');
  html+=cells.map(c=>{
    const cls=['mini-day'];
    if(!c.isCurrent) cls.push('is-other');
    if(c.str===tStr) cls.push('is-today');
    if(c.str===curStr) cls.push('is-selected');
    return `<div class="${cls.join(' ')}" data-date="${c.str}">${c.d}</div>`;
  }).join('');
  grid.innerHTML=html;
  grid.querySelectorAll('.mini-day').forEach(el=> el.addEventListener('click', ()=>{
    const {y,m,d}=DateUtil.parseDate(el.dataset.date);
    state.currentDate=new Date(y,m,d); render();
  }));
}
function renderLegend(){
  const el=document.getElementById('legend');
  el.innerHTML=CONFIG.COLORS.map(c=>`<label class="filter-item"><span class="dot" style="background:${c.dot}"></span>${c.id}</label>`).join('');
}

// ================= MODAL LOGIC =================
let editing=null; // {mode:'create'|'edit', occurrenceKey, masterId, originalDate, isRecurringMaster}
function openCreateModal(dateStr, startTime){
  editing={mode:'create', date:dateStr};
  document.getElementById('modalTitle').textContent='New event';
  document.getElementById('fTitle').value=''; document.getElementById('fDate').value=dateStr;
  document.getElementById('fAllDay').checked=false; document.getElementById('fStart').value=startTime||'09:00'; document.getElementById('fEnd').value='10:00';
  document.getElementById('fNotes').value=''; document.getElementById('fRecur').value='none'; document.getElementById('weeklyPick').style.display='none';
  weekdaysSelected=new Set([1]); renderWeekdayPills(); setPalette('blue'); document.getElementById('deleteBtn').style.display='none';
  clearErrors(); toggleTimeRow();
  document.getElementById('eventOverlay').classList.add('open');
}
let weekdaysSelected=new Set([1]);
function renderWeekdayPills(){
  const names=['S','M','T','W','T','F','S'];
  const cont=document.getElementById('weekdayPills');
  cont.innerHTML=names.map((n,i)=>`<button class="wpill ${weekdaysSelected.has(i)?'active':''}" data-d="${i}">${n}</button>`).join('');
  cont.querySelectorAll('.wpill').forEach(b=> b.addEventListener('click', ()=>{
    const d=Number(b.dataset.d);
    if(weekdaysSelected.has(d)) weekdaysSelected.delete(d); else weekdaysSelected.add(d);
    renderWeekdayPills();
  }));
}
function setPalette(id){
  document.querySelectorAll('.pdot').forEach(p=>p.classList.toggle('active', p.dataset.c===id));
  document.getElementById('palette').dataset.value=id;
}
function openEventByOccurrence(occKey){
  // find occurrence in expanded range around that date
  const parts=occKey.split('_'); const masterId=parts[0]; const date=parts.slice(1).join('_');
  // locate master/event
  const master=state.events.find(e=>e.id===masterId) || state.events.find(e=>e.occurrenceKey===occKey);
  // find actual stored event for this occurrence: could be exception
  let stored = state.events.find(e=> e.masterId===masterId && (e.originalDate===date || e.date===date)) || master;
  // But occurrenceKey may be exception id
  const exByOcc=state.events.find(e=>e.id===parts[0] && e.masterId);
  if(exByOcc) stored=exByOcc;
  // Determine if this occurrence belongs to recurring series
  const actualMaster = stored.masterId ? state.events.find(e=>e.id===stored.masterId) : stored;
  const isRecurring = actualMaster && actualMaster.recurrence;
  editing={mode:'edit', occurrenceKey:occKey, stored, actualMaster, originalDate: stored.masterId? stored.originalDate : (actualMaster? actualMaster.date : stored.date), displayDate: date, masterId: actualMaster? actualMaster.id : stored.id, isRecurring: !!isRecurring};
  // fill modal
  document.getElementById('modalTitle').textContent='Edit event';
  document.getElementById('fTitle').value=stored.title||actualMaster.title;
  const dispDate = stored.masterId ? stored.date : date;
  document.getElementById('fDate').value=dispDate;
  document.getElementById('fAllDay').checked= stored.allDay ?? actualMaster.allDay ?? false;
  document.getElementById('fStart').value= stored.startTime || actualMaster.startTime || '09:00';
  document.getElementById('fEnd').value= stored.endTime || actualMaster.endTime || '10:00';
  document.getElementById('fNotes').value= stored.notes || actualMaster.notes || '';
  const col= stored.color || actualMaster.color || 'blue'; setPalette(col);
  if(isRecurring){
    document.getElementById('fRecur').value=actualMaster.recurrence.freq;
    weekdaysSelected=new Set(actualMaster.recurrence.weekdays||[1]); renderWeekdayPills();
    document.getElementById('weeklyPick').style.display= actualMaster.recurrence.freq==='weekly'?'block':'none';
  } else {
    document.getElementById('fRecur').value='none'; document.getElementById('weeklyPick').style.display='none';
  }
  document.getElementById('deleteBtn').style.display='inline-block';
  clearErrors(); toggleTimeRow();
  document.getElementById('eventOverlay').classList.add('open');
}
function toggleTimeRow(){
  document.getElementById('timeRow').style.opacity=document.getElementById('fAllDay').checked?'0.4':'1';
  document.getElementById('timeRow').style.pointerEvents=document.getElementById('fAllDay').checked?'none':'auto';
}
function clearErrors(){
  document.getElementById('eTitle').classList.remove('show');
  document.getElementById('eTime').classList.remove('show');
  document.getElementById('fTitle').style.borderColor='';
}
function validate(){
  let ok=true;
  if(!document.getElementById('fTitle').value.trim()){ document.getElementById('eTitle').classList.add('show'); document.getElementById('fTitle').style.borderColor='#dc2626'; ok=false; }
  if(!document.getElementById('fAllDay').checked){
    const s=document.getElementById('fStart').value, e=document.getElementById('fEnd').value;
    if(s>=e){ document.getElementById('eTime').classList.add('show'); ok=false; }
  }
  if(document.getElementById('fRecur').value==='weekly' && weekdaysSelected.size===0){ alert('Choose at least one weekday'); ok=false;}
  return ok;
}
function closeModal(){ document.getElementById('eventOverlay').classList.remove('open'); editing=null; }

// Drag handlers
function handleDropToDate(occKey, newDateStr){
  const parts=occKey.split('_'); const masterId=parts[0]; const origDate=parts.slice(1).join('_');
  const master=state.events.find(e=>e.id===masterId);
  const isRecurring = master && master.recurrence;
  if(!isRecurring){
    const ev=state.events.find(e=>e.id===masterId);
    if(ev){ ev.date=newDateStr; saveStore(); render(); showToast('Moved to '+newDateStr); }
    return;
  }
  // recurring: create exception moved
  const existing=state.events.find(e=>e.masterId===masterId && e.originalDate===origDate && !e.deleted);
  if(existing){
    existing.date=newDateStr; // move again
  } else {
    // create exception
    const ex={ id:'e'+Math.random().toString(36).slice(2,7), masterId, originalDate:origDate, date:newDateStr, title:master.title, startTime:master.startTime, endTime:master.endTime, allDay:master.allDay, color:master.color, notes:master.notes, deleted:false };
    state.events.push(ex);
  }
  saveStore(); render();
  // assert
  console.assert(state.events.some(e=>e.masterId===masterId && e.date===newDateStr), 'drag date stored correctly');
}
function handleWeekDrop(occKey, newDateStr, newStartTime){
  const parts=occKey.split('_'); const masterId=parts[0]; const origDate=parts.slice(1).join('_');
  const master=state.events.find(e=>e.id===masterId);
  const isRecurring = master && master.recurrence;
  // compute new end = start + duration (default 60m)
  const origEv = state.events.find(e=>e.id===masterId) || master;
  let duration=60;
  if(origEv && origEv.startTime && origEv.endTime){
    const [sh,sm]=origEv.startTime.split(':').map(Number), [eh,em]=origEv.endTime.split(':').map(Number);
    duration=(eh*60+em)-(sh*60+sm);
  }
  const [nh,nm]=newStartTime.split(':').map(Number);
  let endMins=nh*60+nm+duration; if(endMins> CONFIG.HOUR_END*60) endMins=CONFIG.HOUR_END*60;
  const endStr=String(Math.floor(endMins/60)).padStart(2,'0')+':'+String(endMins%60).padStart(2,'0');
  if(!isRecurring){
    const ev=state.events.find(e=>e.id===masterId);
    ev.date=newDateStr; ev.startTime=newStartTime; ev.endTime=endStr;
    saveStore(); render(); return;
  }
  const existing=state.events.find(e=>e.masterId===masterId && e.originalDate===origDate && !e.deleted);
  if(existing){
    existing.date=newDateStr; existing.startTime=newStartTime; existing.endTime=endStr;
  } else {
    const ex={ id:'e'+Math.random().toString(36).slice(2,7), masterId, originalDate:origDate, date:newDateStr, title:master.title, startTime:newStartTime, endTime:endStr, allDay:false, color:master.color, notes:master.notes, deleted:false };
    state.events.push(ex);
  }
  saveStore(); render();
}

// Choice handling for recurring edit/delete
let pendingAction=null; // {type:'save'|'delete', data}
function showChoice(action){ pendingAction=action; document.getElementById('choiceOverlay').classList.add('open'); }
function hideChoice(){ document.getElementById('choiceOverlay').classList.remove('open'); pendingAction=null; }

function applySave(choice){
  const title=document.getElementById('fTitle').value.trim();
  const date=document.getElementById('fDate').value;
  const allDay=document.getElementById('fAllDay').checked;
  const startTime=document.getElementById('fStart').value;
  const endTime=document.getElementById('fEnd').value;
  const notes=document.getElementById('fNotes').value;
  const color=document.getElementById('palette').dataset.value;
  const recurVal=document.getElementById('fRecur').value;
  const {actualMaster, originalDate, displayDate}=editing;
  if(choice==='one'){
    // create exception at originalDate with new data and date = new date input
    const ex={ id:'e'+Math.random().toString(36).slice(2,7), masterId:actualMaster.id, originalDate: originalDate, date:date, title, startTime: allDay?null:startTime, endTime: allDay?null:endTime, allDay, color, notes, deleted:false };
    state.events.push(ex);
  } else if(choice==='following'){
    // split series: truncate original until day before selected occurrence, create new master starting at new date
    const before=DateUtil.addDays(displayDate, -1);
    actualMaster.recurrence.until=before;
    const newMaster={ id:'e'+Math.random().toString(36).slice(2,7), title, date:date, startTime: allDay?null:startTime, endTime: allDay?null:endTime, allDay, color, notes, recurrence: recurVal==='none'?null: {freq:recurVal, interval:1, weekdays: recurVal==='weekly'? [...weekdaysSelected]:undefined}, masterId:null, originalDate:null, deleted:false};
    state.events.push(newMaster);
  } else if(choice==='all'){
    actualMaster.title=title; actualMaster.date=date; actualMaster.allDay=allDay; actualMaster.startTime=allDay?null:startTime; actualMaster.endTime=allDay?null:endTime; actualMaster.notes=notes; actualMaster.color=color;
    if(recurVal==='none') actualMaster.recurrence=null;
    else actualMaster.recurrence={freq:recurVal, interval:1, weekdays: recurVal==='weekly'? [...weekdaysSelected]:undefined};
    // remove exceptions for this master? keep them but they will be reapplied; for "entire series" we should delete exceptions
    state.events = state.events.filter(e=> e.masterId!==actualMaster.id);
  }
  saveStore(); render(); closeModal(); hideChoice();
}
function applyDelete(choice){
  const {actualMaster, originalDate, stored}=editing;
  if(choice==='one'){
    // mark deleted exception or delete exception if already exception
    if(stored.masterId){
      // deleting an exception instance -> mark deleted? Actually exception itself is the instance, delete it fully and add deleted marker?
      // If stored is exception, replace with deleted marker
      stored.deleted=true;
    } else {
      state.events.push({id:'e'+Math.random().toString(36).slice(2,7), masterId:actualMaster.id, originalDate, date:originalDate, deleted:true, title:'', color:'blue'});
    }
  } else if(choice==='following'){
    actualMaster.recurrence.until=DateUtil.addDays(editing.displayDate,-1);
    // delete any exceptions after
    state.events = state.events.filter(e=> !(e.masterId===actualMaster.id && e.originalDate >= editing.displayDate));
  } else if(choice==='all'){
    // delete master and all exceptions
    const mid=actualMaster.id;
    state.events = state.events.filter(e=> e.id!==mid && e.masterId!==mid);
  }
  saveStore(); render(); closeModal(); hideChoice();
  showToast('Event deleted', true);
}

// Toast undo
let lastDeletedSnapshot=null;
function showToast(msg, isDelete){
  document.getElementById('toastMsg').textContent=msg;
  document.getElementById('toast').classList.add('show');
  setTimeout(()=> document.getElementById('toast').classList.remove('show'), 3000);
}
document.getElementById('undoBtn').addEventListener('click', ()=>{
  if(lastDeletedSnapshot){ state.events=lastDeletedSnapshot; saveStore(); render(); document.getElementById('toast').classList.remove('show'); }
});

// Popover
function openDayPopover(dateStr, anchor){
  const pop=document.getElementById('dayPopover');
  const occ=expandForRange(dateStr,dateStr);
  document.getElementById('popTitle').textContent=new Date(DateUtil.parseDate(dateStr).y, DateUtil.parseDate(dateStr).m, DateUtil.parseDate(dateStr).d).toLocaleDateString('en-US',{weekday:'long', month:'long', day:'numeric'});
  document.getElementById('popList').innerHTML=occ.map(ev=>{
    const col=colorById(ev.color);
    return `<div class="pop-item" data-occ="${ev.occurrenceKey}"><span class="dot" style="background:${col.dot}"></span><div style="flex:1"><div style="font-weight:600;font-size:13px">${ev.title}</div><div style="font-size:11px;color:var(--muted)">${ev.allDay?'All day':ev.startTime+' – '+ev.endTime}</div></div></div>`;
  }).join('') + `<div style="padding:10px"><button class="btn btn-primary" style="width:100%" id="popAdd">+ Add event ${dateStr}</button></div>`;
  pop.style.display='block'; pop.classList.add('open');
  const rect=anchor.getBoundingClientRect();
  pop.style.left=Math.min(window.innerWidth-340, rect.left)+'px';
  pop.style.top=(rect.bottom+8)+'px';
  pop.querySelectorAll('.pop-item').forEach(el=> el.addEventListener('click', ()=>{ pop.classList.remove('open'); openEventByOccurrence(el.dataset.occ); }));
  document.getElementById('popAdd').addEventListener('click', ()=>{ pop.classList.remove('open'); openCreateModal(dateStr); });
}
document.getElementById('popClose').addEventListener('click', ()=> document.getElementById('dayPopover').classList.remove('open'));
document.addEventListener('click', e=>{
  if(!e.target.closest('#dayPopover') && !e.target.closest('[data-more]')) document.getElementById('dayPopover').classList.remove('open');
});

// Palette build
(function buildPalette(){
  const p=document.getElementById('palette');
  p.innerHTML=CONFIG.COLORS.map(c=>`<div class="pdot" data-c="${c.id}" style="background:${c.bg};border-color:${c.border}"><span style="width:8px;height:8px;background:${c.dot};border-radius:999px;display:block"></span></div>`).join('');
  p.querySelectorAll('.pdot').forEach(d=> d.addEventListener('click', ()=> setPalette(d.dataset.c)));
  setPalette('blue');
})();

// Events wiring
document.getElementById('todayBtn').addEventListener('click', ()=>{ state.currentDate=new Date(); state.miniDate=new Date(); render(); });
document.getElementById('prevBtn').addEventListener('click', ()=>{
  if(state.view==='month'){ const y=state.currentDate.getFullYear(), m=state.currentDate.getMonth(); const r=DateUtil.addMonths(y,m,1,-1); state.currentDate=new Date(r.y,r.m,1); }
  else if(state.view==='week'){ const s=DateUtil.formatDate(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate()); state.currentDate=DateUtil.toDateObj(...Object.values(DateUtil.parseDate(DateUtil.addDays(s,-7)))); }
  else { state.currentDate=new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate()+7); }
  render();
});
document.getElementById('nextBtn').addEventListener('click', ()=>{
  if(state.view==='month'){ const y=state.currentDate.getFullYear(), m=state.currentDate.getMonth(); const r=DateUtil.addMonths(y,m,1,1); state.currentDate=new Date(r.y,r.m,1); }
  else if(state.view==='week'){ const s=DateUtil.formatDate(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate()); state.currentDate=DateUtil.toDateObj(...Object.values(DateUtil.parseDate(DateUtil.addDays(s,7)))); }
  else { state.currentDate=new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), state.currentDate.getDate()+7); }
  render();
});
document.getElementById('viewSwitch').addEventListener('click', e=>{
  if(e.target.dataset.view){ state.view=e.target.dataset.view; saveStore(); render(); }
});
document.getElementById('settingsBtn').addEventListener('click', ()=>{ state.weekStart=state.weekStart==='monday'?'sunday':'monday'; saveStore(); render(); });
document.getElementById('wsMon').addEventListener('click', ()=>{ state.weekStart='monday'; saveStore(); render(); });
document.getElementById('wsSun').addEventListener('click', ()=>{ state.weekStart='sunday'; saveStore(); render(); });
document.getElementById('miniPrev').addEventListener('click', ()=>{ const y=state.miniDate.getFullYear(), m=state.miniDate.getMonth(); const r=DateUtil.addMonths(y,m,1,-1); state.miniDate=new Date(r.y,r.m,1); renderMini(); });
document.getElementById('miniNext').addEventListener('click', ()=>{ const y=state.miniDate.getFullYear(), m=state.miniDate.getMonth(); const r=DateUtil.addMonths(y,m,1,1); state.miniDate=new Date(r.y,r.m,1); renderMini(); });
document.getElementById('createBtn').addEventListener('click', ()=> openCreateModal(todayStr()));
document.getElementById('modalClose').addEventListener('click', closeModal);
document.getElementById('cancelBtn').addEventListener('click', closeModal);
document.getElementById('eventOverlay').addEventListener('click', e=>{ if(e.target===document.getElementById('eventOverlay')) closeModal(); });
document.getElementById('fAllDay').addEventListener('change', toggleTimeRow);
document.getElementById('fRecur').addEventListener('change', ()=>{ document.getElementById('weeklyPick').style.display=document.getElementById('fRecur').value==='weekly'?'block':'none'; });

document.getElementById('saveBtn').addEventListener('click', ()=>{
  if(!validate()) return;
  if(editing.mode==='create'){
    const title=document.getElementById('fTitle').value.trim();
    const date=document.getElementById('fDate').value;
    const allDay=document.getElementById('fAllDay').checked;
    const startTime=document.getElementById('fStart').value;
    const endTime=document.getElementById('fEnd').value;
    const notes=document.getElementById('fNotes').value;
    const color=document.getElementById('palette').dataset.value;
    const recurVal=document.getElementById('fRecur').value;
    const ev={id:'e'+Math.random().toString(36).slice(2,7), title, date, allDay, startTime: allDay?null:startTime, endTime: allDay?null:endTime, notes, color, recurrence: recurVal==='none'?null:{freq:recurVal, interval:1, weekdays: recurVal==='weekly'? [...weekdaysSelected]:undefined}, masterId:null, originalDate:null, deleted:false};
    state.events.push(ev); saveStore(); render(); closeModal();
  } else {
    if(editing.isRecurring){
      showChoice({type:'save'});
    } else {
      const title=document.getElementById('fTitle').value.trim();
      const date=document.getElementById('fDate').value;
      const allDay=document.getElementById('fAllDay').checked;
      const startTime=document.getElementById('fStart').value;
      const endTime=document.getElementById('fEnd').value;
      const notes=document.getElementById('fNotes').value;
      const color=document.getElementById('palette').dataset.value;
      const ev=state.events.find(e=>e.id===editing.stored.id);
      ev.title=title; ev.date=date; ev.allDay=allDay; ev.startTime=allDay?null:startTime; ev.endTime=allDay?null:endTime; ev.notes=notes; ev.color=color;
      const recurVal=document.getElementById('fRecur').value;
      ev.recurrence = recurVal==='none'? null : {freq:recurVal, interval:1, weekdays: recurVal==='weekly'? [...weekdaysSelected]:undefined};
      saveStore(); render(); closeModal();
    }
  }
});
document.getElementById('deleteBtn').addEventListener('click', ()=>{
  lastDeletedSnapshot=JSON.parse(JSON.stringify(state.events));
  if(editing.isRecurring){
    showChoice({type:'delete'});
  } else {
    if(!confirm('Delete this event?')) return;
    state.events = state.events.filter(e=> e.id!==editing.stored.id);
    saveStore(); render(); closeModal(); showToast('Event deleted');
  }
});
document.getElementById('choiceClose').addEventListener('click', hideChoice);
document.getElementById('choiceOverlay').addEventListener('click', e=>{ if(e.target===document.getElementById('choiceOverlay')) hideChoice(); });
document.getElementById('choiceOne').addEventListener('click', ()=>{ if(pendingAction?.type==='save') applySave('one'); else applyDelete('one'); });
document.getElementById('choiceFollowing').addEventListener('click', ()=>{ if(pendingAction?.type==='save') applySave('following'); else applyDelete('following'); });
document.getElementById('choiceAll').addEventListener('click', ()=>{ if(pendingAction?.type==='save') applySave('all'); else applyDelete('all'); });

// Self-check helpers exposed for probe
window.DateUtil=DateUtil;
window._state=state;

// Init
loadStore();
render();
renderWeekdayPills();
// Verify known date alignment (2026-01-01 Thursday)
console.assert(DateUtil.dayOfWeek(2026,0,1)===4, '2026-01-01 should be Thursday (4)');
console.assert(DateUtil.daysInMonth(2024,1)===29, 'Feb 2024 29 days');
console.assert(DateUtil.daysInMonth(2025,1)===28, 'Feb 2025 28 days');
console.assert(DateUtil.daysInMonth(2100,1)===28, 'Feb 2100 28 days century rule');
</script>
</body>
</html>
<!-- agent-meta {"model":"meta/muse-spark-1.2","provider":"openrouter","persona":"basic","sessionId":"c0a5e784-f3ab-4220-8b86-2e15ba394448","tokensIn":1122,"tokensOut":20096,"tokensTotal":21218,"cost":0.0866158,"turns":1,"toolCalls":0,"failedToolCalls":0,"timestamp":"2026-08-06T15:34:03.513Z"} -->