/* Rank Lyx — Content Calendar (V1 layout)
   First visual layout + dummy data only. No backend persistence yet, but with
   tab filtering and state-based drag-and-drop. Rendered inside the existing app shell when the Calendar
   nav item is active. Components: CalendarHeader, CalendarTabs, CalendarToolbar,
   WeekCalendarGrid, CalendarCard, ContentModal.
   Event mutations go through the EVENT DATA LAYER helpers (create/update/
   delete/move) so they're easy to swap for Supabase calls later.
   Visual structure follows the provided calendar reference. */

const { useState: useCalState, useEffect: useCalEffect, useRef: useCalRef } = React;
const CalMutationContext = React.createContext({ canMutate: false, allows: () => false });

/* ------------------------------------------------------------------ */
/* Scoped styles — injected once. All classes are `cal-` prefixed. */
const CAL_CSS = `
.cal-page button:disabled { opacity: .5; cursor: not-allowed; }
.cal-page[data-calendar-mutable="false"] .cal-card { cursor: pointer; touch-action: auto; }
.cal-page[data-calendar-mutable="false"] .cal-daycol,
.cal-page[data-calendar-mutable="false"] .cal-mcell { cursor: default; }
.cal-page { background: #fff; }
.cal-inner-wrap { margin: 0; }

/* Subtle, polished scrollbars */
.cal-page { scrollbar-width: thin; scrollbar-color: rgba(10,13,15,0.14) transparent; }
.cal-page::-webkit-scrollbar { width: 8px; height: 8px; }
.cal-page::-webkit-scrollbar-track { background: transparent; }
.cal-page::-webkit-scrollbar-thumb { background: rgba(10,13,15,0.13); border-radius: 8px; border: 2px solid #fff; background-clip: padding-box; }
.cal-page::-webkit-scrollbar-thumb:hover { background: rgba(10,13,15,0.22); border: 2px solid #fff; background-clip: padding-box; }

/* ---- Header ---- */
.cal-hd { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; margin-bottom: 28px; }
.cal-hd__title { font-size: 26px; font-weight: 700; letter-spacing: -0.025em; color: var(--rl-fg); margin: 0 0 4px; }
.cal-hd__sub { font-size: 13.5px; color: var(--rl-fg-3); margin: 0; }

/* ---- Tabs (row 1, tabs only) ---- */
.cal-tabs { display: flex; align-items: center; gap: 2px; border-bottom: 1px solid var(--rl-border); margin-bottom: 22px; overflow-x: auto; scrollbar-width: none; }
.cal-tabs::-webkit-scrollbar { display: none; }
.cal-tab { position: relative; display: inline-flex; align-items: center; gap: 7px; padding: 11px 12px 13px; font-size: 13.5px; font-weight: 550; color: var(--rl-fg-3); background: none; border: none; cursor: pointer; white-space: nowrap; transition: color 120ms var(--rl-ease); }
.cal-tab i, .cal-tab svg { width: 21px; height: 21px; }
.cal-tab:hover { color: var(--rl-fg-2); }
.cal-tab--active { color: var(--rl-fg); font-weight: 650; }
.cal-tab--active::after { content: ""; position: absolute; left: 4px; right: 4px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--rl-fg); }

.cal-search { position: relative; display: inline-flex; align-items: center; }
.cal-search i, .cal-search svg { position: absolute; left: 11px; width: 21px; height: 21px; color: var(--rl-fg-4); pointer-events: none; }
.cal-search input { height: 34px; width: 180px; padding: 0 12px 0 39px; font-family: inherit; font-size: 13px; color: var(--rl-fg); border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; outline: none; transition: all 120ms var(--rl-ease); }
.cal-search input::placeholder { color: var(--rl-fg-4); }
.cal-search input:focus { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); width: 220px; }

.cal-icbtn { height: 34px; min-width: 34px; padding: 0 11px; border-radius: 9px; border: 1px solid var(--rl-border); background: #fff; color: var(--rl-fg-2); display: inline-flex; align-items: center; gap: 7px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 120ms var(--rl-ease); }
.cal-icbtn:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-icbtn i { width: 16px; height: 16px; }
.cal-filter-wrap .cal-icbtn i, .cal-filter-wrap .cal-icbtn svg { width: 21px; height: 21px; color: #8a8f99; }
.cal-new { height: 34px; padding: 0 14px; font-size: 13px; font-weight: 600; border-radius: 9px; border: 1px solid transparent; background: var(--rl-primary); color: #fff; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: background 120ms var(--rl-ease); }
.cal-new:hover { background: var(--rl-primary-hover); }
.cal-new i, .cal-new svg { width: 18px; height: 18px; }

/* ---- Toolbar (row 2) ---- */
.cal-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 20px; }
.cal-tb__left { display: flex; align-items: center; gap: 10px; }
.cal-tb__right { display: flex; align-items: center; gap: 10px; margin-left: auto; flex-wrap: wrap; }
.cal-month { font-size: 19px; font-weight: 700; letter-spacing: -0.02em; color: var(--rl-fg); }
.cal-today { height: 34px; padding: 0 13px; font-size: 12.5px; font-weight: 600; border-radius: 8px; border: 1px solid var(--rl-border); background: #fff; color: var(--rl-fg-2); cursor: pointer; transition: all 120ms var(--rl-ease); }
.cal-today:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-nav { display: inline-flex; gap: 2px; }
.cal-navbtn { width: 34px; height: 34px; border-radius: 8px; border: 1px solid var(--rl-border); background: #fff; color: var(--rl-fg-2); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: all 120ms var(--rl-ease); }
.cal-navbtn:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-navbtn i { width: 16px; height: 16px; }
.cal-seg { display: inline-flex; padding: 3px; gap: 2px; background: #F1F2F4; border-radius: 10px; }
.cal-seg button { height: 28px; padding: 0 15px; font-size: 12.5px; font-weight: 600; color: var(--rl-fg-3); background: none; border: none; border-radius: 7px; cursor: pointer; transition: all 120ms var(--rl-ease); }
.cal-seg button:hover { color: var(--rl-fg-2); }
.cal-seg button.is-active { background: #fff; color: var(--rl-fg); box-shadow: 0 1px 2px rgba(10,13,15,0.1); }
.cal-range-wrap { position: relative; }
.cal-range { display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 13px; font-size: 13px; font-weight: 600; color: var(--rl-fg-2); border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; font-family: inherit; cursor: pointer; transition: border-color 120ms var(--rl-ease), background 120ms var(--rl-ease); }
.cal-range:hover { background: var(--rl-surface-soft); border-color: var(--rl-fg-4); }
.cal-range--open { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); }
.cal-range i, .cal-range svg { width: 20px; height: 25px; color: var(--rl-fg-3); }

/* Mini date picker popover */
.cal-dp { position: absolute; top: calc(100% + 8px); right: 0; z-index: 60; width: 268px; background: #fff; border: 1px solid var(--rl-border); border-radius: 14px; box-shadow: 0 1px 2px rgba(15,23,42,0.04), 0 18px 44px -12px rgba(15,23,42,0.28); padding: 12px; animation: cal-dp-in 130ms var(--rl-ease-out); }
@keyframes cal-dp-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
.cal-dp__hd { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
.cal-dp__title { font-size: 13.5px; font-weight: 700; letter-spacing: -0.01em; color: var(--rl-fg); }
.cal-dp__nav { width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--rl-border); background: #fff; color: var(--rl-fg-2); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: background 120ms var(--rl-ease); }
.cal-dp__nav:hover { background: var(--rl-surface-soft); }
.cal-dp__nav i { width: 15px; height: 15px; }
.cal-dp__dows { display: grid; grid-template-columns: repeat(7, 1fr); margin-bottom: 4px; }
.cal-dp__dow { font-size: 10.5px; font-weight: 700; letter-spacing: 0.03em; color: var(--rl-fg-4); text-align: center; padding: 4px 0; }
.cal-dp__grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
.cal-dp__day { height: 32px; border: none; background: transparent; border-radius: 8px; font-family: inherit; font-size: 12.5px; font-weight: 600; color: var(--rl-fg-2); cursor: pointer; transition: background 110ms var(--rl-ease), color 110ms var(--rl-ease); }
.cal-dp__day:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-dp__day--out { color: var(--rl-fg-4); font-weight: 500; }
.cal-dp__day--today { color: var(--rl-primary); }
.cal-dp__day--sel, .cal-dp__day--sel:hover { background: var(--rl-primary); color: #fff; }

/* ---- Week grid ---- */
.cal-grid-scroll { overflow-x: auto; overflow-y: hidden; border: 1px solid var(--rl-border); border-radius: 14px; background: #fff; box-shadow: 0 1px 2px rgba(10,13,15,0.04); scrollbar-width: thin; scrollbar-color: rgba(10,13,15,0.14) transparent; }
.cal-grid-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
.cal-grid-scroll::-webkit-scrollbar-track { background: transparent; }
.cal-grid-scroll::-webkit-scrollbar-thumb { background: rgba(10,13,15,0.13); border-radius: 8px; }
.cal-grid-scroll::-webkit-scrollbar-thumb:hover { background: rgba(10,13,15,0.22); }
.cal-grid { min-width: 1040px; padding-bottom: 6px; }
.cal-grid__head { display: flex; border-bottom: 1px solid var(--rl-border); }
.cal-grid__corner { width: 66px; flex: 0 0 66px; }
.cal-grid__days-h { flex: 1; display: grid; grid-template-columns: repeat(7, minmax(132px, 1fr)); }
.cal-dayhd { padding: 11px 10px 12px; text-align: center; border-left: 1px solid var(--rl-border-soft); }
.cal-dayhd__dow { font-size: 11px; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase; color: var(--rl-fg-3); }
.cal-dayhd__num { font-size: 16px; font-weight: 650; color: var(--rl-fg-2); margin-top: 2px; line-height: 1.1; }
.cal-dayhd--today { background: #F4F5F6; }
.cal-dayhd--today .cal-dayhd__dow { color: var(--rl-fg); }
.cal-dayhd--today .cal-dayhd__num { color: var(--rl-fg); }

.cal-grid__body { display: flex; }
.cal-timecol { width: 66px; flex: 0 0 66px; }
.cal-timecell { height: 112px; position: relative; }
.cal-timecell span { position: absolute; top: 7px; right: 11px; font-size: 11px; font-weight: 500; color: var(--rl-fg-4); }
.cal-days { flex: 1; display: grid; grid-template-columns: repeat(7, minmax(132px, 1fr)); position: relative; }
.cal-daycol { position: relative; cursor: pointer; border-left: 1px solid var(--rl-border-soft); background-image: repeating-linear-gradient(to bottom, transparent 0 111px, var(--rl-border-soft) 111px 112px); }
.cal-daycol--today { background-color: #FAFAFB; }
.cal-daycol--weekend { background-color: #FCFCFD; }

/* current-time indicator */
.cal-now { position: absolute; left: 0; width: 100%; height: 0; border-top: 1.5px solid #E84A2E; z-index: 4; pointer-events: none; }
.cal-now::before { content: ""; position: absolute; left: -4px; top: -4px; width: 8px; height: 8px; border-radius: 50%; background: #E84A2E; }

/* ---- Content card ---- */
.cal-card { position: absolute; left: 5px; right: 5px; border-radius: 9px; padding: 7px 9px 7px 15px; overflow: hidden; cursor: grab; touch-action: none; user-select: none; -webkit-user-select: none; transition: transform 120ms var(--rl-ease), box-shadow 120ms var(--rl-ease); }
.cal-card:hover { transform: translateY(-1px); box-shadow: 0 8px 18px rgba(10,13,15,0.1); z-index: 6; }
.cal-card--dragging { cursor: grabbing !important; opacity: 0.93 !important; box-shadow: 0 16px 34px rgba(10,13,15,0.2) !important; z-index: 30 !important; transition: none !important; }
/* target column highlight while a card hovers over it during drag */
.cal-daycol--drop { background-color: #EEF4FF !important; }
.cal-card__bar { position: absolute; left: 6px; top: 8px; bottom: 8px; width: 3px; border-radius: 3px; }
.cal-card__time { font-size: 10px; font-weight: 600; letter-spacing: 0.01em; }
.cal-card__title { font-size: 12px; font-weight: 600; line-height: 1.3; margin-top: 2px; color: #2A2F37; letter-spacing: -0.005em; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.cal-card__dot { position: absolute; top: 9px; right: 9px; width: 7px; height: 7px; border-radius: 50%; box-shadow: 0 0 0 2px rgba(255,255,255,0.7); }

/* ---- Modal ---- */
.cal-scrim { position: fixed; inset: 0; z-index: 80; background: rgba(10,13,15,0.4); backdrop-filter: blur(2px); display: flex; align-items: flex-start; justify-content: center; padding: 56px 20px; overflow-y: auto; }
.cal-modal { width: 100%; max-width: 560px; background: #fff; border-radius: 16px; box-shadow: var(--rl-shadow-floating); overflow: hidden; animation: calModalIn 200ms var(--rl-ease-out); }
@keyframes calModalIn { from { opacity: 0; transform: translateY(8px) scale(0.99); } to { opacity: 1; transform: none; } }
.cal-modal__hd { display: flex; align-items: center; justify-content: space-between; padding: 20px 22px; border-bottom: 1px solid var(--rl-border); }
.cal-modal__hd h3 { font-size: 17px; font-weight: 700; letter-spacing: -0.02em; }
.cal-modal__sub { font-size: 12.5px; color: var(--rl-fg-3); margin: 3px 0 0; font-weight: 500; }
.cal-modal__x { width: 32px; height: 32px; border-radius: 8px; border: none; background: transparent; color: var(--rl-fg-3); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: all 120ms var(--rl-ease); }
.cal-modal__x:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-modal__body { padding: 20px 22px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.cal-fld { display: flex; flex-direction: column; gap: 6px; }
.cal-fld--full { grid-column: 1 / -1; }
.cal-fld label { font-size: 12.5px; font-weight: 600; color: var(--rl-fg-2); display: inline-flex; align-items: baseline; }
.cal-req { color: #C0392B; margin-left: 3px; font-weight: 700; }
.cal-opt { color: var(--rl-fg-4); font-weight: 500; font-size: 11px; margin-left: 5px; }
.cal-fld__err { font-size: 11.5px; font-weight: 600; color: #B23A22; margin-top: 1px; }
.cal-fld input[aria-invalid="true"], .cal-fld select[aria-invalid="true"] { border-color: #D7A096; background: #FDF7F5; }
.cal-fld--hint { margin-top: -6px; }
.cal-fld--hint span { font-size: 11.5px; color: var(--rl-fg-4); line-height: 1.45; }
.cal-fld input, .cal-fld select, .cal-fld textarea { font-family: inherit; font-size: 13.5px; color: var(--rl-fg); padding: 9px 11px; border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; outline: none; transition: all 120ms var(--rl-ease); width: 100%; }
.cal-fld textarea { resize: vertical; min-height: 74px; }
.cal-fld input:focus, .cal-fld select:focus, .cal-fld textarea:focus { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); }
.cal-fld input::placeholder, .cal-fld textarea::placeholder { color: var(--rl-fg-4); }

/* Custom option selector (CalSelect) — used for the content modal's selection
   fields. Trigger matches the other fields; the menu is a bordered white card
   of option rows, each with a circular selector (empty ring / filled black). */
.cal-csel { position: relative; }
.cal-csel__trigger { width: 100%; font-family: inherit; font-size: 13.5px; color: var(--rl-fg); padding: 9px 11px; border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; cursor: pointer; display: flex; align-items: center; gap: 8px; text-align: left; transition: border-color 120ms var(--rl-ease), box-shadow 120ms var(--rl-ease); }
.cal-csel__trigger > span:first-child { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cal-csel__trigger--empty > span:first-child { color: var(--rl-fg-4); }
.cal-csel__trigger:hover { border-color: var(--rl-fg-4); }
.cal-csel__trigger--open { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); }
.cal-csel__trigger[aria-invalid="true"] { border-color: #D7A096; background: #FDF7F5; }
.cal-csel__caret { width: 16px; height: 16px; color: var(--rl-fg-3); flex-shrink: 0; transition: transform 160ms var(--rl-ease); }
.cal-csel__trigger--open .cal-csel__caret { transform: rotate(180deg); }
.cal-csel__menu { position: absolute; top: calc(100% + 6px); left: 0; right: 0; z-index: 90; background: #fff; border: 1px solid #e6e7eb; border-radius: 12px; padding: 6px; box-shadow: 0 1px 2px rgba(15,23,42,0.04), 0 16px 36px -12px rgba(15,23,42,0.22); max-height: 240px; overflow: auto; animation: calPopIn 130ms var(--rl-ease-out); }
.cal-csel__opt { display: flex; align-items: center; gap: 10px; width: 100%; padding: 8px 9px; border: none; background: transparent; border-radius: 8px; font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--rl-fg-2); cursor: pointer; text-align: left; transition: background 110ms var(--rl-ease), color 110ms var(--rl-ease); }
.cal-csel__opt:hover { background: var(--rl-surface-soft); }
.cal-csel__opt--on { color: var(--rl-fg); font-weight: 650; }
.cal-csel__radio { width: 18px; height: 18px; border-radius: 50%; border: 1.5px solid var(--rl-border); background: #fff; flex-shrink: 0; transition: border-color 110ms var(--rl-ease), background 110ms var(--rl-ease); }
.cal-csel__opt--on .cal-csel__radio { border-color: #0A0D0F; background: #0A0D0F; }
.cal-csel__label { flex: 1; min-width: 0; }

/* App-styled Due-date picker (CalDateField). Trigger matches the other fields;
   the popover sits 8px under the input, aligned to its left edge. */
.cal-df { position: relative; }
.cal-df__trigger { width: 100%; font-family: inherit; font-size: 13.5px; color: var(--rl-fg); padding: 9px 11px; border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; cursor: pointer; display: flex; align-items: center; gap: 8px; text-align: left; transition: border-color 120ms var(--rl-ease), box-shadow 120ms var(--rl-ease); }
.cal-df__trigger > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cal-df__trigger--empty > span { color: var(--rl-fg-4); }
.cal-df__trigger:hover { border-color: var(--rl-fg-4); }
.cal-df__trigger--open { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); }
.cal-df__trigger[aria-invalid="true"] { border-color: #D7A096; background: #FDF7F5; }
.cal-df__ic { width: 16px; height: 16px; color: var(--rl-fg-3); flex-shrink: 0; }
.cal-df__pop { position: absolute; top: calc(100% + 8px); left: 0; z-index: 90; width: 250px; background: #fff; border: 1px solid #e6e7eb; border-radius: 12px; padding: 12px; box-shadow: 0 1px 2px rgba(15,23,42,0.05), 0 18px 44px -12px rgba(15,23,42,0.28); animation: calPopIn 130ms var(--rl-ease-out); }
.cal-df__hd { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
.cal-df__title { font-size: 13.5px; font-weight: 700; letter-spacing: -0.01em; color: var(--rl-fg); }
.cal-df__nav { width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--rl-border); background: #fff; color: var(--rl-fg-2); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: background 120ms var(--rl-ease); }
.cal-df__nav:hover { background: var(--rl-surface-soft); }
.cal-df__nav i, .cal-df__nav svg { width: 16px; height: 16px; }
.cal-df__dows { display: grid; grid-template-columns: repeat(7, 1fr); margin-bottom: 4px; }
.cal-df__dow { font-size: 10.5px; font-weight: 700; letter-spacing: 0.03em; color: var(--rl-fg-4); text-align: center; padding: 4px 0; }
.cal-df__grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
.cal-df__day { height: 32px; border: none; background: transparent; border-radius: 8px; font-family: inherit; font-size: 12.5px; font-weight: 600; color: var(--rl-fg-2); cursor: pointer; transition: background 110ms var(--rl-ease), color 110ms var(--rl-ease), box-shadow 110ms var(--rl-ease); }
.cal-df__day:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-df__day--out { color: var(--rl-fg-4); font-weight: 500; }
.cal-df__day--today { box-shadow: inset 0 0 0 1.5px var(--rl-border); }
.cal-df__day--sel, .cal-df__day--sel:hover { background: #0a2538; color: #fff; box-shadow: none; }
.cal-df__ft { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--rl-border); }
.cal-df__link { background: none; border: none; font-family: inherit; font-size: 12.5px; font-weight: 600; color: #2563EB; cursor: pointer; padding: 4px 6px; border-radius: 6px; transition: background 110ms var(--rl-ease); }
.cal-df__link:hover { background: rgba(37,99,235,0.08); }

/* App-styled time picker (CalTimeField). Trigger matches the other fields; the
   popover is a 250px scrollable list of CAL_SNAP-step options, 8px below the
   field. Selected option uses #0a2538 / white; hover is subtle. */
.cal-tf { position: relative; }
.cal-tf__trigger { width: 100%; font-family: inherit; font-size: 13.5px; color: var(--rl-fg); padding: 9px 11px; border: 1px solid var(--rl-border); border-radius: 9px; background: #fff; cursor: pointer; display: flex; align-items: center; gap: 8px; text-align: left; transition: border-color 120ms var(--rl-ease), box-shadow 120ms var(--rl-ease); }
.cal-tf__trigger > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cal-tf__trigger--empty > span { color: var(--rl-fg-4); }
.cal-tf__trigger:hover { border-color: var(--rl-fg-4); }
.cal-tf__trigger--open { border-color: var(--rl-primary); box-shadow: var(--rl-focus-ring); }
.cal-tf__ic { width: 16px; height: 16px; color: var(--rl-fg-3); flex-shrink: 0; }
.cal-tf__pop { position: absolute; top: calc(100% + 8px); left: 0; z-index: 90; width: 250px; background: #fff; border: 1px solid #e6e7eb; border-radius: 12px; padding: 10px; box-shadow: 0 1px 2px rgba(15,23,42,0.05), 0 18px 44px -12px rgba(15,23,42,0.28); animation: calPopIn 130ms var(--rl-ease-out); }
.cal-tf__list { max-height: 216px; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; }
.cal-tf__list::-webkit-scrollbar { width: 8px; }
.cal-tf__list::-webkit-scrollbar-thumb { background: var(--rl-border); border-radius: 999px; border: 2px solid #fff; }
.cal-tf__opt { display: block; width: 100%; text-align: left; padding: 7px 10px; border: none; background: transparent; border-radius: 8px; font-family: inherit; font-size: 13px; font-weight: 600; color: var(--rl-fg-2); cursor: pointer; transition: background 110ms var(--rl-ease), color 110ms var(--rl-ease); }
.cal-tf__opt:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-tf__opt--on, .cal-tf__opt--on:hover { background: #0a2538; color: #fff; }
.cal-modal__ft { display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding: 16px 22px 20px; border-top: 1px solid var(--rl-border); }
.cal-btn { height: 38px; padding: 0 18px; font-size: 13.5px; font-weight: 600; border-radius: 10px; cursor: pointer; border: 1px solid transparent; transition: all 120ms var(--rl-ease); }
.cal-btn--ghost { background: #fff; border-color: var(--rl-border); color: var(--rl-fg); }
.cal-btn--ghost:hover { background: var(--rl-surface-soft); }
.cal-btn--primary { background: var(--rl-primary); color: #fff; }
.cal-btn--primary:hover { background: var(--rl-primary-hover); }
.cal-btn--danger { background: #fff; border-color: #E4C2BB; color: #B23A22; display: inline-flex; align-items: center; gap: 7px; }
.cal-btn--danger:hover { background: #FBF0ED; border-color: #D7A096; }
.cal-btn--danger i { width: 15px; height: 15px; }
.cal-btn--danger-solid { background: #B23A22; color: #fff; border-color: transparent; }
.cal-btn--danger-solid:hover { background: #9C311C; }
.cal-modal__del { margin-right: auto; }
.cal-modal__brief { display: inline-flex; align-items: center; gap: 7px; }
.cal-modal__brief i, .cal-modal__brief svg { width: 15px; height: 15px; }
.cal-modal__confirm { display: flex; align-items: center; gap: 10px; width: 100%; }
.cal-modal__confirm-msg { margin-right: auto; font-size: 13px; font-weight: 600; color: var(--rl-fg-2); }

/* ---- Month grid ---- */
.cal-mgrid { border: 1px solid var(--rl-border); border-radius: 14px; background: #fff; overflow: hidden; box-shadow: 0 1px 2px rgba(10,13,15,0.04); }
.cal-mgrid__head { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); border-bottom: 1px solid var(--rl-border); }
.cal-mgrid__dow { padding: 11px 12px; font-size: 11px; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase; color: var(--rl-fg-3); border-left: 1px solid var(--rl-border-soft); }
.cal-mgrid__dow:first-child { border-left: none; }
.cal-mgrid__body { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }
.cal-mcell { min-height: 132px; min-width: 0; padding: 7px 7px 9px; cursor: pointer; display: flex; flex-direction: column; gap: 6px; border-left: 1px solid var(--rl-border-soft); border-top: 1px solid var(--rl-border-soft); transition: background 120ms var(--rl-ease); }
.cal-mcell:nth-child(7n+1) { border-left: none; }
.cal-mcell:nth-child(-n+7) { border-top: none; }
.cal-mcell:hover { background: var(--rl-surface-soft); }
.cal-mcell--weekend { background: #FCFCFD; }
.cal-mcell--out { background: #FAFBFC; }
.cal-mcell--out:hover { background: #F4F5F6; }
.cal-mcell__num { font-size: 12.5px; font-weight: 650; color: var(--rl-fg-2); width: 25px; height: 23px; display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; }
.cal-mcell--out .cal-mcell__num { color: var(--rl-fg-4); font-weight: 550; }
.cal-mcell--today .cal-mcell__num { background: var(--rl-fg); color: #fff; border-radius: 7px; }
.cal-mcell__list { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.cal-mchip { position: relative; display: flex; align-items: center; gap: 5px; min-width: 0; padding: 3px 8px 3px 12px; border-radius: 7px; cursor: pointer; overflow: hidden; transition: transform 110ms var(--rl-ease), box-shadow 110ms var(--rl-ease); }
.cal-mchip:hover { transform: translateY(-1px); box-shadow: 0 5px 12px rgba(10,13,15,0.12); }
.cal-mchip__bar { position: absolute; left: 5px; top: 5px; bottom: 5px; width: 3px; border-radius: 3px; }
.cal-mchip__time { font-size: 10.5px; font-weight: 700; flex-shrink: 0; letter-spacing: -0.01em; }
.cal-mchip__t { font-size: 11px; font-weight: 600; color: #2A2F37; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: -0.005em; }
.cal-mmore { background: none; border: none; padding: 1px 8px; font-family: inherit; font-size: 11px; font-weight: 650; color: var(--rl-fg-3); text-align: left; cursor: pointer; border-radius: 6px; transition: all 110ms var(--rl-ease); }
.cal-mmore:hover { color: var(--rl-fg); background: rgba(10,13,15,0.05); }

/* ---- Calendar layout + right-side summary panel ----
   Header/tabs/toolbar live in .cal-head (capped to the calendar width so the
   toolbar + New button keep their position); the grid and the summary panel sit
   in a flex row below, so the panel's top aligns with the calendar board rather
   than the page header. This survives header/toolbar height changes. */
.cal-head { max-width: 1222px; }
.cal-board-row { display: flex; align-items: flex-start; gap: 28px; }
.cal-board { flex: 1 1 auto; min-width: 0; max-width: 1222px; }
.cal-aside { flex: 0 0 320px; width: 320px; display: flex; flex-direction: column; gap: 16px; position: sticky; top: 0; align-self: flex-start; }
.cal-sumcard { background: #fff; border: 1px solid var(--rl-border); border-radius: 14px; padding: 16px 16px 15px; box-shadow: 0 1px 2px rgba(10,13,15,0.04); }
.cal-sumcard__hd { display: flex; align-items: center; gap: 8px; font-size: 13.5px; font-weight: 700; letter-spacing: -0.01em; color: var(--rl-fg); margin-bottom: 12px; }
.cal-sumcard__hd i, .cal-sumcard__hd svg { width: 15px; height: 15px; color: var(--rl-fg-3); flex-shrink: 0; }
.cal-up-list { display: flex; flex-direction: column; }
.cal-up { display: flex; flex-direction: column; gap: 6px; width: 100%; text-align: left; border: none; background: transparent; font-family: inherit; cursor: pointer; padding: 11px 8px; border-radius: 9px; border-top: 1px solid var(--rl-border-soft); transition: background 110ms var(--rl-ease); }
.cal-up:first-child { border-top: none; }
.cal-up:hover { background: var(--rl-surface-soft); }
.cal-up__when { font-size: 11px; font-weight: 650; color: var(--rl-fg-3); letter-spacing: 0.01em; }
.cal-up__title { font-size: 13px; font-weight: 600; color: var(--rl-fg); line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cal-up__type { display: inline-flex; align-items: center; gap: 6px; font-size: 11.5px; font-weight: 600; line-height: 1.4; color: var(--rl-fg-3); }
.cal-up__dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
.cal-up-empty { font-size: 12.5px; color: var(--rl-fg-4); font-style: italic; padding: 4px 2px 2px; }
/* Stack the panel below the calendar when there isn't room beside it. */
@media (max-width: 1480px) {
  .cal-board-row { flex-direction: column; }
  .cal-aside { position: static; flex-basis: auto; width: 100%; max-width: 1222px; flex-direction: row; }
  .cal-aside > .cal-sumcard { flex: 1 1 0; min-width: 0; }
}
@media (max-width: 720px) {
  .cal-aside { flex-direction: column; }
}

/* ---- Empty / no-results state ---- */
.cal-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; text-align: center; min-height: 320px; border: 1px solid var(--rl-border); border-radius: 14px; background: #fff; box-shadow: 0 1px 2px rgba(10,13,15,0.04); padding: 56px 24px; }
.cal-empty__icon { width: 46px; height: 46px; border-radius: 12px; background: var(--rl-surface-soft); display: inline-flex; align-items: center; justify-content: center; color: var(--rl-fg-3); }
.cal-empty__icon i { width: 22px; height: 22px; }
.cal-empty__title { font-size: 15px; font-weight: 650; color: var(--rl-fg); letter-spacing: -0.01em; }
.cal-empty__sub { font-size: 13px; color: var(--rl-fg-3); max-width: 320px; }
.cal-empty__sub b { color: var(--rl-fg-2); font-weight: 650; }

/* ---- Filter popover ---- */
.cal-filter-wrap { position: relative; }
.cal-icbtn.is-on { border-color: var(--rl-fg); color: var(--rl-fg); background: var(--rl-surface-soft); }
.cal-filter-badge { min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--rl-primary); color: #fff; font-size: 11px; font-weight: 700; line-height: 1; display: inline-flex; align-items: center; justify-content: center; }
.cal-pop { position: absolute; top: calc(100% + 8px); right: 0; z-index: 50; width: 260px; background: #fff; border: 1px solid var(--rl-border); border-radius: 13px; box-shadow: var(--rl-shadow-floating); overflow: hidden; animation: calPopIn 140ms var(--rl-ease-out); }
@keyframes calPopIn { from { opacity: 0; transform: translateY(-5px) scale(0.99); } to { opacity: 1; transform: none; } }
.cal-pop__sec { padding: 12px 12px 13px; }
.cal-pop__sec + .cal-pop__sec { border-top: 1px solid var(--rl-border-soft); }
.cal-pop__lbl { font-size: 11px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: var(--rl-fg-3); margin: 0 2px 9px; }
.cal-pop__rows { display: flex; flex-direction: column; gap: 1px; }
.cal-optrow { display: flex; align-items: center; gap: 9px; padding: 7px 8px; border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 550; color: var(--rl-fg-2); transition: background 110ms var(--rl-ease); }
.cal-optrow:hover { background: var(--rl-surface-soft); }
.cal-optrow.is-on { color: var(--rl-fg); font-weight: 600; }
.cal-optrow__check { width: 17px; height: 17px; border-radius: 5px; border: 1.5px solid #CBD0D6; background: #fff; display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all 110ms var(--rl-ease); }
.cal-optrow.is-on .cal-optrow__check { background: var(--rl-primary); border-color: var(--rl-primary); color: #fff; }
.cal-optrow__check svg { opacity: 0; transition: opacity 110ms var(--rl-ease); }
.cal-optrow.is-on .cal-optrow__check svg { opacity: 1; }
.cal-optrow__dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.cal-optrow__t { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cal-pop__ft { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--rl-border); background: var(--rl-surface-soft); }
.cal-pop__clear { font-family: inherit; font-size: 12.5px; font-weight: 650; color: var(--rl-fg); background: none; border: none; padding: 4px 2px; cursor: pointer; transition: color 110ms var(--rl-ease); }
.cal-pop__clear:hover:not(:disabled) { color: var(--rl-primary); }
.cal-pop__clear:disabled { color: var(--rl-fg-4); cursor: default; }
.cal-pop__count { font-size: 12px; font-weight: 550; color: var(--rl-fg-3); }

/* ---- Active filter chips (below toolbar) ---- */
.cal-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: -4px 0 20px; }
.cal-fchip { display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 5px 0 11px; border-radius: 8px; border: 1px solid var(--rl-border); background: #fff; font-size: 12.5px; box-shadow: 0 1px 1px rgba(10,13,15,0.03); }
.cal-fchip__dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; margin-right: -1px; }
.cal-fchip__k { font-weight: 550; color: var(--rl-fg-3); }
.cal-fchip__v { font-weight: 650; color: var(--rl-fg); letter-spacing: -0.005em; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cal-fchip__x { width: 19px; height: 19px; border-radius: 5px; border: none; background: transparent; color: var(--rl-fg-4); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; flex-shrink: 0; transition: all 110ms var(--rl-ease); }
.cal-fchip__x:hover { background: var(--rl-surface-soft); color: var(--rl-fg); }
.cal-chips__clear { font-family: inherit; font-size: 12.5px; font-weight: 650; color: var(--rl-fg-3); background: none; border: none; padding: 6px 6px; cursor: pointer; border-radius: 7px; transition: all 110ms var(--rl-ease); }
.cal-chips__clear:hover { color: var(--rl-fg); background: var(--rl-surface-soft); }

/* ---- More-options menu ---- */
.cal-more-wrap { position: relative; }
.cal-menu { position: absolute; top: calc(100% + 8px); right: 0; z-index: 50; width: 214px; background: #fff; border: 1px solid var(--rl-border); border-radius: 12px; box-shadow: var(--rl-shadow-floating); padding: 6px; animation: calPopIn 140ms var(--rl-ease-out); }
.cal-menu__item { display: flex; align-items: center; gap: 10px; width: 100%; padding: 9px 10px; border: none; background: none; border-radius: 8px; font-family: inherit; font-size: 13px; font-weight: 600; color: var(--rl-fg); cursor: pointer; text-align: left; transition: background 110ms var(--rl-ease); }
.cal-menu__item:hover:not(:disabled) { background: var(--rl-surface-soft); }
.cal-menu__item:disabled { color: var(--rl-fg-4); cursor: default; }
.cal-menu__item svg { width: 16px; height: 16px; flex-shrink: 0; }
.cal-menu__lbl { flex: 1; }
.cal-menu__soon { font-size: 10px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: var(--rl-fg-4); background: var(--rl-surface-soft); padding: 2px 6px; border-radius: 5px; }
.cal-menu__sep { height: 1px; background: var(--rl-border-soft); margin: 5px 6px; }

@media (max-width: 720px) {
  .cal-page { padding: 22px 16px 40px; }
  .cal-modal__body { grid-template-columns: 1fr; }
  .cal-mcell { min-height: 96px; }
}
`;

