/* CalendarView (M12) — native month/week calendar of scheduled posts,
   tagged by channel, coloured by lifecycle status. Click an entry → modal;
   click a day → new post pre-filled with that date. Still syncs to ClickUp. */
(function () {
  const D = window.CROPR_DATA;
  const DAY = 864e5;
  // LOCAL calendar date (YYYY-MM-DD) — must match the day cells, which are built
  // from local Dates. Using toISOString() (UTC) here shifts entries a day off in
  // positive-offset timezones.
  const iso = (d) => { const x = new Date(d); const p = (n) => String(n).padStart(2, "0"); return `${x.getFullYear()}-${p(x.getMonth() + 1)}-${p(x.getDate())}`; };
  const dateOf = (p) => p.scheduleAt || p.dueDate || null;

  function ChannelDots({ channels }) {
    return <span style={{ display: "inline-flex" }}>{(channels || []).slice(0, 4).map((ch, i) => { const m = D.CHANNELS[ch]; if (!m) return null; return <span key={ch} title={m.name} style={{ marginLeft: i ? -4 : 0, width: 14, height: 14, borderRadius: 999, background: m.avatar, border: "1.5px solid var(--surface)" }} />; })}</span>;
  }

  function Entry({ post, onOpen }) {
    const s = D.STATUS_MAP[post.status] || { color: "#999" };
    const ref = React.useRef(null);
    const [rect, setRect] = React.useState(null);
    const thumb = window.postThumb(post);
    const when = post.scheduleAt || post.dueDate;
    const show = () => { const el = ref.current; if (el) setRect(el.getBoundingClientRect()); };
    const hide = () => setRect(null);
    let pop = null;
    if (rect) {
      const PW = 244, PH = thumb ? 286 : 96;
      let left = rect.right + 8; if (left + PW > window.innerWidth - 8) left = rect.left - PW - 8; left = Math.max(8, left);
      let top = Math.min(rect.top - 6, window.innerHeight - PH - 8); top = Math.max(8, top);
      pop = { left, top, PW, PH };
    }
    const overlay = pop && ReactDOM.createPortal(
      <div style={{ position: "fixed", left: pop.left, top: pop.top, zIndex: 90, width: pop.PW, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, boxShadow: "var(--shadow-lg)", padding: 8, pointerEvents: "none" }}>
        {thumb && <img src={thumb} alt="" style={{ width: "100%", height: 178, objectFit: "cover", borderRadius: 8, display: "block" }} />}
        <div style={{ fontSize: 12.5, fontWeight: 700, marginTop: thumb ? 8 : 2, lineHeight: 1.3 }}>{post.title}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 5 }}>
          <ChannelDots channels={post.channels} />
          {when && <span style={{ fontSize: 11, color: "var(--fg3)" }}>{new Date(when).toLocaleString("en-GB", { weekday: "short", day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })}</span>}
        </div>
        <div style={{ marginTop: 6 }}><StatusBadge status={post.status} /></div>
      </div>, document.body);
    return (
      <div ref={ref} onClick={(e) => { e.stopPropagation(); onOpen(post.id); }} onMouseEnter={show} onMouseLeave={hide} title={post.title}
        style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 6px", borderRadius: 6, cursor: "pointer",
          background: s.color + "16", borderLeft: `3px solid ${s.color}`, marginBottom: 3, overflow: "hidden" }}>
        <ChannelDots channels={post.channels} />
        <span style={{ fontSize: 11, fontWeight: 600, color: "var(--fg1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{post.title}</span>
        {overlay}
      </div>
    );
  }

  function Legend() {
    return (
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        {D.STATUS.filter((s) => !["parked"].includes(s.id)).map((s) => (
          <span key={s.id} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--fg3)" }}>
            <span style={{ width: 9, height: 9, borderRadius: 3, background: s.color }} />{s.label}
          </span>
        ))}
      </div>
    );
  }

  function CalendarView({ posts, onOpen, onAdd }) {
    const [view, setView] = React.useState("month");
    const [cursor, setCursor] = React.useState(() => { const d = new Date(); d.setHours(0, 0, 0, 0); return d; });
    const byDay = {};
    posts.forEach((p) => { const d = dateOf(p); if (d) (byDay[iso(d)] = byDay[iso(d)] || []).push(p); });

    const todayISO = iso(new Date());
    const shift = (n) => { const d = new Date(cursor); if (view === "month") d.setMonth(d.getMonth() + n); else d.setDate(d.getDate() + n * 7); setCursor(d); };

    // build day cells
    let cells = [], title = "";
    if (view === "month") {
      const y = cursor.getFullYear(), mo = cursor.getMonth();
      title = cursor.toLocaleDateString("en-GB", { month: "long", year: "numeric" });
      const first = new Date(y, mo, 1);
      const startDow = (first.getDay() + 6) % 7; // Monday-start
      const start = new Date(first.getTime() - startDow * DAY);
      for (let i = 0; i < 42; i++) { const d = new Date(start.getTime() + i * DAY); cells.push({ d, dim: d.getMonth() !== mo }); }
    } else {
      const dow = (cursor.getDay() + 6) % 7;
      const start = new Date(cursor.getTime() - dow * DAY);
      title = "Week of " + start.toLocaleDateString("en-GB", { day: "2-digit", month: "short" });
      for (let i = 0; i < 7; i++) cells.push({ d: new Date(start.getTime() + i * DAY), dim: false });
    }

    const dows = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    const cellH = view === "month" ? 118 : 460;

    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
          <Segmented value={view} onChange={setView} options={[{ value: "month", label: "Month", icon: "calendar" }, { value: "week", label: "Week", icon: "calendar-days" }]} />
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <Button size="sm" variant="secondary" icon="chevron-left" onClick={() => shift(-1)} />
            <span style={{ fontSize: 15, fontWeight: 700, minWidth: 160, textAlign: "center" }}>{title}</span>
            <Button size="sm" variant="secondary" icon="chevron-right" onClick={() => shift(1)} />
            <Button size="sm" variant="ghost" onClick={() => { const d = new Date(); d.setHours(0, 0, 0, 0); setCursor(d); }}>Today</Button>
          </div>
          <div style={{ flex: 1 }} />
          <Button variant="primary" icon="plus" onClick={() => onAdd(new Date().toISOString())}>New post</Button>
        </div>

        <Card pad={0} style={{ overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)" }}>
            {dows.map((d) => <div key={d} style={{ padding: "10px 12px", fontSize: 11, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".04em", borderBottom: "1px solid var(--border)", background: "var(--bg-subtle)" }}>{d}</div>)}
            {cells.map((c, i) => {
              const key = iso(c.d); const items = byDay[key] || []; const isToday = key === todayISO;
              return (
                <div key={i} onClick={() => onAdd(new Date(c.d.getTime() + 12 * 3600e3).toISOString())}
                  style={{ height: cellH, boxSizing: "border-box", overflow: "hidden", padding: 8, borderRight: (i % 7 !== 6) ? "1px solid var(--border)" : "none", borderBottom: "1px solid var(--border)",
                    background: c.dim ? "var(--bg-subtle)" : "var(--surface)", cursor: "pointer", opacity: c.dim ? 0.55 : 1 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                    <span style={{ fontSize: 12, fontWeight: isToday ? 800 : 600, color: isToday ? "#fff" : "var(--fg2)",
                      background: isToday ? "var(--accent)" : "transparent", width: 22, height: 22, borderRadius: 999, display: "grid", placeItems: "center" }}>{c.d.getDate()}</span>
                  </div>
                  {items.slice(0, view === "month" ? 3 : 20).map((p) => <Entry key={p.id} post={p} onOpen={onOpen} />)}
                  {view === "month" && items.length > 3 && <span style={{ fontSize: 10.5, color: "var(--fg3)" }}>+{items.length - 3} more</span>}
                </div>
              );
            })}
          </div>
        </Card>

        <div style={{ marginTop: 14 }}><Legend /></div>
      </div>
    );
  }
  window.CalendarView = CalendarView;
})();
