/* ============================================================
   Team calendar — month timeline (who's out when)
   ============================================================ */
const { useState, useEffect, useRef } = React;
function TeamCalendar({ user, requests, onOpenRequest, onNewRequest }) {
  const init = parseISO(TODAY);
  const [view, setView] = useState({ y: init.getFullYear(), m: init.getMonth() });
  const [showPending, setShowPending] = useState(true);

  const daysInMonth = new Date(view.y, view.m + 1, 0).getDate();
  const monthStart = new Date(view.y, view.m, 1);
  const monthEnd = new Date(view.y, view.m, daysInMonth);
  const days = [...Array(daysInMonth)].map((_, i) => new Date(view.y, view.m, i + 1));

  // people with any leave this month, leadership pinned + current user first
  const monthReqs = requests.filter((r) => {
    if (r.status === "declined") return false;
    if (!showPending && r.status === "pending") return false;
    return parseISO(r.from) <= monthEnd && parseISO(r.to) >= monthStart;
  });
  const peopleOrder = VP_DATA.people;

  function barFor(r) {
    const a = Math.max(1, parseISO(r.from).getDate() <= 1 || parseISO(r.from) < monthStart ? 1 : parseISO(r.from).getDate());
    const startsBefore = parseISO(r.from) < monthStart;
    const endsAfter = parseISO(r.to) > monthEnd;
    const s = startsBefore ? 1 : parseISO(r.from).getDate();
    const e = endsAfter ? daysInMonth : parseISO(r.to).getDate();
    const left = ((s - 1) / daysInMonth) * 100;
    const width = ((e - s + 1) / daysInMonth) * 100;
    return { left, width, startsBefore, endsAfter };
  }

  const todayInView = init.getFullYear() === view.y && init.getMonth() === view.m;
  const todayLeft = todayInView ? ((init.getDate() - 0.5) / daysInMonth) * 100 : null;

  return (
    <div className="vp-fade-up" style={{ display: "grid", gap: "var(--gap)" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ fontSize: 30 }}>Who's out when</h1>
          <p style={{ color: "var(--ink-3)", margin: "6px 0 0", fontSize: 15 }}>Approved and pending time off across the team.</p>
        </div>
        <Button size="md" icon="plus" onClick={onNewRequest}>Request time off</Button>
      </div>

      <Card pad="0">
        {/* toolbar */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 20px", borderBottom: "1px solid var(--line)", flexWrap: "wrap", gap: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button type="button" onClick={() => setView((v) => v.m === 0 ? { y: v.y - 1, m: 11 } : { ...v, m: v.m - 1 })} className="vp-focusable" style={navBtn}><Icon name="chevLeft" size={17} /></button>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 19, minWidth: 168, textAlign: "center" }}>{MONTHS[view.m]} {view.y}</div>
            <button type="button" onClick={() => setView((v) => v.m === 11 ? { y: v.y + 1, m: 0 } : { ...v, m: v.m + 1 })} className="vp-focusable" style={navBtn}><Icon name="chevRight" size={17} /></button>
            <Button size="sm" variant="outline" onClick={() => setView({ y: init.getFullYear(), m: init.getMonth() })}>Today</Button>
          </div>
          {/* legend */}
          <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
            {Object.values(VP_DATA.leaveTypes).map((t) => (
              <span key={t.id} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500 }}>
                <span style={{ width: 11, height: 11, borderRadius: 3, background: t.color }} /> {t.label}
              </span>
            ))}
            <label style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-2)", cursor: "pointer", fontWeight: 600 }}>
              <input type="checkbox" checked={showPending} onChange={(e) => setShowPending(e.target.checked)} style={{ accentColor: "var(--accent)", width: 15, height: 15 }} />
              Show pending
            </label>
          </div>
        </div>

        {/* timeline */}
        <div style={{ overflowX: "auto" }}>
          <div style={{ minWidth: 760 }}>
            {/* day header */}
            <div style={{ display: "flex", borderBottom: "1px solid var(--line)", position: "sticky", top: 0, background: "var(--surface)", zIndex: 2 }}>
              <div style={{ width: 176, flex: "0 0 auto", padding: "10px 16px", fontSize: 12, fontWeight: 700, color: "var(--ink-4)", letterSpacing: "0.06em", textTransform: "uppercase", borderRight: "1px solid var(--line)" }}>Team member</div>
              <div style={{ flex: 1, display: "grid", gridTemplateColumns: `repeat(${daysInMonth}, 1fr)`, position: "relative" }}>
                {days.map((d, i) => (
                  <div key={i} style={{
                    textAlign: "center", padding: "7px 0 6px", fontSize: 11,
                    background: isWeekend(d) ? "var(--surface-2)" : "transparent",
                    color: (todayInView && d.getDate() === init.getDate()) ? "var(--accent)" : "var(--ink-4)",
                    fontWeight: (todayInView && d.getDate() === init.getDate()) ? 700 : 500,
                  }}>
                    <div style={{ fontSize: 9.5, opacity: 0.7 }}>{DOW[(d.getDay() + 6) % 7][0]}</div>
                    {d.getDate()}
                  </div>
                ))}
              </div>
            </div>

            {/* rows */}
            {peopleOrder.map((p) => {
              const prs = monthReqs.filter((r) => r.person === p.id);
              const isMe = p.id === user.id;
              return (
                <div key={p.id} style={{ display: "flex", borderBottom: "1px solid var(--line)", background: isMe ? "var(--accent-soft)" : "transparent" }}>
                  <div style={{ width: 176, flex: "0 0 auto", padding: "11px 16px", display: "flex", alignItems: "center", gap: 10, borderRight: "1px solid var(--line)" }}>
                    <Avatar person={p} size={30} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.first} {p.last}{isMe && " (you)"}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{p.role === "ceo" ? "CEO" : p.team}</div>
                    </div>
                  </div>
                  <div style={{ flex: 1, position: "relative", minHeight: 52 }}>
                    {/* weekend columns */}
                    <div style={{ position: "absolute", inset: 0, display: "grid", gridTemplateColumns: `repeat(${daysInMonth}, 1fr)` }}>
                      {days.map((d, i) => <div key={i} style={{ background: isWeekend(d) ? "var(--surface-2)" : "transparent", borderRight: "1px solid var(--paper)" }} />)}
                    </div>
                    {/* today line */}
                    {todayLeft != null && <div style={{ position: "absolute", top: 0, bottom: 0, left: `${todayLeft}%`, width: 2, background: "var(--accent)", opacity: 0.55, zIndex: 1 }} />}
                    {/* bars */}
                    {prs.map((r) => {
                      const b = barFor(r);
                      const lt = VP_DATA.leaveTypes[r.type];
                      const isPending = r.status === "pending";
                      return (
                        <div key={r.id} onClick={() => onOpenRequest(r)} title={`${lt.label} · ${fmtRange(r.from, r.to)}`}
                          style={{
                            position: "absolute", top: 9, height: 34, left: `${b.left}%`, width: `calc(${b.width}% - 4px)`,
                            margin: "0 2px", borderRadius: 7, zIndex: 1, cursor: "pointer",
                            background: isPending ? lt.soft : lt.color,
                            border: isPending ? `1.5px dashed ${lt.color}` : "none",
                            color: isPending ? lt.color : "#fff",
                            display: "flex", alignItems: "center", gap: 5, padding: "0 8px",
                            fontSize: 12, fontWeight: 600, overflow: "hidden", whiteSpace: "nowrap",
                            boxShadow: isPending ? "none" : "var(--sh-sm)",
                          }}>
                          <Icon name={lt.icon} size={13} stroke={2} />
                          {b.width > 12 && <span style={{ overflow: "hidden", textOverflow: "ellipsis" }}>{lt.short}{isPending ? " ?" : ""}</span>}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { TeamCalendar });