function ensureCalStyles() {
  if (document.getElementById('cal-styles')) return;
  const el = document.createElement('style');
  el.id = 'cal-styles';
  el.textContent = CAL_CSS;
  document.head.appendChild(el);
}

/* ------------------------------------------------------------------ */
/* Static config + dummy data */

/* Single source of truth for blog post types. Add a new type here and it
   automatically flows to the calendar tab filters, the "+ New" modal options,
   and the per-card styling. */
const POST_TYPES = ['Guide', 'Product Roundup', 'Product Comparison', 'Single Product Review'];

/* Visual treatment + tab icon per post type. Keyed by the post-type string so
   there is exactly one place to edit when a type is added. */
const CAL_TYPES = {
  'Guide': { bg: '#eaf1fb', bar: '#648bdf', fg: '#648bdf', icon: 'book-open' }, // soft blue
  'Product Roundup': { bg: '#e6f6ec', bar: '#5dab83', fg: '#5dab83', icon: 'list' }, // soft green
  'Product Comparison': { bg: '#f0ecfb', bar: '#987dda', fg: '#987dda', icon: 'columns-2' }, // soft purple
  'Single Product Review': { bg: '#fbf1e7', bar: '#de8c53', fg: '#de8c53', icon: 'star' } // soft peach
};

