// =============================================================================
// CALENDAR TAB
// Month grid + 72-hr prep queue + upcoming agenda + add-event form.
// =============================================================================

(function () {
  const { useState } = React;
  const { C, EVT } = window.JD_THEME;
  const { card, ct, inp, bg, br, bgg, Empty, Loading, ErrorBox } = window.JD_STYLES;

  function Calendar() {
    const calQ = window.useJarvisData("calendarEvents");
    const m72Q = window.useJarvisData("meetings72");
    const calEvents = calQ.data || {};
    const m72 = m72Q.data || [];

    const { prepChecks, setPrepChecks } = window.useShared();

    const [addEventOpen, setAddEventOpen] = useState(false);
    const [newEvent, setNewEvent] = useState({ day: 1, title: "", time: "", type: "client" });

    const today = new Date();
    const todayDay = today.getDate();
    const monthName = today.toLocaleString("en-US", { month: "long" });
    const first = new Date(today.getFullYear(), today.getMonth(), 1).getDay();
    const daysInMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
    const calDays = [];
    for (let i = 0; i < first; i++) calDays.push(null);
    for (let i = 1; i <= daysInMonth; i++) calDays.push(i);

    const agenda = Object.entries(calEvents)
      .map(([d, evs]) => evs.map(e => ({ day: +d, ...e })))
      .flat()
      .sort((a, b) => a.day - b.day);

    const saveEvent = async () => {
      if (!newEvent.title.trim()) return;
      try {
        await window.JD.mutate("createEvent", newEvent);
        calQ.reload();
      } catch (e) {
        console.error("createEvent failed:", e);
      }
      setNewEvent({ day: 1, title: "", time: "", type: "client" });
      setAddEventOpen(false);
    };

    return (
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
            <div style={{ fontSize: 30, color: C.bg, letterSpacing: "0.01em", fontWeight: 500 }}>{monthName} {today.getFullYear()}</div>
            <div style={{ fontSize: 14, color: "rgba(10,21,32,0.55)" }}>{Object.values(calEvents).flat().length} events scheduled</div>
          </div>
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <button style={{ padding: "6px 14px", borderRadius: 6, border: "0.5px solid rgba(10,21,32,0.18)", background: "transparent", color: "rgba(10,21,32,0.65)", cursor: "pointer", fontSize: 14, fontFamily: "Georgia,serif" }}>◀ Prev</button>
            <button style={{ padding: "6px 14px", borderRadius: 6, border: "0.5px solid rgba(159,117,9,0.4)", background: "rgba(159,117,9,0.15)", color: C.gold, cursor: "pointer", fontSize: 14, fontFamily: "Georgia,serif" }}>Today</button>
            <button style={{ padding: "6px 14px", borderRadius: 6, border: "0.5px solid rgba(10,21,32,0.18)", background: "transparent", color: "rgba(10,21,32,0.65)", cursor: "pointer", fontSize: 14, fontFamily: "Georgia,serif" }}>Next ▶</button>
            <button onClick={() => setAddEventOpen(true)} style={{ padding: "6px 16px", borderRadius: 6, border: "0.5px solid rgba(159,117,9,0.5)", background: "rgba(159,117,9,0.2)", color: C.gold, cursor: "pointer", fontSize: 14, fontFamily: "Georgia,serif", marginLeft: 8, fontWeight: 500 }}>+ Add Event</button>
          </div>
        </div>

        {addEventOpen && (
          <div style={card({ marginBottom: 14, border: "0.5px solid rgba(159,117,9,0.4)" })}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
              <div style={{ fontSize: 13, color: C.gold, letterSpacing: "0.2em", textTransform: "uppercase" }}>New Event</div>
              <button onClick={() => setAddEventOpen(false)} style={{ background: "transparent", border: "none", color: C.muted, cursor: "pointer", fontSize: 20, padding: 0, lineHeight: 1 }}>×</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 10, marginBottom: 10 }}>
              <div>
                <label style={fieldLabel}>Title</label>
                <input value={newEvent.title} onChange={e => setNewEvent(n => ({ ...n, title: e.target.value }))} placeholder="Meeting title..." style={inp} />
              </div>
              <div>
                <label style={fieldLabel}>Day</label>
                <input type="number" min={1} max={31} value={newEvent.day} onChange={e => setNewEvent(n => ({ ...n, day: +e.target.value || 1 }))} style={inp} />
              </div>
              <div>
                <label style={fieldLabel}>Time</label>
                <input value={newEvent.time} onChange={e => setNewEvent(n => ({ ...n, time: e.target.value }))} placeholder="9:00 AM" style={inp} />
              </div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={fieldLabel}>Category</label>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {Object.entries(EVT).map(([k, v]) => (
                  <button key={k} onClick={() => setNewEvent(n => ({ ...n, type: k }))} style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 12px", borderRadius: 6, border: "0.5px solid " + (newEvent.type === k ? v.c : "rgba(222,214,185,0.12)"), background: newEvent.type === k ? v.c + "22" : "transparent", color: newEvent.type === k ? v.c : "rgba(222,214,185,0.7)", cursor: "pointer", fontSize: 13, fontFamily: "Georgia,serif" }}>
                    <div style={{ width: 8, height: 8, borderRadius: "50%", background: v.c }} />
                    {v.l}
                  </button>
                ))}
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button onClick={() => setAddEventOpen(false)} style={{ padding: "7px 16px", borderRadius: 6, border: "0.5px solid rgba(222,214,185,0.12)", background: "transparent", color: C.muted, cursor: "pointer", fontSize: 14, fontFamily: "Georgia,serif" }}>Cancel</button>
              <button onClick={saveEvent} style={bg}>Save Event</button>
            </div>
          </div>
        )}

        <div style={{ display: "flex", gap: 18, flexWrap: "wrap", marginBottom: 14 }}>
          {Object.entries(EVT).map(([k, v]) => (
            <div key={k} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <div style={{ width: 10, height: 10, borderRadius: "50%", background: v.c }} />
              <span style={{ fontSize: 14, color: "rgba(10,21,32,0.7)" }}>{v.l}</span>
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "3fr 1fr", gap: 14 }}>
          <div style={card()}>
            {calQ.loading && <Loading />}
            {calQ.error && <ErrorBox message={calQ.error.message} />}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, marginBottom: 6 }}>
              {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((d, i) => (
                <div key={i} style={{ textAlign: "left", fontSize: 12, color: C.muted, letterSpacing: "0.14em", textTransform: "uppercase", padding: "4px 6px" }}>{d}</div>
              ))}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4 }}>
              {calDays.map((d, i) => {
                const evs = d ? (calEvents[d] || []) : [];
                const isToday = d === todayDay;
                return (
                  <div key={i} style={{ minHeight: 84, padding: "6px 8px", background: d ? (isToday ? "rgba(159,117,9,0.12)" : C.card2) : "transparent", borderRadius: 6, border: d ? "0.5px solid " + (isToday ? "rgba(159,117,9,0.35)" : C.border) : "none" }}>
                    {d && <>
                      <div style={{ fontSize: 13, color: isToday ? C.gold : "rgba(222,214,185,0.7)", marginBottom: 4 }}>{d}</div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                        {evs.slice(0, 3).map((e, j) => (
                          <div key={j} style={{ display: "flex", gap: 3, alignItems: "flex-start" }}>
                            <div style={{ width: 4, height: 4, borderRadius: "50%", background: EVT[e.type]?.c, marginTop: 5, flexShrink: 0 }} />
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 12, color: "rgba(222,214,185,0.92)", lineHeight: 1.25, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.t}</div>
                              <div style={{ fontSize: 10, color: C.muted }}>{e.time}</div>
                            </div>
                          </div>
                        ))}
                        {evs.length > 3 && <div style={{ fontSize: 10, color: C.muted, paddingLeft: 4 }}>+{evs.length - 3} more</div>}
                      </div>
                    </>}
                  </div>
                );
              })}
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={card({ border: "0.5px solid rgba(212,160,23,0.25)" })}>
              <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: C.yellow, marginBottom: 12 }}>72-Hour Prep</div>
              {m72Q.loading ? <Loading /> :
               m72.length === 0 ? <Empty label="Nothing in next 72hr" /> : m72.map((m, i) => (
                <div key={i} style={{ padding: "10px 0", borderBottom: "0.5px solid " + C.border, opacity: prepChecks[i] === true ? 0.5 : 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3 }}>
                    <div style={{ width: 7, height: 7, borderRadius: "50%", background: EVT[m.type]?.c, flexShrink: 0 }} />
                    <div style={{ fontSize: 15, color: C.cream, lineHeight: 1.3, textDecoration: prepChecks[i] === true ? "line-through" : "none" }}>{m.title}</div>
                  </div>
                  <div style={{ fontSize: 13, color: C.muted, marginBottom: 8, paddingLeft: 13 }}>{m.date} · {m.time}</div>
                  {prepChecks[i] !== true ? (
                    <div style={{ display: "flex", gap: 6, paddingLeft: 13 }}>
                      <button onClick={() => setPrepChecks(p => ({ ...p, [i]: true }))} style={bgg}>Prepped</button>
                      <button onClick={() => setPrepChecks(p => ({ ...p, [i]: "no" }))} style={br}>Need Prep</button>
                    </div>
                  ) : (
                    <div style={{ fontSize: 12, color: C.green, paddingLeft: 13 }}>Prepped ✓</div>
                  )}
                </div>
              ))}
            </div>
            <div style={card()}>
              <div style={ct}>Upcoming Agenda</div>
              {agenda.length === 0 ? <Empty label="No events" /> : agenda.slice(0, 8).map((a, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 0", borderBottom: "0.5px solid rgba(222,214,185,0.06)" }}>
                  <div style={{ width: 36, textAlign: "center" }}>
                    <div style={{ fontSize: 18, color: a.day === todayDay ? C.gold : C.cream }}>{a.day}</div>
                  </div>
                  <div style={{ width: 3, height: 34, background: EVT[a.type]?.c, borderRadius: 2 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, color: C.cream, lineHeight: 1.3 }}>{a.t}</div>
                    <div style={{ fontSize: 12, color: C.muted }}>{a.time}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  const fieldLabel = { fontSize: 12, color: window.JD_THEME.C.muted, letterSpacing: "0.12em", textTransform: "uppercase", display: "block", marginBottom: 4 };

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS.Calendar = Calendar;
})();
