/* Events tab.
 *
 * Desktop (≥1024px): idea rail (320px) + month calendar with warm-ivory
 * background. HTML5 drag-drop: drop an idea on a day → state becomes
 * scheduled.
 *
 * Phone (<1024px): segmented Calendar/Ideas toggle. Tap-to-schedule
 * modal is the drag-drop fallback per spec 4.4.
 */
(function () {
  const { useState, useEffect, useMemo, useRef } = React;
  const {
    SegmentedControl,
    Drawer,
    Button,
    Input,
    TextArea,
    Card,
    Pill,
    Icons,
    EmptyState,
    showToast,
    events,
    coach,
    tokens,
    time,
  } = window.CC;

  // ────────────────────────────────────────────────────────────
  // Hooks
  // ────────────────────────────────────────────────────────────
  function useEvents() {
    const [list, setList] = useState(events.all());
    useEffect(() => events.subscribe(setList), []);
    return list;
  }
  function useViewport() {
    const [wide, setWide] = useState(
      typeof window !== "undefined" ? window.innerWidth >= 1024 : true
    );
    useEffect(() => {
      const onResize = () => setWide(window.innerWidth >= 1024);
      window.addEventListener("resize", onResize);
      return () => window.removeEventListener("resize", onResize);
    }, []);
    return { wide };
  }

  // ────────────────────────────────────────────────────────────
  // Tab root
  // ────────────────────────────────────────────────────────────
  function Events() {
    const { wide } = useViewport();
    const all = useEvents();
    const [editing, setEditing] = useState(null);
    const [adding, setAdding] = useState(false);
    const [scheduleFor, setScheduleFor] = useState(null); // idea object → date picker
    const [phoneTab, setPhoneTab] = useState("calendar");
    const [ideaFilter, setIdeaFilter] = useState("idea");
    const [cursorMonth, setCursorMonth] = useState(() => {
      const d = new Date();
      d.setDate(1);
      return d;
    });

    const ideasList = all.filter((e) => events.effectiveState(e) === ideaFilter);

    return (
      <div className="cc-events">
        <header className="cc-events__head">
          <h1 className="cc-hub__title">Events</h1>
          {!wide && (
            <SegmentedControl
              value={phoneTab}
              onChange={setPhoneTab}
              options={[
                { label: "Calendar", value: "calendar" },
                { label: "Ideas", value: "ideas" },
              ]}
            />
          )}
        </header>

        <div className="cc-events__layout">
          {(wide || phoneTab === "ideas") && (
            <IdeaRail
              filter={ideaFilter}
              onFilterChange={setIdeaFilter}
              events={ideasList}
              onAdd={() => setAdding(true)}
              onEdit={(e) => setEditing(e)}
              onSchedule={(e) => setScheduleFor(e)}
            />
          )}
          {(wide || phoneTab === "calendar") && (
            <Calendar
              cursorMonth={cursorMonth}
              onCursorChange={setCursorMonth}
              events={all.filter((e) => events.effectiveState(e) !== "idea")}
              onDropIdea={(idea, dateIso) => {
                events.schedule(idea.id, dateIso);
                showToast(`Scheduled "${idea.title}".`);
              }}
              onOpen={(e) => setEditing(e)}
            />
          )}
        </div>

        <NewIdeaDrawer open={adding} onClose={() => setAdding(false)} />
        <EditEventDrawer event={editing} onClose={() => setEditing(null)} />
        <SchedulePickerDrawer
          event={scheduleFor}
          onClose={() => setScheduleFor(null)}
          onPick={(dateIso) => {
            events.schedule(scheduleFor.id, dateIso);
            setScheduleFor(null);
            showToast(`Scheduled for ${time.shortDate(new Date(dateIso))}.`);
          }}
        />
      </div>
    );
  }

  // ────────────────────────────────────────────────────────────
  // Idea rail
  // ────────────────────────────────────────────────────────────
  function IdeaRail({ filter, onFilterChange, events: items, onAdd, onEdit, onSchedule }) {
    const [hot, setHot] = useState(false);
    function onDragOver(e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
      setHot(true);
    }
    function onDragLeave() { setHot(false); }
    function onDrop(e) {
      e.preventDefault();
      setHot(false);
      const id = e.dataTransfer.getData("text/plain");
      const found = window.CC.events.byId(id);
      if (found && found.state !== "idea") {
        window.CC.events.unschedule(found.id);
        showToast(`"${found.title}" moved back to ideas.`);
      }
    }
    return (
      <aside
        className={`cc-events__rail ${hot ? "is-hot" : ""}`}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
      >
        <div className="cc-events__rail-head">
          <SegmentedControl
            size="sm"
            value={filter}
            onChange={onFilterChange}
            options={[
              { label: "Ideas", value: "idea" },
              { label: "Scheduled", value: "scheduled" },
              { label: "Done", value: "done" },
            ]}
          />
        </div>
        {items.length === 0 ? (
          <EmptyState
            icon={Icons.calendar(40)}
            title={
              filter === "idea"
                ? "No ideas yet"
                : filter === "scheduled"
                ? "Nothing scheduled"
                : "Nothing done yet"
            }
            subtitle={filter === "idea" ? "Tap + to add the first." : null}
          />
        ) : (
          <ul className="cc-events__rail-list">
            {items.map((e) => (
              <IdeaCard
                key={e.id}
                event={e}
                onEdit={() => onEdit(e)}
                onSchedule={() => onSchedule(e)}
              />
            ))}
          </ul>
        )}
        <button
          type="button"
          className="cc-events__rail-fab"
          onClick={onAdd}
          aria-label="Add idea"
        >
          {Icons.plus(20)}
        </button>
      </aside>
    );
  }

  function IdeaCard({ event: ev, onEdit, onSchedule }) {
    const eff = events.effectiveState(ev);
    function onDragStart(e) {
      e.dataTransfer.setData("text/plain", ev.id);
      e.dataTransfer.effectAllowed = "move";
    }
    return (
      <li
        className={`cc-idea-card cc-idea-card--${eff}`}
        draggable
        onDragStart={onDragStart}
      >
        <button type="button" className="cc-idea-card__main" onClick={onEdit}>
          <div className="cc-idea-card__title">{ev.title}</div>
          {ev.notes && (
            <div className="cc-idea-card__desc">{ev.notes}</div>
          )}
          {ev.date && (
            <div className="cc-idea-card__date">
              {time.shortDate(new Date(ev.date))}
              {ev.time ? ` · ${ev.time}` : ""}
              {eff === "done" && " · done"}
            </div>
          )}
        </button>
        {eff === "idea" && (
          <button
            type="button"
            className="cc-idea-card__schedule"
            onClick={onSchedule}
            aria-label="Schedule"
          >
            {Icons.calendar(16)}
          </button>
        )}
      </li>
    );
  }

  // ────────────────────────────────────────────────────────────
  // Calendar
  // ────────────────────────────────────────────────────────────
  function Calendar({ cursorMonth, onCursorChange, events: items, onDropIdea, onOpen }) {
    const grid = useMemo(() => buildGrid(cursorMonth), [cursorMonth]);
    const todayIso = events.todayIso();

    const byDate = useMemo(() => {
      const m = new Map();
      for (const e of items) {
        if (!e.date) continue;
        const list = m.get(e.date) || [];
        list.push(e);
        m.set(e.date, list);
      }
      return m;
    }, [items]);

    function shiftMonth(delta) {
      const d = new Date(cursorMonth);
      d.setMonth(d.getMonth() + delta);
      onCursorChange(d);
    }

    return (
      <section className="cc-cal">
        <header className="cc-cal__head">
          <button type="button" onClick={() => shiftMonth(-1)} aria-label="Previous month">
            ←
          </button>
          <h2 className="cc-cal__title">
            {cursorMonth.toLocaleDateString(undefined, { month: "long", year: "numeric" })}
          </h2>
          <button type="button" onClick={() => shiftMonth(1)} aria-label="Next month">
            →
          </button>
        </header>
        <div className="cc-cal__weekdays">
          {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
            <span key={d}>{d}</span>
          ))}
        </div>
        <div className="cc-cal__grid">
          {grid.map((cell) => (
            <CalendarCell
              key={cell.iso}
              cell={cell}
              today={cell.iso === todayIso}
              events={byDate.get(cell.iso) || []}
              onDropIdea={onDropIdea}
              onOpen={onOpen}
            />
          ))}
        </div>
      </section>
    );
  }

  function buildGrid(cursorMonth) {
    const out = [];
    const first = new Date(cursorMonth);
    first.setDate(1);
    // Mon=0 ... Sun=6 — UK week start.
    const dayOfWeek = (first.getDay() + 6) % 7;
    const start = new Date(first);
    start.setDate(1 - dayOfWeek);
    for (let i = 0; i < 42; i++) {
      const d = new Date(start);
      d.setDate(start.getDate() + i);
      const iso = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
      out.push({
        iso,
        day: d.getDate(),
        otherMonth: d.getMonth() !== cursorMonth.getMonth(),
      });
    }
    return out;
  }

  function CalendarCell({ cell, today, events: items, onDropIdea, onOpen }) {
    const [hot, setHot] = useState(false);
    function onDragOver(e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
      setHot(true);
    }
    function onDragLeave() { setHot(false); }
    function onDrop(e) {
      e.preventDefault();
      setHot(false);
      const id = e.dataTransfer.getData("text/plain");
      const found = window.CC.events.byId(id);
      if (found) onDropIdea(found, cell.iso);
    }
    function eventDragStart(e, ev) {
      e.stopPropagation();
      e.dataTransfer.setData("text/plain", ev.id);
      e.dataTransfer.effectAllowed = "move";
    }
    return (
      <div
        className={`cc-cal__cell ${cell.otherMonth ? "is-other" : ""} ${
          today ? "is-today" : ""
        } ${hot ? "is-hot" : ""}`}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
      >
        <div className="cc-cal__day">{cell.day}</div>
        <div className="cc-cal__events">
          {items.slice(0, 3).map((e) => (
            <button
              type="button"
              key={e.id}
              onClick={() => onOpen(e)}
              draggable
              onDragStart={(de) => eventDragStart(de, e)}
              className={`cc-cal__event cc-cal__event--${window.CC.events.effectiveState(e)}`}
              title={e.title}
            >
              {e.time && <span className="cc-cal__event-time">{e.time}</span>}
              {e.title}
            </button>
          ))}
          {items.length > 3 && (
            <span className="cc-cal__more">+{items.length - 3}</span>
          )}
        </div>
      </div>
    );
  }

  // ────────────────────────────────────────────────────────────
  // New idea drawer
  // ────────────────────────────────────────────────────────────
  function NewIdeaDrawer({ open, onClose }) {
    const [title, setTitle] = useState("");
    const [notes, setNotes] = useState("");
    const [saving, setSaving] = useState(false);

    useEffect(() => {
      if (open) {
        setTitle("");
        setNotes("");
        setSaving(false);
      }
    }, [open]);

    async function save() {
      if (!title.trim()) {
        showToast("Title required.");
        return;
      }
      setSaving(true);
      try {
        await events.add({ title, notes: notes || null });
        showToast("Idea added.");
        onClose();
      } catch (e) {
        showToast("Couldn’t save.");
      } finally {
        setSaving(false);
      }
    }

    return (
      <Drawer
        open={open}
        onClose={onClose}
        title="New idea"
        footer={
          <Button fullWidth size="lg" onClick={save} loading={saving}>
            Save
          </Button>
        }
      >
        <div style={{ display: "grid", gap: 16 }}>
          <Input label="Title" value={title} onChange={setTitle} autoFocus />
          <TextArea label="Notes (optional)" value={notes} onChange={setNotes} rows={4} />
        </div>
      </Drawer>
    );
  }

  // ────────────────────────────────────────────────────────────
  // Edit event drawer (used for any event tap)
  // ────────────────────────────────────────────────────────────
  function EditEventDrawer({ event, onClose }) {
    const [draft, setDraft] = useState(event || {});
    useEffect(() => setDraft(event || {}), [event]);
    if (!event) return null;

    function patch(p) {
      setDraft((d) => ({ ...d, ...p }));
      events.update(event.id, p).catch(() => {});
    }

    async function del() {
      await events.softDelete(event.id);
      showToast("Deleted.", {
        action: { label: "Undo", onClick: () => events.restore(event.id) },
      });
      onClose();
    }

    function backToIdea() {
      events.unschedule(event.id);
      showToast("Moved back to ideas.");
      onClose();
    }

    return (
      <Drawer
        open={Boolean(event)}
        onClose={onClose}
        title={event.title || "Event"}
        footer={
          <div style={{ display: "flex", gap: 8 }}>
            <Button variant="ghost" onClick={del}>
              {Icons.trash(14)} Delete
            </Button>
            <span style={{ flex: 1 }} />
            {event.state === "scheduled" && (
              <Button variant="secondary" onClick={backToIdea}>
                Move to ideas
              </Button>
            )}
            <Button onClick={onClose}>Done</Button>
          </div>
        }
      >
        <div style={{ display: "grid", gap: 16 }}>
          <Input
            label="Title"
            value={draft.title || ""}
            onChange={(v) => patch({ title: v })}
          />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Input
              label="Date"
              type="date"
              value={draft.date || ""}
              onChange={(v) => patch({ date: v || null, state: v ? "scheduled" : "idea" })}
            />
            <Input
              label="Time"
              type="time"
              value={draft.time || ""}
              onChange={(v) => patch({ time: v || null })}
            />
          </div>
          <TextArea
            label="Notes"
            value={draft.notes || ""}
            onChange={(v) => patch({ notes: v || null })}
            rows={4}
          />
        </div>
      </Drawer>
    );
  }

  // ────────────────────────────────────────────────────────────
  // Schedule picker (phone fallback for drag-drop)
  // ────────────────────────────────────────────────────────────
  function SchedulePickerDrawer({ event, onClose, onPick }) {
    const [date, setDate] = useState(events.todayIso());
    useEffect(() => {
      if (event) setDate(events.todayIso());
    }, [event]);
    if (!event) return null;
    return (
      <Drawer
        open={Boolean(event)}
        onClose={onClose}
        title={`Schedule "${event.title}"`}
        footer={
          <Button fullWidth size="lg" onClick={() => onPick(date)}>
            Schedule
          </Button>
        }
      >
        <Input label="Date" type="date" value={date} onChange={setDate} autoFocus />
      </Drawer>
    );
  }

  window.CC = window.CC || {};
  window.CC.Events = Events;
})();