const CAL_STATUS = {
  Draft: '#E0A21B',
  Review: '#5B8DEF',
  Scheduled: '#46B978',
  Planned: '#B5BAC3'
};

/* Filter option sets for the Filter popover. Status order follows CAL_STATUS;
   priorities + assignees mirror the values offered in the ContentModal. */
const CAL_STATUSES = ['Draft', 'Review', 'Scheduled', 'Planned'];
const CAL_PRIORITIES = ['High', 'Medium', 'Low'];
const CAL_ASSIGNEES = ['Jamie Doyle', 'Olivia Carter', 'Ethan Nguyen', 'Sophie Bennett'];

/* Tabs derive from POST_TYPES — "All Content" plus one tab per post type. */
const CAL_TABS = [
{ id: 'all', label: 'All Content', icon: 'layers' },
...POST_TYPES.map((pt) => ({ id: pt, label: pt, icon: CAL_TYPES[pt].icon }))];


/* Real browser-local "today" at local midnight — the single source of truth for
   the focused date, the today highlight, the current-time line, and the seeded
   sample week. Uses local getters (never UTC) so the YYYY-MM-DD date key never
   shifts across timezones. Recomputed on use so it stays correct past midnight. */
function calToday() {
  const n = new Date();
  return new Date(n.getFullYear(), n.getMonth(), n.getDate());
}
function calTodayIso() {
  return calIso(calToday());
}

