/* ============================================================
   Team calendar — month timeline (who's out when)
   ============================================================ */
const { useState, useEffect, useRef } = React;

// Kosovo public-holiday styling — a warm amber wash, distinct from both
// the grey weekend columns and the brand-coloured leave bars.
const HOL_TINT = "rgba(180,120,10,0.13)";
const HOL_INK = "#9A6B07";

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));

  // Kosovo public holidays falling in the visible month.
  const monthHolidays = days
    .map((d) => { const h = holiday(d); return h ? { day: d.getDate(), date: d, ...h } : null; })
    .filter(Boolean);

  // 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>
            ))}
            <span 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: HOL_TINT, boxShadow: `inset 0 0 0 1.5px ${HOL_INK}` }} /> Public holiday (Kosovo)
            </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>

        {/* Kosovo public holidays this month */}
        {monthHolidays.length > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", padding: "11px 20px", borderBottom: "1px solid var(--line)", background: HOL_TINT }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: HOL_INK }}>
              <Icon name="calendar" size={14} stroke={2} /> Kosovo holidays
            </span>
            {monthHolidays.map((h) => (
              <span key={h.day} style={{
                display: "inline-flex", alignItems: "baseline", gap: 6, fontSize: 12.5, fontWeight: 600,
                color: "var(--ink-2)", background: "var(--surface)", padding: "4px 10px",
                borderRadius: "var(--r-pill)", boxShadow: `inset 0 0 0 1px ${HOL_INK}33`,
              }}>
                <span style={{ color: HOL_INK, fontWeight: 700 }}>{MONTHS_SHORT[view.m]} {h.day}</span>
                {h.name}{h.moveable && <span style={{ color: "var(--ink-4)", fontWeight: 500 }}> *</span>}
              </span>
            ))}
            {monthHolidays.some((h) => h.moveable) && (
              <span style={{ fontSize: 11.5, color: "var(--ink-4)" }}>* date follows the moon sighting and may shift a day</span>
            )}
          </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) => {
                  const hol = holiday(d);
                  const isToday = todayInView && d.getDate() === init.getDate();
                  return (
                    <div key={i}
                      title={hol ? `${hol.name} — Kosovo public holiday${hol.moveable ? " (date subject to confirmation)" : ""}` : undefined}
                      style={{
                        textAlign: "center", padding: "7px 0 6px", fontSize: 11, position: "relative",
                        background: hol ? HOL_TINT : isWeekend(d) ? "var(--surface-2)" : "transparent",
                        color: isToday ? "var(--accent)" : hol ? HOL_INK : "var(--ink-4)",
                        fontWeight: isToday || hol ? 700 : 500,
                      }}>
                      <div style={{ fontSize: 9.5, opacity: 0.7 }}>{DOW[(d.getDay() + 6) % 7][0]}</div>
                      {d.getDate()}
                      {hol && <div style={{ width: 4, height: 4, borderRadius: "50%", background: HOL_INK, margin: "2px auto 0" }} />}
                    </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) => { const hol = holiday(d); return <div key={i} title={hol ? `${hol.name} — Kosovo public holiday` : undefined} style={{ background: hol ? HOL_TINT : 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 });
