/* calendar.jsx: the real Calendar module (free with every plan).
 * A month grid of everything the club is doing, a "Coming up" list, and a private subscription link that Google, Outlook,
 * Apple and Zoho calendars can follow without a Clubcraft login. The server expands repeats (GET /club/calendar?from&to), so
 * this file only draws what it is given. Club admins and people with Edit access add and edit items; everyone else views.
 * Other apps hand dates over through window.CCCalendarHandoff (set in comms.jsx): {source_type, source_id, name, items:[{title, date, end, notes}]}.
 * The page asks before adding them, and sending the same plan again replaces its earlier items.
 * Exposes window.CCCalendar; shell.jsx mounts it on the Calendar page when not in demo mode.
 */
(function () {
  const h = React.createElement;
  const API = window.ClubcraftApi;

  const KINDS = { Meeting: "#17458F", Event: "#d2603a", Task: "#2f7d4f", Post: "#7a52c7", Club: "#9a6a08", Personal: "#0e7490" };
  const KIND_LABEL = { Meeting: "Meetings", Event: "Events", Task: "Tasks", Post: "Posts", Club: "Club", Personal: "Personal" };
  const SHARING = [["me", "Just me"], ["club", "The whole club"], ["people", "Selected people"]];
  const REPEATS = [["", "Does not repeat"], ["weekly", "Every week"], ["fortnightly", "Every 2 weeks"], ["monthly_nth", "Monthly, on the same weekday"]];
  const DAY = 86400000;

  const dateOf = (iso) => new Date(iso + "T12:00:00");
  const isoOf = (d) => d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
  const fmtDay = (iso) => dateOf(iso).toLocaleDateString(CCIntl.locale(), { weekday: "short", day: "numeric", month: "short" });
  const fmtTime = (t) => { if (!t) return ""; const [hh, mm] = t.split(":").map(Number); return (hh % 12 || 12) + (mm ? ":" + String(mm).padStart(2, "0") : "") + (hh < 12 ? "am" : "pm"); };
  const zoneNow = () => CCIntl.timezone();      // always the club's own zone (My club); the calendar has none of its own
  // The member's second time zone, if they have one: "10pm Honolulu" for a club-time start.
  const alsoAt = (iso, t) => CCIntl.alsoTime(iso, t, zoneNow());
  const alsoShort = (iso, t) => CCIntl.alsoTime(iso, t, zoneNow(), true);      // "10pm" for the narrow month cells
  const workFromNow = () => CCIntl.workingFrom(zoneNow());
  const timeRange = (o) => (o.startTime ? fmtTime(o.startTime) + (o.endTime ? " to " + fmtTime(o.endTime) : "") + (alsoAt(o.date || o.startDate, o.startTime) ? " (" + alsoAt(o.date || o.startDate, o.startTime) + ")" : "") : "All day");
  const repeatLabel = (r) => (REPEATS.find((x) => x[0] === r) || [0, ""])[1];

  const pad2 = (n) => String(n).padStart(2, "0");
  const toMin = (t) => { const [hh, mm] = t.split(":").map(Number); return hh * 60 + mm; };
  const fromMin = (m) => (m >= 24 * 60 ? "23:59" : pad2(Math.floor(m / 60)) + ":" + pad2(m % 60));
  /* New items are timed and run one hour: the next whole hour for today, 9am for any other day. */
  const defaultStart = (iso, today) => { const n = new Date().getHours() + 1; return iso === today && n < 23 ? pad2(n) + ":00" : "09:00"; };
  const EMPTY = { id: null, title: "", kind: "Meeting", startDate: "", endDate: "", allDay: false, startTime: "09:00", endTime: "10:00", location: "", notes: "", repeat: "", repeatUntil: "", reminders: null, sharing: "me", sharedWith: [], canEdit: true, mine: true };
  const toForm = (o) => ({ canEdit: o.canEdit !== false, mine: !!o.mine, ownerName: o.ownerName || "", sharing: o.sharing || "me", sharedWith: o.sharedWith || [], id: o.id, title: o.title, kind: o.kind, startDate: o.startDate, endDate: o.endDate || "", allDay: !o.startTime, startTime: o.startTime || "09:00", endTime: o.endTime || (o.startTime ? "" : "10:00"), location: o.location, notes: o.notes, repeat: o.repeat, repeatUntil: o.repeatUntil || "", reminders: o.reminders == null ? null : o.reminders, source: o.source });
  const toBody = (f) => ({ title: f.title, kind: f.kind, startDate: f.startDate, endDate: f.endDate && f.endDate !== f.startDate ? f.endDate : "", startTime: f.allDay ? "" : f.startTime, endTime: f.allDay ? "" : f.endTime, location: f.location, notes: f.notes, repeat: f.repeat, repeatUntil: f.repeat ? f.repeatUntil : "", reminders: f.reminders, ...(f.kind === "Personal" ? { sharing: f.sharing, sharedWith: f.sharing === "people" ? f.sharedWith : [] } : {}) });
  const REMINDERS = [[0, "At the start"], [10, "10 minutes before"], [30, "30 minutes before"], [60, "1 hour before"], [120, "2 hours before"], [1440, "1 day before"], [2880, "2 days before"], [10080, "1 week before"]];
  const remLabel = (m) => (REMINDERS.find((r) => r[0] === m) || [0, m + " minutes before"])[1].toLowerCase();
  const remText = (list) => (list.length ? list.map(remLabel).join(", ") : "no reminders");

  /* A list of reminders, each a choice from the list; up to five. */
  function Reminders({ value, onChange, disabled }) {
    const used = new Set(value);
    const next = REMINDERS.map((r) => r[0]).find((m) => !used.has(m) && m !== 0);
    return h("div", { className: "cc-rem" },
      value.map((m, i) => h("div", { key: i, className: "cc-row", style: { gap: 6, marginBottom: 6 } },
        h("select", { value: m, disabled, "aria-label": "Reminder " + (i + 1), onChange: (e) => onChange(value.map((x, j) => (j === i ? Number(e.target.value) : x))) },
          REMINDERS.filter((r) => r[0] === m || !used.has(r[0])).map(([v, l]) => h("option", { key: v, value: v }, l))),
        !disabled && h("button", { type: "button", className: "cc-btn sm ghost", "aria-label": "Remove reminder " + (i + 1), onClick: () => onChange(value.filter((_, j) => j !== i)) }, "✕"))),
      !disabled && value.length < 5 && next != null && h("button", { type: "button", className: "cc-btn sm", onClick: () => onChange(value.concat(next)) }, "Add a reminder"),
      value.length === 0 && h("p", { className: "cc-muted sm", style: { margin: "2px 0" } }, "No reminders."));
  }

  /* ---------- add / edit / view one item ---------- */
  function ItemModal({ clubId, form, editor, members, defaults, onClose, onSaved }) {
    const [f, setF] = React.useState(form);
    const canEdit = form.canEdit;                                  // this item: the owner of a Personal entry, or an editor for club items
    const fromApp = f.source && (f.source.type === "Tasks" || f.source.type === "Social");
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const set = (k, v) => setF((x) => ({ ...x, [k]: v }));
    // Changing the start moves the end with it, so the length stays the same (one hour for a new item).
    const setStart = (t) => setF((x) => {
      const len = x.startTime && x.endTime && toMin(x.endTime) > toMin(x.startTime) ? toMin(x.endTime) - toMin(x.startTime) : 60;
      return { ...x, startTime: t, endTime: t ? fromMin(toMin(t) + len) : x.endTime };
    });
    const bind = (k) => ({ value: f[k], onChange: (e) => set(k, e.target.value), disabled: !canEdit });
    async function save() {
      setBusy(true); setErr(null);
      try {
        await API.call(f.id ? "PATCH" : "POST", "/club/calendar" + (f.id ? "/" + f.id : ""), toBody(f), { club: clubId });
        onSaved(f.startDate);
      } catch (e) { setErr(e.message); setBusy(false); }
    }
    async function del() {
      if (!window.confirm(f.repeat ? "Delete this item and every repeat of it?" : "Delete this item?")) return;
      setBusy(true); setErr(null);
      try { await API.call("DELETE", "/club/calendar/" + f.id, null, { club: clubId }); onSaved(null); } catch (e) { setErr(e.message); setBusy(false); }
    }
    return h("div", { className: "cc-modal-bg", role: "dialog", "aria-modal": "true", "aria-label": f.id ? "Calendar item" : "New calendar item", onMouseDown: (e) => { if (e.target === e.currentTarget) onClose(); } },
      h("div", { className: "cc-modal" },
        h("div", { className: "cc-modal-h" }, h("h2", null, canEdit ? (f.id ? "Edit item" : "Add to the calendar") : f.title), h("button", { className: "cc-btn sm", onClick: onClose, "aria-label": "Close" }, "✕")),
        h("div", { className: "cc-modal-b" },
          f.source && h("div", { className: "cc-note trial" }, "From " + f.source.type + ". Changing it here does not change the plan." + (fromApp ? " Who can see it is controlled in " + f.source.type + ": only people who can open that " + (f.source.type === "Tasks" ? "project" : "campaign") + " see it here." : "")),
          !f.id && !editor && h("div", { className: "cc-note" }, "You can add personal entries. Only a club admin or a member with Edit access to Calendar can add items for the whole club."),
          f.kind === "Personal" && f.id && !f.mine && h("div", { className: "cc-note trial" }, "Personal entry shared with you by " + (f.ownerName || "a club member") + ". Only they can change it."),
          canEdit && h("label", { className: "cc-field" }, "What is on?", h("input", { autoFocus: true, placeholder: "For example: Club meeting", ...bind("title") })),
          h("div", { className: "cc-grid2" },
            h("label", { className: "cc-field" }, "Type", h("select", { ...bind("kind"), disabled: !canEdit || (!editor && f.kind === "Personal") }, Object.keys(KINDS).filter((k) => editor || k === "Personal" || k === f.kind).map((k) => h("option", { key: k, value: k }, k === "Club" ? "Club activity" : k)))),
            h("label", { className: "cc-field" }, "Where (optional)", h("input", { ...bind("location") }))),
          h("div", { className: "cc-grid2" },
            h("label", { className: "cc-field" }, "Date", h("input", { type: "date", ...bind("startDate") })),
            h("label", { className: "cc-field" }, "Ends on (if more than one day)", h("input", { type: "date", min: f.startDate, ...bind("endDate") }))),
          h("label", { className: "cc-field", style: { flexDirection: "row", gap: 8, alignItems: "center" } }, h("input", { type: "checkbox", checked: f.allDay, disabled: !canEdit, onChange: (e) => set("allDay", e.target.checked) }), "All day"),
          !f.allDay && h("div", { className: "cc-grid2" },
            h("label", { className: "cc-field" }, "Starts", h("input", { type: "time", value: f.startTime, disabled: !canEdit, onChange: (e) => setStart(e.target.value) })),
            h("label", { className: "cc-field" }, "Ends", h("input", { type: "time", ...bind("endTime") }))),
          !f.allDay && h("p", { className: "cc-hint", style: { marginTop: -4 } }, workFromNow() ? CCIntl.t("working.field", { club: CCIntl.zoneName(zoneNow()), zone: CCIntl.zoneName(workFromNow()) }) + (alsoAt(f.startDate, f.startTime) ? " Starts " + alsoAt(f.startDate, f.startTime) + "." : "") : CCIntl.t("working.clubonly", { club: CCIntl.zoneName(zoneNow()) })),
          h("div", { className: "cc-grid2" },
            h("label", { className: "cc-field" }, "Repeats", h("select", { ...bind("repeat") }, REPEATS.map(([v, l]) => h("option", { key: v, value: v }, l)))),
            f.repeat && h("label", { className: "cc-field" }, "Repeat until (optional)", h("input", { type: "date", min: f.startDate, ...bind("repeatUntil") }))),
          h("fieldset", { className: "cc-field" }, h("legend", null, "Reminders"),
            h("label", { style: { display: "flex", gap: 8, alignItems: "center", marginBottom: 6 } }, h("input", { type: "checkbox", disabled: !canEdit, checked: f.reminders === null, onChange: (e) => set("reminders", e.target.checked ? null : defaults.slice()) }),
              "Use the club's reminders (" + remText(defaults) + ")"),
            f.reminders !== null && h(Reminders, { value: f.reminders, disabled: !canEdit, onChange: (v) => set("reminders", v) }),
            f.allDay && h("p", { className: "cc-muted sm", style: { margin: "4px 0 0" } }, "All-day items only take reminders of a day or more, sent at 9am.")),
          f.kind === "Personal" && (f.mine || !f.id) && h("fieldset", { className: "cc-field" }, h("legend", null, "Who can see this"),
            SHARING.map(([v, l]) => h("label", { key: v, style: { display: "flex", gap: 8, alignItems: "center", marginBottom: 4 } },
              h("input", { type: "radio", name: "cc-sharing", checked: f.sharing === v, onChange: () => set("sharing", v) }), l)),
            f.sharing === "people" && h("div", { className: "cc-people", style: { maxHeight: 160, overflowY: "auto", border: "1px solid var(--b-line)", borderRadius: 6, padding: "6px 8px", marginTop: 4 } },
              members.length === 0 && h("p", { className: "cc-muted sm", style: { margin: 0 } }, "There is nobody else in the club yet."),
              members.map((m) => h("label", { key: m.id, style: { display: "flex", gap: 8, alignItems: "center", marginBottom: 2 } },
                h("input", { type: "checkbox", checked: f.sharedWith.includes(m.id), onChange: (e) => set("sharedWith", e.target.checked ? f.sharedWith.concat(m.id) : f.sharedWith.filter((i) => i !== m.id)) }), m.name || "Member"))),
            h("p", { className: "cc-muted sm", style: { margin: "4px 0 0" } }, f.sharing === "me" ? "Only you can see it, in Clubcraft and on your personal calendar link. Not even club admins can." : f.sharing === "club" ? "Everyone in the club can see it. Only you can change it." : "Only you and the people you pick can see it. Only you can change it.")),
          h("label", { className: "cc-field" }, "Notes (optional)", h("textarea", { rows: 3, maxLength: 10000, ...bind("notes") })),
          err && h("div", { className: "cc-err", role: "alert" }, err)),
        h("div", { className: "cc-modal-f" },
          canEdit && f.id ? h("button", { className: "cc-btn ghost", disabled: busy, onClick: del }, "Delete") : h("span"),
          h("div", { className: "cc-row" },
            h("button", { className: "cc-btn ghost", onClick: onClose }, canEdit ? "Cancel" : "Close"),
            canEdit && h("button", { className: "cc-btn primary", disabled: busy || !f.title.trim() || !f.startDate || (f.kind === "Personal" && f.sharing === "people" && f.sharedWith.length === 0), onClick: save }, busy ? "Saving…" : "Save")))));
  }

  /* ---------- dates waiting from another app ---------- */
  function Handoff({ clubId, handoff, onDone, onDismiss }) {
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    async function add() {
      setBusy(true); setErr(null);
      try {
        await API.call("POST", "/club/calendar/import", { source_type: handoff.source_type, source_id: String(handoff.source_id), name: handoff.name, items: handoff.items }, { club: clubId });
        onDone(handoff.items.map((i) => i.date).sort()[0]);
      } catch (e) { setErr(e.message); setBusy(false); }
    }
    return h("section", { className: "cc-card" },
      h("div", { className: "cc-card-h" }, h("h2", null, "Add " + handoff.items.length + " dates from " + handoff.source_type), h("span", { className: "cc-pill trial" }, handoff.name)),
      h("ul", { className: "cc-rv-list" }, handoff.items.map((i, n) => h("li", { key: n }, h("b", null, i.title), " ", h("span", { className: "cc-muted" }, fmtDay(i.date) + (i.end && i.end !== i.date ? " to " + fmtDay(i.end) : ""))))),
      h("p", { className: "cc-muted sm" }, "If you added these before, the earlier ones are replaced, not doubled."),
      err && h("div", { className: "cc-err", role: "alert" }, err),
      h("div", { className: "cc-row" }, h("button", { className: "cc-btn primary", disabled: busy, onClick: add }, busy ? "Adding…" : "Add to the calendar"), h("button", { className: "cc-btn ghost", disabled: busy, onClick: onDismiss }, "Not now")));
  }

  /* ---------- the page ---------- */
  function CalendarApp({ clubId, clubInfo }) {
    const access = (clubInfo.me.access || {}).Calendar || "view";
    const canEdit = access === "edit";
    const [month, setMonth] = React.useState(() => { const d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 1); });
    const [data, setData] = React.useState(null);
    const [filter, setFilter] = React.useState("All");
    const [modal, setModal] = React.useState(null);
    const [handoff, setHandoff] = React.useState(() => (canEdit ? window.CCCalendarHandoff.get() : null));
    const [err, setErr] = React.useState(null);
    const [copied, setCopied] = React.useState(false);
    const [adminBusy, setAdminBusy] = React.useState(false);
    const [projects, setProjects] = React.useState([]);        // Tasks projects that can put their due dates here
    const [taskBusy, setTaskBusy] = React.useState(null);
    const [taskNote, setTaskNote] = React.useState("");

    const lead = (month.getDay() + 6) % 7;                                   // Monday first
    const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
    const cells = Array.from({ length: Math.ceil((lead + days) / 7) * 7 }, (_, i) => (i < lead || i >= lead + days ? null : new Date(month.getFullYear(), month.getMonth(), i - lead + 1, 12)));
    const from = isoOf(new Date(month.getFullYear(), month.getMonth(), 1, 12));
    const to = isoOf(new Date(month.getFullYear(), month.getMonth() + 1, 0, 12));

    const load = React.useCallback(() => API.call("GET", "/club/calendar?from=" + from + "&to=" + to, null, { club: clubId }).then((r) => { setData(r); setErr(null); }).catch((e) => setErr(e.message)), [clubId, from, to]);
    React.useEffect(() => { load(); }, [load]);

    const loadProjects = React.useCallback(() => { if (canEdit) API.call("GET", "/club/calendar/tasks", null, { club: clubId }).then((r) => setProjects(r.projects || [])).catch(() => setProjects([])); }, [clubId, canEdit]);
    React.useEffect(() => { loadProjects(); }, [loadProjects]);
    const syncTasks = async (p) => {
      setTaskBusy(p.id); setTaskNote(""); setErr(null);
      try {
        const r = await API.call("POST", "/club/calendar/tasks", { projectId: p.id }, { club: clubId });
        setTaskNote(r.added ? "Put " + r.added + " due dates from " + p.name + " on the calendar." + (r.truncated ? " Only the first 80 were added." : "") : "No open tasks with due dates in " + p.name + ", so nothing is on the calendar for it.");
        loadProjects(); load();
      } catch (e) { setErr(e.message); }
      setTaskBusy(null);
    };

    const [campaigns, setCampaigns] = React.useState([]);      // Social campaigns that can put their posts here
    const [socialBusy, setSocialBusy] = React.useState(null);
    const [socialNote, setSocialNote] = React.useState("");
    const loadCampaigns = React.useCallback(() => { if (canEdit) API.call("GET", "/club/calendar/social", null, { club: clubId }).then((r) => setCampaigns(r.campaigns || [])).catch(() => setCampaigns([])); }, [clubId, canEdit]);
    React.useEffect(() => { loadCampaigns(); }, [loadCampaigns]);
    const syncSocial = async (c) => {
      setSocialBusy(c.id); setSocialNote(""); setErr(null);
      try {
        const r = await API.call("POST", "/club/calendar/social", { campaignId: c.id }, { club: clubId });
        setSocialNote("Put " + r.added + " posts from " + c.name + " on the calendar.");
        loadCampaigns(); load();
      } catch (e) { setErr(e.message); }
      setSocialBusy(null);
    };

    const byDay = {};
    ((data && data.occurrences) || []).forEach((o) => {
      for (let d = o.date; d <= o.occEnd; d = isoOf(new Date(dateOf(d).getTime() + DAY))) (byDay[d] = byDay[d] || []).push(o);
    });
    const shown = (o) => filter === "All" || o.kind === filter;
    const today = data ? data.today : isoOf(new Date());
    const afterSave = (iso) => {
      setModal(null);
      if (iso && iso.slice(0, 7) !== from.slice(0, 7)) { const d = dateOf(iso); setMonth(new Date(d.getFullYear(), d.getMonth(), 1)); } else load();
    };
    // Drag and drop (docs/calendar-module.md): hand-added items move here; Tasks and Social items change in their own app first (server checks the same rules); Events, Comms and repeats are opened to change.
    const [drag, setDrag] = React.useState(null);                // the occurrence being dragged
    const [over, setOver] = React.useState(null);                // the day it is hovering over
    const movable = (o) => o.canEdit && !o.repeat && (!o.source || ((o.source.type === "Tasks" || o.source.type === "Social") && !!o.source.ref && o.kind !== "Event") && !/^Posted: /.test(o.title));
    const moveTo = async (o, iso) => {
      setDrag(null); setOver(null);
      if (!o || iso === o.date) return;
      setErr(null);
      try {
        await API.call("POST", "/club/calendar/" + o.id + "/move", { date: iso }, { club: clubId });
      } catch (e) { setErr(e.message); }
      load();
    };
    const open = (o) => setModal(toForm(o));
    const add = (iso) => { const d = iso || today, s = defaultStart(d, today); setModal({ ...EMPTY, kind: canEdit ? "Meeting" : "Personal", startDate: d, startTime: s, endTime: fromMin(toMin(s) + 60) }); };
    const defaults = (data && data.defaultReminders) || [30];
    const [remBusy, setRemBusy] = React.useState(false);
    const [remEdit, setRemEdit] = React.useState(null);
    const saveDefaults = async () => { setRemBusy(true); setErr(null); try { await API.call("PUT", "/club/calendar/settings", { reminders: remEdit }, { club: clubId }); setRemEdit(null); await load(); } catch (e) { setErr(e.message); } setRemBusy(false); };
    const copy = (url, which) => { navigator.clipboard.writeText(url).then(() => { setCopied(which); setTimeout(() => setCopied(false), 2500); }).catch(() => window.prompt("Copy this link", url)); };
    const rotateMine = async () => {
      if (!window.confirm("Make a new personal link? Any calendar app using your old link will stop getting updates until you subscribe again.")) return;
      setAdminBusy(true); try { await API.call("POST", "/club/calendar/feed/rotate-mine", {}, { club: clubId }); await load(); } catch (e) { setErr(e.message); } setAdminBusy(false);
    };
    const rotate = async () => {
      if (!window.confirm("Make a new private link? Anyone using the old link will stop getting updates until they subscribe again.")) return;
      setAdminBusy(true); try { await API.call("POST", "/club/calendar/feed/rotate", {}, { club: clubId }); await load(); } catch (e) { setErr(e.message); } setAdminBusy(false);
    };

    const workFrom = workFromNow();
    return h("div", null,
      err && h("div", { className: "cc-err", role: "alert" }, err),
      handoff && h(Handoff, { clubId, handoff, onDismiss: () => { window.CCCalendarHandoff.clear(); setHandoff(null); }, onDone: (first) => { window.CCCalendarHandoff.clear(); setHandoff(null); afterSave(first); } }),
      !canEdit && h("div", { className: "cc-note" }, "You can view the club calendar and keep your own personal entries. A club admin or a member with Edit access to Calendar can add and change club items."),
      h("div", { className: "cc-ex-cal" },
        h("div", null,
          h("div", { className: "cc-ex-calbar" },
            h("div", { className: "nav" },
              h("button", { className: "cc-btn sm", onClick: () => setMonth(new Date(month.getFullYear(), month.getMonth() - 1, 1)), "aria-label": "Previous month" }, "‹"),
              h("b", null, month.toLocaleDateString(CCIntl.locale(), { month: "long", year: "numeric" })),
              h("button", { className: "cc-btn sm", onClick: () => setMonth(new Date(month.getFullYear(), month.getMonth() + 1, 1)), "aria-label": "Next month" }, "›"),
              h("button", { className: "cc-link", onClick: () => { const d = new Date(); setMonth(new Date(d.getFullYear(), d.getMonth(), 1)); } }, "Today")),
            h("div", { className: "cc-ex-chips tight" }, ["All", ...Object.keys(KINDS)].map((k) => h("button", { key: k, className: filter === k ? "on" : "", onClick: () => setFilter(k) }, k !== "All" && h("i", { style: { background: KINDS[k] } }), k === "All" ? "All" : KIND_LABEL[k])))),
          h("p", { className: "cc-muted sm", style: { margin: "4px 0 8px" }, role: "status" }, workFrom ? CCIntl.t("working.cal", { club: CCIntl.zoneName(zoneNow()), zone: CCIntl.zoneName(workFrom) }) : CCIntl.t("working.clubonly", { club: CCIntl.zoneName(zoneNow()) })),
          !data && !err && h("p", { className: "cc-muted" }, "Loading…"),
          h("div", { className: "cc-ex-grid", role: "grid", "aria-label": "Month" },
            ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => h("div", { key: d, className: "dow" }, d)),
            cells.map((d, i) => {
              if (!d) return h("div", { key: i, className: "day off" });
              const iso = isoOf(d), list = (byDay[iso] || []).filter(shown);
              return h("div", { key: i, className: "day" + (iso === today ? " today" : "") + (drag && over === iso ? " drop" : ""), onClick: () => add(iso), style: { cursor: "pointer" },
                onDragOver: drag ? (e) => { e.preventDefault(); if (over !== iso) setOver(iso); } : undefined,
                onDrop: drag ? (e) => { e.preventDefault(); moveTo(drag, iso); } : undefined },
                h("span", { className: "n" }, d.getDate()),
                list.slice(0, 3).map((o, j) => h("button", { key: o.id + ":" + j, type: "button", className: "ev", draggable: movable(o), style: { "--c": KINDS[o.kind], textAlign: "left", cursor: movable(o) ? "grab" : "pointer", border: 0, borderLeft: "3px solid " + KINDS[o.kind] }, title: o.title + ", " + timeRange(o) + (movable(o) ? ". Drag to another day to move it" + (o.source ? " (it changes in " + o.source.type + " too)." : ".") : o.source ? ((o.source.type === "Tasks" || o.source.type === "Social") && !o.source.ref ? ". Press Refresh on its " + (o.source.type === "Tasks" ? "project" : "campaign") + " to make it movable." : ". Change it in " + o.source.type + ".") : ""),
                  onDragStart: movable(o) ? (e) => { e.dataTransfer.effectAllowed = "move"; e.dataTransfer.setData("text/plain", o.id); setDrag(o); } : undefined, onDragEnd: () => { setDrag(null); setOver(null); },
                  onClick: (e) => { e.stopPropagation(); open(o); } }, (o.startTime && o.date === iso ? fmtTime(o.startTime) + (alsoShort(o.date, o.startTime) ? " (" + alsoShort(o.date, o.startTime) + ")" : "") + " " : "") + o.title)),
                list.length > 3 && h("span", { className: "more" }, "+" + (list.length - 3) + " more"));
            })),
          h("div", { className: "cc-ex-legend" }, Object.keys(KINDS).map((k) => h("span", { key: k }, h("i", { style: { background: KINDS[k] } }), { Meeting: "Meetings", Event: "From Events", Task: "From Tasks", Post: "From Social", Club: "Club activities", Personal: "Personal" }[k]))),
          data && data.total === 0 && h("div", { className: "cc-note trial" }, canEdit ? "Nothing here yet. Click a day, or press Add an item, to put your regular club meeting on the calendar." : "Nothing has been added yet.")),
        h("aside", { className: "cc-ex-side" },
          h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "Add to the calendar")),
            h("button", { className: "cc-btn primary", onClick: () => add() }, canEdit ? "Add an item" : "Add a personal entry"),
            h("ul", { className: "cc-ex-ways" },
              h("li", null, h("b", null, "Personal entries"), h("span", null, "Choose the Personal type for something only you see, or share it with the club or with people you pick.")),
              canEdit && h("li", null, h("b", null, "From your plans"), h("span", null, "Use Add to Calendar on an Events or Comms plan, or add a Tasks project or Social campaign below. Tasks and posts show only to people who can open that project or campaign.")))),
          canEdit && projects.length > 0 && h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "Task due dates")),
            h("p", { className: "cc-muted sm" }, "Show a project's open tasks on the calendar. They refresh each night, or press Refresh to update now."),
            h("ul", { className: "cc-ex-ways" }, projects.map((p) => h("li", { key: p.id }, h("b", null, p.name), h("span", null, p.dated + " open with a due date"),
              h("button", { className: "cc-btn sm" + (p.onCalendar ? "" : " primary"), disabled: taskBusy === p.id || (!p.dated && !p.onCalendar), onClick: () => syncTasks(p) }, taskBusy === p.id ? "Working…" : p.onCalendar ? "Refresh" : "Add to calendar")))),
            taskNote && h("div", { className: "cc-note trial", role: "status" }, taskNote)),
          canEdit && campaigns.length > 0 && h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "Social posts")),
            h("p", { className: "cc-muted sm" }, "Show a campaign's planned and posted posts on the calendar. They refresh each night."),
            h("ul", { className: "cc-ex-ways" }, campaigns.map((c) => h("li", { key: c.id }, h("b", null, c.name),
              h("button", { className: "cc-btn sm" + (c.onCalendar ? "" : " primary"), disabled: socialBusy === c.id, onClick: () => syncSocial(c) }, socialBusy === c.id ? "Working…" : c.onCalendar ? "Refresh now" : "Add to calendar")))),
            socialNote && h("div", { className: "cc-note trial", role: "status" }, socialNote)),
          data && h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "Reminders")),
            h("p", { className: "cc-muted sm" }, "Every item gets these unless it has its own: ", h("b", null, remText(defaults)), "."),
            data.isAdmin && (remEdit === null
              ? h("button", { className: "cc-btn sm", onClick: () => setRemEdit(defaults.slice()) }, "Change the club's reminders")
              : h("div", null, h(Reminders, { value: remEdit, onChange: setRemEdit }),
                h("div", { className: "cc-row", style: { gap: 8, marginTop: 6 } }, h("button", { className: "cc-btn sm primary", disabled: remBusy, onClick: saveDefaults }, remBusy ? "Saving…" : "Save"), h("button", { className: "cc-btn sm ghost", disabled: remBusy, onClick: () => setRemEdit(null) }, "Cancel")))),
            h("p", { className: "cc-muted sm" }, "Reminders come from your calendar app once you subscribe below. Apple and Outlook calendars show them; Google Calendar ignores reminders on subscribed calendars, so set those in Google.")),
          h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "See it on your phone")),
            h("p", { className: "cc-muted sm" }, "Subscribe once from Google, Outlook, Apple or Zoho Calendar and it stays up to date. No Clubcraft login needed."),
            data ? h("div", null,
              h("b", { className: "sm" }, "Your link"),
              h("p", { className: "cc-muted sm", style: { margin: "2px 0 4px" } }, "Everything you can see, including your personal entries and the tasks and posts you can open."),
              h("div", { className: "cc-ex-copy" }, h("code", { title: data.myFeedUrl }, data.myFeedUrl), h("button", { className: "cc-btn sm", type: "button", onClick: () => copy(data.myFeedUrl, "mine") }, copied === "mine" ? "Copied" : "Copy link")),
              h("p", { className: "cc-muted sm" }, "Keep this one to yourself: anyone who has it can read all of that. ", h("button", { className: "cc-link", disabled: adminBusy, onClick: rotateMine }, "Make a new link")),
              h("b", { className: "sm" }, "Club link"),
              h("p", { className: "cc-muted sm", style: { margin: "2px 0 4px" } }, "Club items only: no personal entries, no tasks or posts (unless a personal entry is shared with the whole club)."),
              h("div", { className: "cc-ex-copy" }, h("code", { title: data.feedUrl }, data.feedUrl), h("button", { className: "cc-btn sm", type: "button", onClick: () => copy(data.feedUrl, "club") }, copied === "club" ? "Copied" : "Copy link"))) : null,
            h("p", { className: "cc-muted sm" }, "Keep the club link inside the club: anyone who has it can read the club calendar."),
            data && data.isAdmin && h("div", { className: "cc-row", style: { flexWrap: "wrap", gap: 8 } },
              h("button", { className: "cc-btn sm ghost", disabled: adminBusy, onClick: rotate }, "Make a new link"))),
          h("section", { className: "cc-ex-panel" }, h("div", { className: "cc-ex-ph" }, h("h3", null, "Coming up")),
            data && data.upcoming.length === 0 && h("p", { className: "cc-muted sm" }, "Nothing in the next four months."),
            h("ul", { className: "cc-ex-up" }, ((data && data.upcoming) || []).map((o, i) => h("li", { key: o.id + ":" + i }, h("i", { style: { background: KINDS[o.kind] } }), h("div", null, h("b", null, h("button", { className: "cc-link", onClick: () => open(o) }, o.title)), h("span", null, fmtDay(o.date) + ", " + timeRange(o) + (o.repeat ? " (" + repeatLabel(o.repeat).toLowerCase() + ")" : "")))))))),
      ),
      modal && h(ItemModal, { clubId, form: modal, editor: canEdit, members: (data && data.members) || [], defaults, onClose: () => setModal(null), onSaved: afterSave }));
  }

  window.CCCalendar = CalendarApp;
})();