const DOW_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const DOW_FULL = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function calStartOfWeek(d) {
  const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  x.setDate(x.getDate() - (x.getDay() + 6) % 7); // back up to Monday
  return x;
}
function calAddDays(d, n) {
  const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  x.setDate(x.getDate() + n);
  return x;
}
function calIso(d) {
  return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function calParseIso(s) {
  const p = String(s).split('-').map(Number);
  return new Date(p[0], p[1] - 1, p[2]);
}
function calWeekday(dateStr) {return (calParseIso(dateStr).getDay() + 6) % 7;} // 0=Mon..6=Sun

/* The 7 day-header descriptors for the week starting at `weekStart` (a Monday). */
function buildWeekDays(weekStart) {
  const todayIso = calTodayIso();
  return Array.from({ length: 7 }, (_, i) => {
    const d = calAddDays(weekStart, i);
    const iso = calIso(d);
    return { dow: DOW_NAMES[i], num: d.getDate(), dateStr: iso, today: iso === todayIso, weekend: i >= 5 };
  });
}
/* A single day-header descriptor (used by Day view). */
function buildDayDescriptor(date) {
  const iso = calIso(date);
  const wd = (date.getDay() + 6) % 7;
  return { dow: DOW_NAMES[wd], num: date.getDate(), dateStr: iso, today: iso === calTodayIso(), weekend: wd >= 5 };
}
function calMonthLabel(days) {
  const a = calParseIso(days[0].dateStr),b = calParseIso(days[days.length - 1].dateStr);
  if (a.getMonth() === b.getMonth()) return MONTH_NAMES[a.getMonth()] + ' ' + a.getFullYear();
  if (a.getFullYear() === b.getFullYear()) return MONTH_SHORT[a.getMonth()] + ' – ' + MONTH_SHORT[b.getMonth()] + ' ' + b.getFullYear();
  return MONTH_SHORT[a.getMonth()] + ' ' + a.getFullYear() + ' – ' + MONTH_SHORT[b.getMonth()] + ' ' + b.getFullYear();
}
function calRangeLabel(days) {
  const a = calParseIso(days[0].dateStr),b = calParseIso(days[days.length - 1].dateStr);
  if (a.getTime() === b.getTime()) return a.getDate() + ' ' + MONTH_SHORT[a.getMonth()] + ' ' + a.getFullYear();
  return a.getDate() + ' ' + MONTH_SHORT[a.getMonth()] + ' - ' + b.getDate() + ' ' + MONTH_SHORT[b.getMonth()] + ' ' + b.getFullYear();
}
function calDateLabel(dateStr) {
  const d = calParseIso(dateStr);
  return DOW_NAMES[(d.getDay() + 6) % 7] + ', ' + MONTH_SHORT[d.getMonth()] + ' ' + d.getDate();
}
/* Month view helpers: a 7-wide grid of weeks (Mon-start) covering the anchor's
   month, with leading/trailing days from adjacent months flagged `inMonth:false`. */
function buildMonthGrid(anchor) {
  const y = anchor.getFullYear(),m = anchor.getMonth();
  const first = new Date(y, m, 1);
  const firstWd = (first.getDay() + 6) % 7; // 0=Mon
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const numWeeks = Math.ceil((firstWd + daysInMonth) / 7);
  const gridStart = calStartOfWeek(first);
  const todayIso = calTodayIso();
  const weeks = [];
  for (let w = 0; w < numWeeks; w++) {
    const days = [];
    for (let i = 0; i < 7; i++) {
      const d = calAddDays(gridStart, w * 7 + i);
      const iso = calIso(d);
      days.push({ num: d.getDate(), dateStr: iso, today: iso === todayIso, inMonth: d.getMonth() === m, weekend: i >= 5 });
    }
    weeks.push(days);
  }
  return weeks;
}
function calMonthRangeLabel(anchor) {
  const y = anchor.getFullYear(),m = anchor.getMonth();
  const last = new Date(y, m + 1, 0).getDate();
  return '1 ' + MONTH_SHORT[m] + ' - ' + last + ' ' + MONTH_SHORT[m] + ' ' + y;
}


const CAL_START_HOUR = 8; // 8 AM — first visible slot
const CAL_LAST_SLOT = 17; // 5 PM — last visible/labeled slot
const CAL_END_HOUR = 18; // 6 PM — internal bottom boundary so the 5 PM slot is a full row (no 6 PM label drawn)
const CAL_HOUR_PX = 112;
const CAL_INSET = 8; // vertical breathing room around each card (px, top & bottom)
const CAL_SNAP = 0.5; // drop snapping increment in hours (0.5 = 30 min). Easy to change to 1 for hourly.

/* dummy scheduled content — `day` here is just a seed offset (0=Mon..6=Sun)
   within the current week; loadCalendarEvents() converts it to a real `date`.
   start/end = 24h (decimals = half hours). `type` is one of POST_TYPES. */
const CAL_EVENTS = [
{ day: 0, start: 8, end: 9, title: 'Draft: SaaS Onboarding Guide', type: 'Guide', status: 'Draft', primaryKeyword: 'saas onboarding' },
{ day: 0, start: 9, end: 10.5, title: 'Outline: Best CRMs for Startups 2026', type: 'Product Roundup', status: 'Review', primaryKeyword: 'best crm for startups' },
{ day: 0, start: 11, end: 12, title: 'Review: Notion AI', type: 'Single Product Review', status: 'Scheduled', primaryKeyword: 'notion ai review' },
{ day: 1, start: 9, end: 10, title: 'Review Product Comparison Outline', type: 'Product Comparison', status: 'Review', primaryKeyword: 'project management comparison' },
{ day: 1, start: 11, end: 12.5, title: 'Draft: Email Marketing Tools Roundup', type: 'Product Roundup', status: 'Draft', primaryKeyword: 'best email marketing tools' },
{ day: 2, start: 8, end: 9, title: 'New Guide: AI Search Ranking', type: 'Guide', status: 'Planned', primaryKeyword: 'ai search ranking' },
{ day: 2, start: 10, end: 11, title: 'Asana vs Monday Comparison', type: 'Product Comparison', status: 'Scheduled', primaryKeyword: 'asana vs monday' },
{ day: 2, start: 16, end: 17, title: 'Edit: Top SEO Tools Roundup', type: 'Product Roundup', status: 'Planned', primaryKeyword: 'best seo tools' },
{ day: 3, start: 9, end: 10, title: 'Review: Jasper AI', type: 'Single Product Review', status: 'Scheduled', primaryKeyword: 'jasper ai review' },
{ day: 3, start: 14, end: 15, title: 'Guide: On-Page SEO Checklist', type: 'Guide', status: 'Review', primaryKeyword: 'on-page seo checklist' },
{ day: 4, start: 8.5, end: 10, title: 'Compare: HubSpot vs Salesforce', type: 'Product Comparison', status: 'Scheduled', primaryKeyword: 'hubspot vs salesforce' },
{ day: 4, start: 11, end: 12, title: 'Review: Surfer SEO', type: 'Single Product Review', status: 'Planned', primaryKeyword: 'surfer seo review' },
{ day: 5, start: 9, end: 10, title: 'Draft: Link Building Guide', type: 'Guide', status: 'Planned', primaryKeyword: 'link building strategies' },
{ day: 6, start: 10, end: 11, title: 'Publish: Best CRMs for Startups 2026', type: 'Product Roundup', status: 'Scheduled', primaryKeyword: 'best crm for startups' }];


function fmtHour(h) {
  const period = h >= 12 ? 'PM' : 'AM';
  const whole = Math.floor(h);
  const mins = Math.round((h - whole) * 60);
  const display = whole % 12 === 0 ? 12 : whole % 12;
  return display + (mins ? ':' + String(mins).padStart(2, '0') : '') + ' ' + period;
}
function fmtRange(s, e) {
  return fmtHour(s) + ' - ' + fmtHour(e);
}
/* Compact hour for dense month chips, e.g. 8 -> "8a", 14.5 -> "2:30p". */
function fmtHourShort(h) {
  const whole = Math.floor(h);
  const mins = Math.round((h - whole) * 60);
  const period = h >= 12 ? 'p' : 'a';
  const display = whole % 12 === 0 ? 12 : whole % 12;
  return display + (mins ? ':' + String(mins).padStart(2, '0') : '') + period;
}
/* hours-as-decimal -> "HH:MM" for <input type="time"> values */
function hhmm(h) {
  const whole = Math.floor(h);
  const m = Math.round((h - whole) * 60);
  return String(whole).padStart(2, '0') + ':' + String(m).padStart(2, '0');
}
/* "HH:MM" -> hours-as-decimal (inverse of hhmm) */
function parseTime(str, fallback) {
  if (!str || str.indexOf(':') < 0) return fallback;
  const parts = str.split(':');
  return Number(parts[0]) + (Number(parts[1]) || 0) / 60;
}
/* Snap an hour value to the calendar's increment and clamp it into the
   visible 8 AM–5 PM start range (shared by drag + click-to-create). */
function snapStart(h) {
  const s = Math.round(h / CAL_SNAP) * CAL_SNAP;
  return Math.max(CAL_START_HOUR, Math.min(CAL_LAST_SLOT, s));
}

/* Selectable options for the custom time picker — every CAL_SNAP increment across
   the visible working range (CAL_START_HOUR..CAL_END_HOUR). Value is the "HH:MM"
   string the existing form logic already parses; label is the friendly time. */
function calTimeOptions() {
  const opts = [];
  const steps = Math.round((CAL_END_HOUR - CAL_START_HOUR) / CAL_SNAP);
  for (let i = 0; i <= steps; i++) {
    const h = CAL_START_HOUR + i * CAL_SNAP;
    opts.push({ value: hhmm(h), label: fmtHour(h) });
  }
  return opts;
}

/* Does an event match the free-text search? Searches title, primary keyword,
   notes, type, status, priority, and assigned-to. `q` is pre-lowercased + trimmed. */
function eventMatchesQuery(ev, q) {
  if (!q) return true;
  const hay = [ev.title, ev.primaryKeyword, ev.notes, ev.type, ev.status, ev.priority, ev.assigned].
  filter(Boolean).join(' · ').toLowerCase();
  return hay.indexOf(q) >= 0;
}

/* Does an event pass the structured Filter popover? Each section is an array of
   selected values; an empty section means "no constraint". All sections AND
   together (and combine with the search + active tab at the call site). */
function eventMatchesFilters(ev, f) {
  if (f.status.length && !f.status.includes(ev.status)) return false;
  if (f.priority.length && !f.priority.includes(ev.priority)) return false;
  if (f.assigned.length && !f.assigned.includes(ev.assigned)) return false;
  return true;
}
function filtersActive(f) {
  return f.status.length + f.priority.length + f.assigned.length > 0;
}

/* ==================================================================
   EVENT DATA LAYER
   The single place that knows how to mutate the events collection.
   Today these are pure, synchronous in-memory transforms: each takes the
   current events array and returns the next one. Components never touch the
   array shape directly — they call these helpers — so swapping to Supabase
   later means changing ONLY these four bodies (e.g. await an insert/update/
   delete and return the refreshed list), with no changes in CalendarPage.

   Event shape: { id, day, start, end, title, type, status, priority?, assigned?, notes? }
   ================================================================== */

/* Monotonic, collision-safe id for newly created events. Replace with the
   DB-generated id (e.g. the row's uuid) once persistence lands. */
let calEventSeq = 0;
function nextCalEventId() {
  calEventSeq += 1;
  return 'ev-' + Date.now().toString(36) + '-' + calEventSeq;
}

/* Seed the in-memory store from the dummy data, converting each seed `day`
   offset into a real ISO `date` in the current week. Later: fetch from Supabase. */
function loadCalendarEvents() {
  const monday = calStartOfWeek(calToday());
  return CAL_EVENTS.map((e, i) => {
    const { day, ...rest } = e;
    return { id: 'ev' + i, date: calIso(calAddDays(monday, day)), ...rest };
  });
}

/* CREATE — append a new event (with a fresh id). Later: supabase.insert(data). */
function createCalendarEvent(events, data) {
  return [...events, { id: nextCalEventId(), ...data }];
}

/* UPDATE — merge changes into one event by id. Later: supabase.update(changes).eq('id', id). */
function updateCalendarEvent(events, id, changes) {
  return events.map((e) => e.id === id ? { ...e, ...changes } : e);
}

/* DELETE — remove one event by id. Later: supabase.delete().eq('id', id). */
function deleteCalendarEvent(events, id) {
  return events.filter((e) => e.id !== id);
}

/* MOVE — reschedule one event to a new date + start, preserving its duration.
   Later: supabase.update({ date, start, end }).eq('id', id). */
function moveCalendarEvent(events, id, date, start) {
  return events.map((e) =>
  e.id === id ?
  { ...e, date, start, end: Math.round((start + (e.end - e.start)) * 100) / 100 } :
  e);
}

/* AUTO-PLACE — pick the next free start hour on `dateIso` for a default-duration
   event when the user left Start/End blank. Future/past date: scan from 8 AM.
   Today: scan from just after the real browser-local time, rounded up to the next
   CAL_SNAP increment. The floor is clamped into the visible 8 AM–5 PM start range
   (so a time outside that range falls back to the nearest valid slot). Slots
   already occupied on that day are skipped, so repeated same-day creates don't all
   stack at 8 AM; if the day is full, it stacks at the last valid slot. */
function autoPlaceSlot(events, dateIso, duration) {
  const dur = duration || 1;
  const lastStart = CAL_END_HOUR - dur; // latest start that still fits before 6 PM
  let floor = CAL_START_HOUR;
  if (dateIso === calTodayIso()) {
    const n = new Date();
    const dec = n.getHours() + n.getMinutes() / 60;
    floor = Math.ceil(dec / CAL_SNAP) * CAL_SNAP; // next snap after the real now
  }
  floor = Math.max(CAL_START_HOUR, Math.min(floor, lastStart));
  const taken = events.
  filter((e) => e.date === dateIso && e.start != null && e.end != null).
  map((e) => [e.start, e.end]);
  const isFree = (s) => {
    const e = s + dur;
    return !taken.some(([a, b]) => s < b && e > a);
  };
  for (let s = floor; s <= lastStart + 1e-9; s = Math.round((s + CAL_SNAP) * 100) / 100) {
    if (isFree(s)) return { start: Math.round(s * 100) / 100, end: Math.round((s + dur) * 100) / 100 };
  }
  return { start: lastStart, end: Math.round((lastStart + dur) * 100) / 100 };
}

/* ------------------------------------------------------------------ */
/* CalendarHeader */
function CalendarHeader() {
  return (
    <header className="cal-hd">
      <div>
        <h1 className="cal-hd__title">Calendar</h1>
        <p className="cal-hd__sub">Plan, schedule, and manage your upcoming content.</p>
      </div>
    </header>);

}

/* ------------------------------------------------------------------ */
/* CalendarTabs — row 1, content-type tabs only (visual) */
function CalendarTabs({ active, onSelect }) {
  return (
    <nav className="cal-tabs" aria-label="Content categories">
      {CAL_TABS.map((t) =>
      <button
        key={t.id}
        type="button"
        className={'cal-tab ' + (active === t.id ? 'cal-tab--active' : '')}
        aria-current={active === t.id ? 'true' : undefined}
        onClick={() => onSelect(t.id)}>
          <i data-lucide={t.icon}></i>
          <span>{t.label}</span>
        </button>
      )}
    </nav>);

}

/* ------------------------------------------------------------------ */
/* CalendarFilterButton — the "Filter" button + its popover. Manages its own
   open/close (click-outside + Escape); the selected filters live up in
   CalendarPage so they combine with the tab, search, and view. */
function CalendarFilterButton({ filters, onToggle, onClear }) {
  const [open, setOpen] = useCalState(false);
  const wrapRef = useCalRef(null);
  const count = filters.status.length + filters.priority.length + filters.assigned.length;

  useCalEffect(() => {
    if (!open) return;
    const onDown = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDown);document.removeEventListener('keydown', onKey);};
  }, [open]);

  // Re-stamp lucide icons whenever the popover opens (the Filter button glyph).
  // The row check marks are React-owned inline SVGs, so lucide never touches
  // them — avoids the removeChild reconciliation crash from toggled data-lucide.
  useCalEffect(() => {
    if (open && window.lucide) window.lucide.createIcons();
  }, [open]);

  const renderRow = (section, value, color) => {
    const on = filters[section].includes(value);
    return (
      <div
        key={value}
        className={'cal-optrow ' + (on ? 'is-on' : '')}
        role="checkbox"
        aria-checked={on}
        tabIndex={0}
        onClick={() => onToggle(section, value)}
        onKeyDown={(e) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();onToggle(section, value);}}}>
        <span className="cal-optrow__check" aria-hidden="true" style={on ? { background: 'var(--rl-primary)', borderColor: 'var(--rl-primary)', color: '#fff' } : undefined}>
          <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: on ? 1 : 0 }}><polyline points="20 6 9 17 4 12"></polyline></svg>
        </span>
        {color && <span className="cal-optrow__dot" style={{ background: color }}></span>}
        <span className="cal-optrow__t">{value}</span>
      </div>);

  };

  return (
    <div className="cal-filter-wrap" ref={wrapRef}>
      <button
        type="button"
        className={'cal-icbtn ' + (count ? 'is-on' : '')}
        aria-expanded={open}
        aria-haspopup="dialog"
        onClick={() => setOpen((o) => !o)}>
        <i data-lucide="sliders-horizontal"></i><span>Filter</span>
        {count > 0 && <span className="cal-filter-badge">{count}</span>}
      </button>
      {open &&
      <div className="cal-pop" role="dialog" aria-label="Filter content">
        <div className="cal-pop__sec">
          <div className="cal-pop__lbl">Status</div>
          <div className="cal-pop__rows">
            {CAL_STATUSES.map((s) => renderRow('status', s, CAL_STATUS[s]))}
          </div>
        </div>
        <div className="cal-pop__sec">
          <div className="cal-pop__lbl">Priority</div>
          <div className="cal-pop__rows">
            {CAL_PRIORITIES.map((p) => renderRow('priority', p))}
          </div>
        </div>
        <div className="cal-pop__sec">
          <div className="cal-pop__lbl">Assigned to</div>
          <div className="cal-pop__rows">
            {CAL_ASSIGNEES.map((a) => renderRow('assigned', a))}
          </div>
        </div>
        <div className="cal-pop__ft">
          <button type="button" className="cal-pop__clear" disabled={count === 0} onClick={onClear}>Clear filters</button>
          <span className="cal-pop__count">{count ? count + ' active' : 'No filters'}</span>
        </div>
      </div>}
    </div>);

}

/* ------------------------------------------------------------------ */
/* CalendarMoreMenu — the "⋯" toolbar button + its dropdown. Self-manages
   open/close (click-outside + Escape). Export / Print / Settings are
   placeholders for now; "Clear all filters" wipes the search term and every
   active filter via onClearAll (disabled when nothing is active). */
function CalendarMoreMenu({ canClear, onClearAll }) {
  const [open, setOpen] = useCalState(false);
  const wrapRef = useCalRef(null);

  useCalEffect(() => {
    if (!open) return;
    const onDown = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    if (window.lucide) window.lucide.createIcons();
    return () => {document.removeEventListener('mousedown', onDown);document.removeEventListener('keydown', onKey);};
  }, [open]);

  return (
    <div className="cal-more-wrap" ref={wrapRef}>
      <button
        type="button"
        className={'cal-icbtn ' + (open ? 'is-on' : '')}
        aria-label="More options"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}>
        <i data-lucide="more-horizontal"></i>
      </button>
      {open &&
      <div className="cal-menu" role="menu">
        <button type="button" className="cal-menu__item" role="menuitem" disabled>
          <i data-lucide="download"></i><span className="cal-menu__lbl">Export calendar</span><span className="cal-menu__soon">Soon</span>
        </button>
        <button type="button" className="cal-menu__item" role="menuitem" disabled>
          <i data-lucide="printer"></i><span className="cal-menu__lbl">Print calendar</span><span className="cal-menu__soon">Soon</span>
        </button>
        <div className="cal-menu__sep"></div>
        <button type="button" className="cal-menu__item" role="menuitem" disabled={!canClear} onClick={() => {onClearAll();setOpen(false);}}>
          <i data-lucide="filter-x"></i><span className="cal-menu__lbl">Clear all filters</span>
        </button>
        <div className="cal-menu__sep"></div>
        <button type="button" className="cal-menu__item" role="menuitem" disabled>
          <i data-lucide="settings"></i><span className="cal-menu__lbl">Calendar settings</span><span className="cal-menu__soon">Soon</span>
        </button>
      </div>}
    </div>);

}

/* ------------------------------------------------------------------ */
/* RangePicker — the date-range chip in the toolbar, now a button that opens a
   small month-grid date picker. Picking a day calls onPick(Date); the parent
   sets it as the anchor, from which all three views (day/week/month) plus the
   headers, month label and range chip re-derive. Closes on pick, outside-click,
   or Escape. The whole chip (calendar icon + date text) is the trigger. */
function RangePicker({ rangeLabel, anchor, onPick }) {
  const [open, setOpen] = useCalState(false);
  const [viewMonth, setViewMonth] = useCalState(() => new Date(anchor.getFullYear(), anchor.getMonth(), 1));
  const wrapRef = useCalRef(null);

  // Re-center the browsed month on the current anchor each time it opens.
  useCalEffect(() => {
    if (open) setViewMonth(new Date(anchor.getFullYear(), anchor.getMonth(), 1));
  }, [open]);

  // Close on outside-click / Escape while open.
  useCalEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  useCalEffect(() => {if (window.lucide) window.lucide.createIcons();}, [open, viewMonth]);

  const weeks = buildMonthGrid(viewMonth);
  const anchorIso = calIso(anchor);
  const stepMonth = (dir) => setViewMonth((p) => new Date(p.getFullYear(), p.getMonth() + dir, 1));
  const pick = (dateStr) => {onPick(calParseIso(dateStr));setOpen(false);};

  return (
    <div className="cal-range-wrap" ref={wrapRef}>
      <button
        type="button"
        className={'cal-range' + (open ? ' cal-range--open' : '')}
        aria-haspopup="dialog"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}>
        <i data-lucide="calendar"></i>
        <span>{rangeLabel}</span>
      </button>
      {open &&
      <div className="cal-dp" role="dialog" aria-label="Jump to date">
        <div className="cal-dp__hd">
          <button type="button" className="cal-dp__nav" aria-label="Previous month" onClick={() => stepMonth(-1)}><i data-lucide="chevron-left"></i></button>
          <span className="cal-dp__title">{MONTH_NAMES[viewMonth.getMonth()] + ' ' + viewMonth.getFullYear()}</span>
          <button type="button" className="cal-dp__nav" aria-label="Next month" onClick={() => stepMonth(1)}><i data-lucide="chevron-right"></i></button>
        </div>
        <div className="cal-dp__dows">
          {DOW_NAMES.map((d) => <span key={d} className="cal-dp__dow">{d[0]}</span>)}
        </div>
        <div className="cal-dp__grid">
          {weeks.map((wk) => wk.map((d) =>
          <button
            key={d.dateStr}
            type="button"
            className={'cal-dp__day' + (d.inMonth ? '' : ' cal-dp__day--out') + (d.today ? ' cal-dp__day--today' : '') + (d.dateStr === anchorIso ? ' cal-dp__day--sel' : '')}
            onClick={() => pick(d.dateStr)}>
            {d.num}
          </button>
          ))}
        </div>
      </div>}
    </div>);

}

/* ------------------------------------------------------------------ */
/* CalendarToolbar — row 2: month, Today, prev/next, search, filter,
   view toggle, date range, + New */
function CalendarToolbar({ view, anchorDate, onView, onNew, monthLabel, rangeLabel, onToday, onPrev, onNext, onPickDate, query, onQuery, filters, onToggleFilter, onClearFilters, canClear, onClearAll }) {
  const mutation = React.useContext(CalMutationContext);
  return (
    <div className="cal-toolbar">
      <div className="cal-tb__left">
        <span className="cal-month">{monthLabel}</span>
        <button type="button" className="cal-today" onClick={onToday}>Today</button>
        <div className="cal-nav">
          <button type="button" className="cal-navbtn" aria-label={view === 'Day' ? 'Previous day' : 'Previous week'} onClick={onPrev}><i data-lucide="chevron-left"></i></button>
          <button type="button" className="cal-navbtn" aria-label={view === 'Day' ? 'Next day' : 'Next week'} onClick={onNext}><i data-lucide="chevron-right"></i></button>
        </div>
      </div>
      <div className="cal-tb__right">
        <div className="cal-search" style={{ gap: "8px" }}>
          <i data-lucide="search"></i>
          <input type="text" placeholder="Search content..." value={query} onChange={(e) => onQuery(e.target.value)} />
        </div>
        <CalendarFilterButton filters={filters} onToggle={onToggleFilter} onClear={onClearFilters} />
        <CalendarMoreMenu canClear={canClear} onClearAll={onClearAll} />
        <div className="cal-seg" role="group" aria-label="Calendar view">
          {['Day', 'Week', 'Month'].map((v) =>
          <button
            key={v}
            type="button"
            className={view === v ? 'is-active' : ''}
            aria-pressed={view === v}
            onClick={() => onView(v)}>
              {v}
            </button>
          )}
        </div>
        <RangePicker rangeLabel={rangeLabel} anchor={anchorDate} onPick={onPickDate} />
        <button type="button" className="cal-new" disabled={!mutation.canMutate} onClick={() => {if (mutation.allows()) onNew();}} style={{ gap: "3px", padding: "0px 5px", width: "70px" }}>
          <i data-lucide="plus"></i><span>New</span>
        </button>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* CalendarActiveFilters — chip row beneath the toolbar summarizing every
   active search term / filter. Each chip removes just its own value; a
   "Clear all" appears once more than one is active. Renders nothing when
   nothing is active. The "x" is an inline SVG (React-owned) so removing a
   chip never trips the lucide/React removeChild conflict. */
function FilterChipX() {
  return (
    <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>);

}
function CalendarActiveFilters({ query, filters, onRemoveQuery, onRemoveFilter, onClearAll }) {
  const q = query.trim();
  const total = (q ? 1 : 0) + filters.status.length + filters.priority.length + filters.assigned.length;
  if (total === 0) return null;

  const chip = (key, kLabel, vLabel, onRemove, dot) =>
  <span className="cal-fchip" key={key}>
      {dot && <span className="cal-fchip__dot" style={{ background: dot }}></span>}
      <span className="cal-fchip__k">{kLabel}</span>
      <span className="cal-fchip__v">{vLabel}</span>
      <button type="button" className="cal-fchip__x" aria-label={'Remove ' + kLabel + ' ' + vLabel} onClick={onRemove}><FilterChipX /></button>
    </span>;


  return (
    <div className="cal-chips" aria-label="Active filters">
      {q && chip('q', 'Search', q, onRemoveQuery)}
      {filters.status.map((s) => chip('st-' + s, 'Status', s, () => onRemoveFilter('status', s), CAL_STATUS[s]))}
      {filters.priority.map((p) => chip('pr-' + p, 'Priority', p, () => onRemoveFilter('priority', p)))}
      {filters.assigned.map((a) => chip('as-' + a, 'Assignee', a, () => onRemoveFilter('assigned', a)))}
      {total > 1 && <button type="button" className="cal-chips__clear" onClick={onClearAll}>Clear all</button>}
    </div>);

}

/* ------------------------------------------------------------------ */
/* CalendarCard — draggable. A pointer-drag moves the card to another
   day column / time slot; a click (no drag) opens the detail modal.
   On drop we hand the new day + snapped start back up via onMove; the
   parent updates state (the single source of truth) so position, the
   visible label, and the modal all stay in sync. */
function CalendarCard({ ev, onOpen, onMove }) {
  const mutation = React.useContext(CalMutationContext);
  const t = CAL_TYPES[ev.type];
  const statusColor = CAL_STATUS[ev.status] || 'var(--rl-fg-4)';
  const evCol = calWeekday(ev.date); // this card's current column (0=Mon..6=Sun)
  const top = (ev.start - CAL_START_HOUR) * CAL_HOUR_PX + CAL_INSET;
  const height = (ev.end - ev.start) * CAL_HOUR_PX - CAL_INSET * 2;
  const duration = ev.end - ev.start; // preserved across the move
  const cardRef = useCalRef(null);
  const drag = useCalRef(null); // mutable drag session (no re-render while dragging)

  function clearDropHl(daysEl) {
    if (!daysEl) return;
    daysEl.querySelectorAll('.cal-daycol--drop').forEach((c) => c.classList.remove('cal-daycol--drop'));
  }

  function onPointerDown(e) {
    if (!mutation.allows()) return;
    if (e.pointerType === 'mouse' && e.button !== 0) return; // left button / touch only
    const cardEl = cardRef.current;
    const daysEl = cardEl.closest('.cal-days');
    if (!daysEl) return;
    const rect = daysEl.getBoundingClientRect();
    const cardRect = cardEl.getBoundingClientRect();
    const ncols = daysEl.querySelectorAll('.cal-daycol').length || 7; // 7 in Week view, 1 in Day view
    drag.current = {
      startX: e.clientX, startY: e.clientY, moved: false,
      rect, ncols, colW: rect.width / ncols,
      grabOffsetY: e.clientY - cardRect.top, // where inside the card we grabbed
      cardEl, daysEl, target: null
    };
    try {cardEl.setPointerCapture(e.pointerId);} catch (_) {}
  }

  function onPointerMove(e) {
    if (!mutation.allows()) { endDrag(e, true); return; }
    const d = drag.current;
    if (!d) return;
    const dx = e.clientX - d.startX,dy = e.clientY - d.startY;
    if (!d.moved) {
      if (Math.hypot(dx, dy) < 4) return; // ignore micro-movement so clicks still register
      d.moved = true;
      d.cardEl.classList.add('cal-card--dragging');
    }
    // target day from pointer X, clamped to the 7 visible columns
    let day = Math.floor((e.clientX - d.rect.left) / d.colW);
    day = Math.max(0, Math.min(d.ncols - 1, day));
    // target start from the card's top edge (pointer minus grab offset), snapped + clamped
    const topPx = e.clientY - d.grabOffsetY - d.rect.top - CAL_INSET;
    let start = CAL_START_HOUR + topPx / CAL_HOUR_PX;
    start = Math.round(start / CAL_SNAP) * CAL_SNAP;
    const maxStart = Math.min(CAL_LAST_SLOT, CAL_END_HOUR - duration); // no start after 5 PM; keep end inside grid
    start = Math.max(CAL_START_HOUR, Math.min(maxStart, start));
    d.target = { day, start };
    // live snapped-slot preview
    const tx = (day - evCol) * d.colW;
    const ty = (start - ev.start) * CAL_HOUR_PX;
    d.cardEl.style.transform = 'translate(' + tx + 'px, ' + ty + 'px) scale(1.02)';
    // highlight the target column
    clearDropHl(d.daysEl);
    const colEl = d.daysEl.children[day];
    if (colEl && colEl.classList.contains('cal-daycol')) colEl.classList.add('cal-daycol--drop');
  }

  function endDrag(e, cancelled) {
    const d = drag.current;
    if (!d) return;
    drag.current = null;
    try {d.cardEl.releasePointerCapture(e.pointerId);} catch (_) {}
    clearDropHl(d.daysEl);
    d.cardEl.classList.remove('cal-card--dragging');
    d.cardEl.style.transform = '';
    if (cancelled || !mutation.allows()) return; // state remains untouched
    if (!d.moved) {onOpen();return;} // it was a click, not a drag
    // valid drop only if released over the grid; otherwise revert to previous position
    const within =
    e.clientX >= d.rect.left && e.clientX <= d.rect.right &&
    e.clientY >= d.rect.top - 24 && e.clientY <= d.rect.bottom + 48;
    if (within && d.target && (d.target.day !== evCol || d.target.start !== ev.start)) {
      onMove(ev.id, d.target.day, d.target.start);
    }
  }

  useCalEffect(() => {
    if (!mutation.canMutate) endDrag({}, true);
    return () => endDrag({}, true);
  }, [mutation.canMutate]);

  return (
    <div
      ref={cardRef}
      className="cal-card"
      role="button"
      tabIndex={0}
      title={ev.status + ' · ' + ev.type}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={(e) => endDrag(e, false)}
      onPointerCancel={(e) => endDrag(e, true)}
      onClick={() => { if (!mutation.allows()) onOpen(); }}
      onKeyDown={(e) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();onOpen();}}}
      style={{ top: top + 'px', height: height + 'px', background: t.bg }}>
      <span className="cal-card__bar" style={{ background: t.bar }}></span>
      <span className="cal-card__dot" style={{ background: statusColor }}></span>
      <div className="cal-card__time" style={{ color: t.fg }}>{fmtRange(ev.start, ev.end)}</div>
      <div className="cal-card__title">{ev.title}</div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* WeekCalendarGrid */
function WeekCalendarGrid({ events, weekDays, onOpen, onMove, onSlotClick, filterType, now }) {
  const mutation = React.useContext(CalMutationContext);
  const hours = [];
  for (let h = CAL_START_HOUR; h <= CAL_LAST_SLOT; h++) hours.push(h);
  const bodyHeight = (CAL_END_HOUR - CAL_START_HOUR) * CAL_HOUR_PX;
  // Red current-time line driven by real browser-local time (refreshed each
  // minute by the parent). Only shown when the visible day/week contains the
  // actual today AND the clock is inside the drawn 8 AM–5 PM range.
  const nowAt = now || new Date();
  const nowDec = nowAt.getHours() + nowAt.getMinutes() / 60;
  const nowIso = calIso(nowAt);
  const nowInRange = nowDec >= CAL_START_HOUR && nowDec <= CAL_LAST_SLOT;
  const nowCol = weekDays.findIndex((d) => d.dateStr === nowIso); // today's column, or -1 if not visible
  const showNow = nowInRange && nowCol >= 0;
  const nowTop = (nowDec - CAL_START_HOUR) * CAL_HOUR_PX;
  // 'all' shows every type; otherwise only matching type. Cards also only appear
  // in the week that contains their due date (filtered per-column by date below).
  const visible = events.filter((ev) => filterType === 'all' || ev.type === filterType);

  // Click on empty space inside a day column -> create content prefilled at that
  // day's date + snapped time. Clicks that land on an existing card are ignored
  // here (the card handles its own open), and a click bubbling up after a drag is
  // also ignored because its target is the card element.
  function slotClick(e, dayIndex) {
    if (!mutation.allows()) return;
    if (e.target.closest('.cal-card')) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const start = snapStart(CAL_START_HOUR + (e.clientY - rect.top) / CAL_HOUR_PX);
    onSlotClick(weekDays[dayIndex].dateStr, start);
  }

  return (
    <div className="cal-grid-scroll" style={{ height: "1188px" }}>
      <div className="cal-grid">
        {/* Day headers */}
        <div className="cal-grid__head">
          <div className="cal-grid__corner"></div>
          <div className="cal-grid__days-h" style={{ gridTemplateColumns: 'repeat(' + weekDays.length + ', minmax(132px, 1fr))' }}>
            {weekDays.map((d, i) =>
            <div key={i} className={'cal-dayhd ' + (d.today ? 'cal-dayhd--today' : '')}>
                <div className="cal-dayhd__dow">{d.dow}</div>
                <div className="cal-dayhd__num">{d.num}</div>
              </div>
            )}
          </div>
        </div>

        {/* Body: time column + day columns */}
        <div className="cal-grid__body">
          <div className="cal-timecol">
            {hours.map((h) =>
            <div key={h} className="cal-timecell">
                <span>{fmtHour(h)}</span>
              </div>
            )}
          </div>
          <div className="cal-days" style={{ height: bodyHeight + 'px', gridTemplateColumns: 'repeat(' + weekDays.length + ', minmax(132px, 1fr))' }}>
            {weekDays.map((d, i) =>
            <div
              key={i}
              className={'cal-daycol ' + (d.today ? 'cal-daycol--today ' : '') + (d.weekend ? 'cal-daycol--weekend' : '')}
              onClick={(e) => slotClick(e, i)}>
                {visible.filter((ev) => ev.date === d.dateStr).map((ev) =>
              <CalendarCard key={ev.id} ev={ev} onOpen={() => onOpen(ev)} onMove={(id, col, start) => onMove(id, weekDays[col].dateStr, start)} />
              )}
              </div>
            )}
            {showNow && <div className="cal-now" style={{ top: nowTop + 'px', left: nowCol / weekDays.length * 100 + '%', width: 100 / weekDays.length + '%' }}></div>}
          </div>
        </div>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* MonthChip — compact event pill shown inside a month-grid day cell.
   Clicking opens the same editable detail modal as a week-view card. */
function MonthChip({ ev, onOpen }) {
  const t = CAL_TYPES[ev.type];
  return (
    <div
      className="cal-mchip"
      role="button"
      tabIndex={0}
      title={ev.title + ' · ' + fmtRange(ev.start, ev.end) + ' · ' + ev.status}
      style={{ background: t.bg }}
      onClick={(e) => {e.stopPropagation();onOpen();}}
      onKeyDown={(e) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();e.stopPropagation();onOpen();}}}>
      <span className="cal-mchip__bar" style={{ background: t.bar }}></span>
      <span className="cal-mchip__time" style={{ color: t.fg }}>{fmtHourShort(ev.start)}</span>
      <span className="cal-mchip__t">{ev.title}</span>
    </div>);

}

/* ------------------------------------------------------------------ */
/* MonthCalendarGrid — full-month overview. Each day cell lists its events as
   chips (capped, with a "+N more" that drills into Day view); clicking empty
   space in a cell opens the New Content modal prefilled with that due date. */
function MonthCalendarGrid({ events, monthWeeks, filterType, onOpen, onDayClick, onMore }) {
  const MAX_CHIPS = 3;
  const visible = events.filter((ev) => filterType === 'all' || ev.type === filterType);
  return (
    <div className="cal-mgrid">
      <div className="cal-mgrid__head">
        {DOW_NAMES.map((d) => <div key={d} className="cal-mgrid__dow">{d}</div>)}
      </div>
      <div className="cal-mgrid__body">
        {monthWeeks.map((week) => week.map((day) => {
          const dayEvents = visible.
          filter((ev) => ev.date === day.dateStr).
          sort((a, b) => a.start - b.start);
          const shown = dayEvents.slice(0, MAX_CHIPS);
          const extra = dayEvents.length - shown.length;
          return (
            <div
              key={day.dateStr}
              className={'cal-mcell ' + (
              day.inMonth ? '' : 'cal-mcell--out ') + (
              day.weekend ? 'cal-mcell--weekend ' : '') + (
              day.today ? 'cal-mcell--today' : '')}
              onClick={() => onDayClick(day.dateStr)}>
              <div className="cal-mcell__num">{day.num}</div>
              <div className="cal-mcell__list">
                {shown.map((ev) =>
                <MonthChip key={ev.id} ev={ev} onOpen={() => onOpen(ev)} />
                )}
                {extra > 0 &&
                <button type="button" className="cal-mmore" onClick={(e) => {e.stopPropagation();onMore(day.dateStr);}}>
                    +{extra} more
                  </button>}
              </div>
            </div>);

        }))}
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* ContentModal — "+ New" create form, or detail view of a clicked card.
   When `event` is set, fields populate from it and the header shows the
   live due date + start–end range (so a moved card reflects immediately). */
/* Reusable custom option selector — replaces the native <select> in the content
   modal with the option-list style used across the app. A hidden <input name>
   carries the chosen value, so the modal's existing form reading (buildData via
   formRef.elements) and required-field validation keep working unchanged.
   `options` is an array of strings or { value, label } objects. Self-contained:
   it owns its value (seeded from defaultValue) and re-seeds on modal remount. */
function CalSelect({ name, defaultValue, options, placeholder, invalid }) {
  const mutation = React.useContext(CalMutationContext);
  const [value, setValue] = useCalState(defaultValue == null ? '' : defaultValue);
  const [open, setOpen] = useCalState(false);
  const wrapRef = useCalRef(null);

  const opts = options.map((o) => typeof o === 'string' ? { value: o, label: o } : o);
  const current = opts.find((o) => o.value === value);

  // Close on outside-click / Escape. Escape is captured + stopped so it closes
  // only the dropdown, never the parent modal, while the menu is open.
  useCalEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') {e.stopPropagation();setOpen(false);}};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey, true);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey, true);};
  }, [open]);

  useCalEffect(() => {if (window.lucide) window.lucide.createIcons();}, [open, value]);

  const pick = (v) => {if (!mutation.allows()) return;setValue(v);setOpen(false);};

  return (
    <div className="cal-csel" ref={wrapRef}>
      <input type="hidden" name={name} value={value} readOnly />
      <button
        type="button"
        className={'cal-csel__trigger' + (open ? ' cal-csel__trigger--open' : '') + (current ? '' : ' cal-csel__trigger--empty')}
        disabled={!mutation.canMutate}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-invalid={invalid ? 'true' : undefined}
        onClick={() => {if (mutation.allows()) setOpen((o) => !o);}}>
        <span>{current ? current.label : placeholder || 'Select'}</span>
        <i data-lucide="chevron-down" className="cal-csel__caret"></i>
      </button>
      {open && mutation.canMutate &&
      <div className="cal-csel__menu" role="listbox">
        {opts.map((o) =>
        <button
          key={o.value}
          type="button"
          role="option"
          aria-selected={o.value === value}
          className={'cal-csel__opt' + (o.value === value ? ' cal-csel__opt--on' : '')}
          onClick={() => pick(o.value)}>
          <span className="cal-csel__radio"></span>
          <span className="cal-csel__label">{o.label}</span>
        </button>
        )}
      </div>}
    </div>);

}

/* Reusable app-styled date picker for the modal's Due date field. Replaces the
   native <input type="date">. A hidden <input name> carries the YYYY-MM-DD value
   so buildData()/validation and calendar placement keep working unchanged.
   Behaviors: pick closes; Clear empties; Today selects the real local today;
   closes on outside-click / Escape (Escape stops at the picker, not the modal). */
function CalDateField({ name, defaultValue, invalid }) {
  const mutation = React.useContext(CalMutationContext);
  const [value, setValue] = useCalState(defaultValue || '');
  const [open, setOpen] = useCalState(false);
  const [viewMonth, setViewMonth] = useCalState(() => {
    const base = defaultValue ? calParseIso(defaultValue) : calToday();
    return new Date(base.getFullYear(), base.getMonth(), 1);
  });
  const wrapRef = useCalRef(null);

  // Re-center the browsed month on the selected value (or today) each time it opens.
  useCalEffect(() => {
    if (!open) return;
    const base = value ? calParseIso(value) : calToday();
    setViewMonth(new Date(base.getFullYear(), base.getMonth(), 1));
  }, [open]);

  useCalEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') {e.stopPropagation();setOpen(false);}};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey, true);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey, true);};
  }, [open]);

  useCalEffect(() => {if (window.lucide) window.lucide.createIcons();}, [open, viewMonth, value]);

  const weeks = buildMonthGrid(viewMonth);
  const stepMonth = (dir) => setViewMonth((p) => new Date(p.getFullYear(), p.getMonth() + dir, 1));
  const pick = (dateStr) => {if (!mutation.allows()) return;setValue(dateStr);setOpen(false);};
  const clearDate = () => pick('');
  const pickToday = () => pick(calIso(calToday()));

  const display = value ? calDateLabel(value) + ', ' + calParseIso(value).getFullYear() : 'Select a date';

  return (
    <div className="cal-df" ref={wrapRef}>
      <input type="hidden" name={name} value={value} readOnly />
      <button
        type="button"
        className={'cal-df__trigger' + (open ? ' cal-df__trigger--open' : '') + (value ? '' : ' cal-df__trigger--empty')}
        disabled={!mutation.canMutate}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-invalid={invalid ? 'true' : undefined}
        onClick={() => {if (mutation.allows()) setOpen((o) => !o);}}>
        <i data-lucide="calendar" className="cal-df__ic"></i>
        <span>{display}</span>
      </button>
      {open && mutation.canMutate &&
      <div className="cal-df__pop" role="dialog" aria-label="Choose due date" style={{ width: "250px" }}>
        <div className="cal-df__hd">
          <button type="button" className="cal-df__nav" aria-label="Previous month" onClick={() => stepMonth(-1)}><i data-lucide="chevron-left"></i></button>
          <span className="cal-df__title">{MONTH_NAMES[viewMonth.getMonth()] + ' ' + viewMonth.getFullYear()}</span>
          <button type="button" className="cal-df__nav" aria-label="Next month" onClick={() => stepMonth(1)}><i data-lucide="chevron-right"></i></button>
        </div>
        <div className="cal-df__dows">{DOW_NAMES.map((d) => <span key={d} className="cal-df__dow">{d[0]}</span>)}</div>
        <div className="cal-df__grid">
          {weeks.map((wk) => wk.map((d) =>
          <button
            key={d.dateStr}
            type="button"
            className={'cal-df__day' + (d.inMonth ? '' : ' cal-df__day--out') + (d.today ? ' cal-df__day--today' : '') + (d.dateStr === value ? ' cal-df__day--sel' : '')}
            onClick={() => pick(d.dateStr)}>
            {d.num}
          </button>
          ))}
        </div>
        <div className="cal-df__ft">
          <button type="button" className="cal-df__link" onClick={clearDate}>Clear</button>
          <button type="button" className="cal-df__link" onClick={pickToday}>Today</button>
        </div>
      </div>}
    </div>);

}

/* Reusable app-styled time picker for the modal's Start/End time fields. Replaces
   the native <input type="time">. A hidden <input name> carries the "HH:MM" value
   (or "" when unset) so optional-time behavior, auto-placement, and the End<=Start
   correction in buildData() all keep working. The whole field is the trigger, so
   clicking anywhere in it (icon included) opens the picker. */
function CalTimeField({ name, defaultValue, placeholder }) {
  const mutation = React.useContext(CalMutationContext);
  const [value, setValue] = useCalState(defaultValue || '');
  const [open, setOpen] = useCalState(false);
  const wrapRef = useCalRef(null);
  const listRef = useCalRef(null);

  useCalEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') {e.stopPropagation();setOpen(false);}};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey, true);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey, true);};
  }, [open]);

  // On open, center the selected option in the scroll list (no scrollIntoView).
  useCalEffect(() => {
    if (open && listRef.current) {
      const on = listRef.current.querySelector('.cal-tf__opt--on');
      if (on) listRef.current.scrollTop = on.offsetTop - listRef.current.clientHeight / 2 + on.clientHeight / 2;
    }
    if (window.lucide) window.lucide.createIcons();
  }, [open, value]);

  const opts = calTimeOptions();
  const current = opts.find((o) => o.value === value);
  const display = current ? current.label : value ? fmtHour(parseTime(value, CAL_START_HOUR)) : placeholder || 'Select a time';
  const pick = (v) => {if (!mutation.allows()) return;setValue(v);setOpen(false);};

  return (
    <div className="cal-tf" ref={wrapRef}>
      <input type="hidden" name={name} value={value} readOnly />
      <button
        type="button"
        className={'cal-tf__trigger' + (open ? ' cal-tf__trigger--open' : '') + (value ? '' : ' cal-tf__trigger--empty')}
        disabled={!mutation.canMutate}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => {if (mutation.allows()) setOpen((o) => !o);}}>
        <i data-lucide="clock" className="cal-tf__ic"></i>
        <span>{display}</span>
      </button>
      {open && mutation.canMutate &&
      <div className="cal-tf__pop" role="dialog" aria-label="Choose time">
        <div className="cal-tf__list" ref={listRef} role="listbox">
          {opts.map((o) =>
          <button
            key={o.value}
            type="button"
            role="option"
            aria-selected={o.value === value}
            className={'cal-tf__opt' + (o.value === value ? ' cal-tf__opt--on' : '')}
            onClick={() => pick(o.value)}>
            {o.label}
          </button>
          )}
        </div>
      </div>}
    </div>);

}

/* ------------------------------------------------------------------ */
function ContentModal({ open, event, prefill, activeTab, onClose, onCreate, onSave, onDelete, onStartBrief }) {
  const mutation = React.useContext(CalMutationContext);
  const formRef = useCalRef(null);
  const [confirmDelete, setConfirmDelete] = useCalState(false);
  const [errors, setErrors] = useCalState({}); // per-field required-validation messages
  useCalEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    document.addEventListener('keydown', onKey);
    if (window.lucide) window.lucide.createIcons();
    return () => document.removeEventListener('keydown', onKey);
  }, [open, event]);

  // Re-render lucide icons when the footer toggles into confirm state.
  useCalEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, [confirmDelete]);

  // Reset the delete-confirm whenever the modal opens or switches target,
  // so a prior confirm state never leaks into the next open (the component
  // returns null while closed but stays mounted, so state persists).
  useCalEffect(() => {
    setConfirmDelete(false);
    setErrors({});
  }, [open, event && event.id]);

  if (!open) return null;

  const editing = !!event;
  // Date default: the clicked slot/day's date, else today.
  const defDate = !editing ? prefill ? prefill.date : calTodayIso() : calTodayIso();
  // Default post type follows the active tab so the new card stays visible after
  // creation; falls back to Guide on the "All Content" tab.
  const defType = activeTab && activeTab !== 'all' ? activeTab : 'Guide';
  // Time fields prefill ONLY when a specific time slot was clicked (prefill.start
  // is a number). A Month day-cell click or the "+ New" button leaves them blank
  // (date-only) so the card auto-schedules into the next free slot on save.
  const hasPrefillTime = !editing && prefill && prefill.start != null;

  const dateVal = editing ? event.date : defDate;
  const timeVal = editing ? hhmm(event.start) : hasPrefillTime ? hhmm(prefill.start) : '';
  const endVal = editing ? hhmm(event.end) : hasPrefillTime ? hhmm(Math.min(CAL_END_HOUR, prefill.start + 1)) : '';
  const subtitle = editing ? calDateLabel(event.date) + ' · ' + fmtRange(event.start, event.end) : null;
  const keySuffix = editing ? event.id : 'new-' + defDate + '-' + (hasPrefillTime ? prefill.start : 'd');

  // Build the event payload from the form. Start/End are OPTIONAL: when Start is
  // blank we flag autoTime so the page auto-places the card in the next free slot.
  // When Start is set but End is blank or <= Start, End is corrected to 1h later.
  function buildData() {
    const els = formRef.current.elements;
    const startRaw = els.start.value;
    const endRaw = els.end.value;
    let start = null,end = null,autoTime = false;
    if (!startRaw) {
      autoTime = true; // no time chosen -> auto-place into the grid on save
    } else {
      start = snapStart(parseTime(startRaw, CAL_START_HOUR));
      if (!endRaw) {
        end = Math.min(CAL_END_HOUR, start + 1);
      } else {
        end = Math.round(parseTime(endRaw, start + 1) / CAL_SNAP) * CAL_SNAP;
        if (!(end > start)) end = Math.min(CAL_END_HOUR, start + 1); // correct end <= start
      }
      end = Math.min(CAL_END_HOUR, end);
    }
    return {
      date: els.due.value || dateVal,
      start, end, autoTime,
      title: els.title.value.trim(),
      primaryKeyword: els.keyword.value.trim(),
      type: els.type.value || defType,
      status: els.status.value || 'Planned',
      priority: els.priority.value,
      assigned: els.assigned.value,
      notes: els.notes.value
    };
  }
  // Required: Content title, Content type, Primary keyword, Due date.
  function submit() {
    if (!mutation.allows()) return;
    const data = buildData();
    const errs = {};
    if (!data.title) errs.title = 'Content title is required.';
    if (!data.type) errs.type = 'Content type is required.';
    if (!data.primaryKeyword) errs.keyword = 'Primary keyword is required.';
    if (!data.date) errs.due = 'Due date is required.';
    if (Object.keys(errs).length) {setErrors(errs);return;}
    setErrors({});
    if (editing) onSave(event.id, data);else onCreate(data);
  }
  function handleCreate() {submit();}
  function handleSave() {submit();}

  // Hand the card's current detail off to the AI Writer / Brief page. Reads the
  // live form fields so any unsaved edits in the modal carry over. Maps:
  // Topic = title, Post type = type, Primary keyword = keyword, Additional
  // information = notes (left empty when the card has no notes).
  function handleStartBrief() {
    if (!mutation.allows() || !mutation.allows('canUseAi')) return;
    const els = formRef.current.elements;
    onStartBrief && onStartBrief({
      topic: els.title.value.trim(),
      postType: els.type.value || '',
      keyword: els.keyword.value.trim(),
      notes: els.notes.value.trim()
    });
  }

  return (
    <div className="cal-scrim" onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}>
      <div className="cal-modal" key={keySuffix} role="dialog" aria-modal="true" aria-label={editing ? 'Content details' : 'New content'}>
        <div className="cal-modal__hd">
          <div>
            <h3>{editing ? 'Content details' : 'New content'}</h3>
            {subtitle && <p className="cal-modal__sub">{subtitle}</p>}
          </div>
          <button type="button" className="cal-modal__x" aria-label="Close" onClick={onClose}>
            <i data-lucide="x"></i>
          </button>
        </div>
        <form ref={formRef} className="cal-modal__body" onSubmit={(e) => {e.preventDefault();submit();}}>
          <div className="cal-fld cal-fld--full">
            <label>Content title<span className="cal-req" aria-hidden="true">*</span></label>
            <input type="text" name="title" readOnly={!mutation.canMutate} placeholder="e.g. Draft SaaS SEO Guide" defaultValue={editing ? event.title : ''} aria-invalid={errors.title ? 'true' : undefined} />
            {errors.title && <span className="cal-fld__err">{errors.title}</span>}
          </div>

          <div className="cal-fld">
            <label>Content type<span className="cal-req" aria-hidden="true">*</span></label>
            <CalSelect name="type" defaultValue={editing ? event.type : defType} options={POST_TYPES} placeholder="Select type" invalid={!!errors.type} />
            {errors.type && <span className="cal-fld__err">{errors.type}</span>}
          </div>
          <div className="cal-fld">
            <label>Primary keyword<span className="cal-req" aria-hidden="true">*</span></label>
            <input type="text" name="keyword" readOnly={!mutation.canMutate} placeholder="e.g. best crm software" defaultValue={editing && event.primaryKeyword ? event.primaryKeyword : ''} aria-invalid={errors.keyword ? 'true' : undefined} />
            {errors.keyword && <span className="cal-fld__err">{errors.keyword}</span>}
          </div>

          <div className="cal-fld">
            <label>Due date<span className="cal-req" aria-hidden="true">*</span></label>
            <CalDateField name="due" defaultValue={dateVal} invalid={!!errors.due} />
            {errors.due && <span className="cal-fld__err">{errors.due}</span>}
          </div>
          <div className="cal-fld">
            <label>Assigned to<span className="cal-opt">optional</span></label>
            <CalSelect
              name="assigned"
              defaultValue={editing && event.assigned ? event.assigned : ''}
              options={[
              { value: '', label: 'Unassigned' },
              'Jamie Doyle', 'Olivia Carter', 'Ethan Nguyen', 'Sophie Bennett']}
              placeholder="Unassigned" />
          </div>

          <div className="cal-fld">
            <label>Status<span className="cal-opt">optional</span></label>
            <CalSelect name="status" defaultValue={editing ? event.status : 'Planned'} options={['Draft', 'Review', 'Scheduled', 'Planned']} />
          </div>
          <div className="cal-fld">
            <label>Priority<span className="cal-opt">optional</span></label>
            <CalSelect name="priority" defaultValue={editing ? event.priority || 'Medium' : 'Low'} options={['Low', 'Medium', 'High']} />
          </div>

          <div className="cal-fld">
            <label>Start time<span className="cal-opt">optional</span></label>
            <CalTimeField name="start" defaultValue={timeVal} placeholder="Select a time" />
          </div>
          <div className="cal-fld">
            <label>End time<span className="cal-opt">optional</span></label>
            <CalTimeField name="end" defaultValue={endVal} placeholder="Select a time" />
          </div>
          <div className="cal-fld cal-fld--full cal-fld--hint">
            <span>Leave the time blank to auto-schedule into the next free slot on the due date.</span>
          </div>

          <div className="cal-fld cal-fld--full">
            <label>Notes<span className="cal-opt">optional</span></label>
            <textarea name="notes" readOnly={!mutation.canMutate} placeholder="Add any details, links, or context for this content piece." defaultValue={editing && event.notes ? event.notes : ''}></textarea>
          </div>
        </form>
        <div className="cal-modal__ft">
          {editing && confirmDelete ?
          <div className="cal-modal__confirm">
              <span className="cal-modal__confirm-msg">Delete this content? This can’t be undone.</span>
              <button type="button" className="cal-btn cal-btn--ghost" onClick={() => setConfirmDelete(false)}>Keep</button>
              <button type="button" className="cal-btn cal-btn--danger-solid" disabled={!mutation.canMutate} onClick={() => {if (mutation.allows()) onDelete(event.id);}}>Delete</button>
            </div> :
          <React.Fragment>
              {editing &&
            <button type="button" className="cal-btn cal-btn--danger cal-modal__del" disabled={!mutation.canMutate} onClick={() => {if (mutation.allows()) setConfirmDelete(true);}}>
                  <i data-lucide="trash-2"></i><span>Delete</span>
                </button>}
              <button type="button" className="cal-btn cal-btn--ghost" onClick={onClose}>Cancel</button>
              {editing &&
            <button type="button" className="cal-btn cal-btn--ghost cal-modal__brief" disabled={!mutation.canMutate || !mutation.allows('canUseAi')} onClick={handleStartBrief}>
                  <i data-lucide="sparkles"></i><span>Start Brief</span>
                </button>}
              <button type="button" className="cal-btn cal-btn--primary" disabled={!mutation.canMutate} onClick={editing ? handleSave : handleCreate}>{editing ? 'Save' : 'Create'}</button>
            </React.Fragment>}
        </div>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* CalendarPage — top-level page */
/* ------------------------------------------------------------------ */
/* CalendarSummaryPanel — permanent right-side rail summarizing the calendar.
   Date-scoped (not affected by tab/search): "Upcoming this week" lists up to 8
   items from the week containing the anchor. Rows open the same detail modal as
   a calendar card. */
function CalendarSummaryPanel({ events, anchorDate, onOpen }) {
  // "Upcoming this week" — the Mon–Sun week containing the anchor date.
  const weekStart = calStartOfWeek(anchorDate);
  const weekSet = new Set(Array.from({ length: 7 }, (_, i) => calIso(calAddDays(weekStart, i))));
  const upcoming = events.
  filter((e) => weekSet.has(e.date)).
  sort((a, b) => a.date === b.date ? a.start - b.start : a.date < b.date ? -1 : 1).
  slice(0, 8);

  useCalEffect(() => {if (window.lucide) window.lucide.createIcons();}, [events, anchorDate]);

  return (
    <aside className="cal-aside" aria-label="Calendar summary">
      <div className="cal-sumcard">
        <div className="cal-sumcard__hd"><i data-lucide="calendar-clock"></i><span>Upcoming this week</span></div>
        {upcoming.length === 0 ?
        <div className="cal-up-empty">No scheduled content this week.</div> :
        <div className="cal-up-list">
          {upcoming.map((ev) => {
            const d = calParseIso(ev.date);
            const when = DOW_FULL[(d.getDay() + 6) % 7] + ', ' + fmtHour(ev.start);
            return (
              <button type="button" className="cal-up" key={ev.id} onClick={() => onOpen(ev)}>
                <div className="cal-up__when">{when}</div>
                <div className="cal-up__title">{ev.title}</div>
                <div className="cal-up__type"><span className="cal-up__dot" style={{ background: CAL_TYPES[ev.type].bar }}></span>{ev.type}</div>
              </button>);

          })}
        </div>}
      </div>
    </aside>);

}

/* ------------------------------------------------------------------ */
/* CalendarPage — top-level page */
function CalendarPage({ onStartBrief, workspaceId }) {
  ensureCalStyles();
  const access = useWorkspaceAccessUi();
  const scopeActive = useCalRef(true);
  const scopeId = useCalRef(workspaceId || access.workspaceId);
  const allows = (capability = 'canMutateWorkspaceContent') => scopeActive.current && access.workspaceId === scopeId.current && access.allows(capability);
  const canMutate = allows();
  const [tab, setTab] = useCalState('all');
  const [view, setView] = useCalState('Week');
  // Events live in state (single source of truth) so drag-and-drop persists
  // in-session and is easy to swap for a Supabase-backed store later.
  const [events, setEvents] = useCalState(loadCalendarEvents);
  // The focused day. Week view shows the Mon–Sun week containing it; Day view
  // shows just this day. Navigation steps by 1 day (Day) or 7 days (Week).
  const [anchorDate, setAnchorDate] = useCalState(() => calToday());
  const [selectedId, setSelectedId] = useCalState(null); // clicked card id, or null for "+ New"
  const [slotPrefill, setSlotPrefill] = useCalState(null); // {date, start} when opened from an empty slot
  const [modalOpen, setModalOpen] = useCalState(false);
  const [query, setQuery] = useCalState(''); // free-text search across all visible content
  const [filters, setFilters] = useCalState({ status: [], priority: [], assigned: [] }); // Filter popover selections
  useCalEffect(() => {
    const clearScope = () => {
      scopeActive.current = false;
      setModalOpen(false);
      setEvents([]);
      setSelectedId(null);
      setSlotPrefill(null);
      setQuery('');
      setFilters({ status: [], priority: [], assigned: [] });
    };
    window.addEventListener('ranklyx:workspace-switching', clearScope);
    return () => {scopeActive.current = false;window.removeEventListener('ranklyx:workspace-switching', clearScope);};
  }, []);
  // Real wall-clock time, refreshed every minute, drives the red "now" line.
  useCalEffect(() => {
    // A failed switch can reconfirm this Workspace without a reload. Restore
    // only the original examples, never a blocked action or another scope's edits.
    if (!scopeActive.current && access.workspaceId === scopeId.current && access.status !== 'loading') {
      scopeActive.current = true;
      setEvents(loadCalendarEvents());
    }
  }, [access.workspaceId, access.status]);
  const [now, setNow] = useCalState(() => new Date());
  useCalEffect(() => {
    const id = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(id);
  }, []);

  const weekDays = view === 'Day' ?
  [buildDayDescriptor(anchorDate)] :
  buildWeekDays(calStartOfWeek(anchorDate));

  // Month view derives its own grid + labels from the anchor's month.
  const isMonth = view === 'Month';
  const monthWeeks = isMonth ? buildMonthGrid(anchorDate) : null;
  const monthLabel = isMonth ? MONTH_NAMES[anchorDate.getMonth()] + ' ' + anchorDate.getFullYear() : calMonthLabel(weekDays);
  const rangeLabel = isMonth ? calMonthRangeLabel(anchorDate) : calRangeLabel(weekDays);

  // Navigation: Day steps ±1 day, Week ±7 days, Month ±1 calendar month.
  const gotoToday = () => setAnchorDate(calToday());
  const stepMonth = (prev, dir) => new Date(prev.getFullYear(), prev.getMonth() + dir, 1);
  const gotoPrev = () => setAnchorDate((prev) => view === 'Month' ? stepMonth(prev, -1) : calAddDays(prev, view === 'Day' ? -1 : -7));
  const gotoNext = () => setAnchorDate((prev) => view === 'Month' ? stepMonth(prev, 1) : calAddDays(prev, view === 'Day' ? 1 : 7));

  const openNew = () => {if (!allows()) return;setSelectedId(null);setSlotPrefill(null);setModalOpen(true);};
  const openSlot = (date, start) => {if (!allows()) return;setSelectedId(null);setSlotPrefill({ date, start });setModalOpen(true);};
  const openEvent = (ev) => {if (!scopeActive.current) return;setSelectedId(ev.id);setSlotPrefill(null);setModalOpen(true);};
  const closeModal = () => setModalOpen(false);

  // Add a brand-new card to the same events state the existing cards live in.
  // If the modal flagged autoTime (no Start chosen), place it in the next free
  // slot on its due date so every card lands inside the grid.
  const createEvent = (data) => {
    if (!allows()) return;
    const { autoTime, ...rest } = data;
    setEvents((prev) => {
      const placed = autoTime ? { ...rest, ...autoPlaceSlot(prev, rest.date, 1) } : rest;
      return createCalendarEvent(prev, placed);
    });
    setModalOpen(false);
  };

  // Save edits from the detail modal back into events state (repositions the
  // card if day/time changed, recolors + refilters if the type changed). If the
  // user cleared Start/End, auto-place against the other events on that day.
  const updateEvent = (id, data) => {
    if (!allows()) return;
    const { autoTime, ...rest } = data;
    setEvents((prev) => {
      const placed = autoTime ? { ...rest, ...autoPlaceSlot(prev.filter((e) => e.id !== id), rest.date, 1) } : rest;
      return updateCalendarEvent(prev, id, placed);
    });
    setModalOpen(false);
  };

  // Remove a card from events state; it disappears from the calendar immediately.
  const deleteEvent = (id) => {
    if (!allows()) return;
    setEvents((prev) => deleteCalendarEvent(prev, id));
    setModalOpen(false);
  };

  // Move = new date + snapped start; duration (end - start) is preserved.
  const moveEvent = (id, date, start) => {
    if (!allows()) return;
    setEvents((prev) => moveCalendarEvent(prev, id, date, start));
  };
  const startBrief = (fields) => {
    if (!allows() || !allows('canUseAi')) return;
    const scope = window.ClicklyxWebsiteContext;
    if (scope && !scope.allows()) return;
    const origin = scope && scope.capture();
    if (onStartBrief) onStartBrief(origin ? { ...fields, requestOrigin: origin } : fields);
  };

  // Filter popover handlers: toggle one value in a section, or clear all.
  const toggleFilter = (section, value) => setFilters((prev) => {
    const has = prev[section].includes(value);
    return { ...prev, [section]: has ? prev[section].filter((v) => v !== value) : [...prev[section], value] };
  });
  const clearFilters = () => setFilters({ status: [], priority: [], assigned: [] });
  // Clear everything at once (search + all filter sections).
  const clearAll = () => {setQuery('');clearFilters();};


  // Always read the live event from state so the modal reflects a just-moved card.
  const selectedLive = selectedId ? events.find((e) => e.id === selectedId) || null : null;

  // Search + Filter combine: an event must match the free-text query AND the
  // structured Filter popover selections to be shown. Applied across Day / Week /
  // Month before the grids see the events; the active tab is applied per-grid.
  const q = query.trim().toLowerCase();
  const hasFilters = filtersActive(filters);
  const filtered = events.filter((e) => eventMatchesQuery(e, q) && eventMatchesFilters(e, filters));

  // Empty-state detection: are there zero matching cards in the dates currently
  // on screen? Surfaced whenever a search or filter is active (so an ordinarily
  // empty day still shows its time grid).
  const visibleDates = isMonth ?
  new Set(monthWeeks.reduce((acc, wk) => acc.concat(wk.map((d) => d.dateStr)), [])) :
  new Set(weekDays.map((d) => d.dateStr));
  const visibleMatchCount = filtered.
  filter((e) => tab === 'all' || e.type === tab).
  filter((e) => visibleDates.has(e.date)).length;
  const showEmpty = (q.length > 0 || hasFilters) && visibleMatchCount === 0;
  const emptyKind = q && hasFilters ? 'search and filters' : q ? 'search' : 'filters';

  useCalEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, [tab, view, modalOpen, events, anchorDate, query, filters]);

  return (
    <CalMutationContext.Provider value={{ canMutate, allows }}>
    <div className="rl-page cal-page" data-screen-label="Content Calendar" data-calendar-mutable={canMutate}>
      <div className="cal-inner-wrap">
        <div className="cal-head">
        <CalendarHeader />
        <CalendarTabs active={tab} onSelect={setTab} />
        <CalendarToolbar view={view} anchorDate={anchorDate} onView={setView} onNew={openNew} monthLabel={monthLabel} rangeLabel={rangeLabel} onToday={gotoToday} onPrev={gotoPrev} onNext={gotoNext} onPickDate={(d) => setAnchorDate(d)} query={query} onQuery={setQuery} filters={filters} onToggleFilter={toggleFilter} onClearFilters={clearFilters} canClear={q.length > 0 || hasFilters} onClearAll={clearAll} />
        <CalendarActiveFilters query={query} filters={filters} onRemoveQuery={() => setQuery('')} onRemoveFilter={toggleFilter} onClearAll={clearAll} />
        </div>
        <div className="cal-board-row" style={{ gap: "50px" }}>
        <div className="cal-board">
        {showEmpty ?
          <div className="cal-empty">
          <span className="cal-empty__icon"><i data-lucide="search-x"></i></span>
          <div className="cal-empty__title">No content found.</div>
          <div className="cal-empty__sub">Nothing in this view matches your {emptyKind}. Try adjusting or clearing them.</div>
        </div> :
          isMonth ?
          <MonthCalendarGrid
            events={filtered}
            monthWeeks={monthWeeks}
            filterType={tab}
            onOpen={openEvent}
            onDayClick={(date) => openSlot(date, null)}
            onMore={(date) => {setView('Day');setAnchorDate(calParseIso(date));}} /> :

          <WeekCalendarGrid events={filtered} weekDays={weekDays} onOpen={openEvent} onMove={moveEvent} onSlotClick={openSlot} filterType={tab} now={now} />}
        </div>
        <CalendarSummaryPanel events={events} anchorDate={anchorDate} onOpen={openEvent} />
        </div>
      </div>
      <ContentModal open={modalOpen} event={selectedLive} prefill={slotPrefill} activeTab={tab} onClose={closeModal} onCreate={createEvent} onSave={updateEvent} onDelete={deleteEvent} onStartBrief={startBrief} />
    </div>
    </CalMutationContext.Provider>);

}

window.CalendarPage = CalendarPage;
