/* global React, window */

/* =========================================================
   Calendar Showcase — full month, May 2026, dense booking.
   Saturday-first week. Booked chips pulse soft teal.
   ========================================================= */

/* Seeded bookings for May 2026. Format: { dayOfMonth: [["HH:MM", kindIdx], ...] }
   kindIdx → calendar.slotKinds[idx]
   Friday = off (no slots rendered). Today = May 14 (highlighted). */
const BOOKINGS = {
  2:  [["10:00", 0], ["13:00", 1]],
  3:  [["11:30", 3], ["14:30", 0], ["17:00", 2]],
  4:  [["10:00", 4], ["15:00", 0]],
  5:  [["10:00", 3], ["11:30", 1], ["14:30", 2]],
  6:  [["13:00", 0], ["16:00", 1]],
  7:  [["11:00", 4], ["14:00", 2]],
  9:  [["10:30", 0], ["15:00", 1]],
  10: [["11:00", 3], ["13:30", 0], ["16:00", 2]],
  11: [["10:00", 1], ["12:30", 4], ["15:30", 0]],
  12: [["11:30", 0], ["14:00", 2]],
  13: [["10:00", 3], ["12:00", 1], ["16:00", 0]],
  14: [["10:30", 0], ["13:00", 2], ["16:30", 1]], // TODAY
  16: [["11:00", 4], ["14:30", 0]],
  17: [["13:30", 1]],
  18: [["10:00", 0], ["12:30", 3], ["15:00", 2]],
  19: [["11:00", 1], ["16:00", 0]],
  20: [["10:30", 4], ["14:00", 2]],
  21: [["11:30", 0], ["15:30", 1]],
  23: [["10:00", 2], ["14:30", 0]],
  24: [["12:00", 3], ["16:00", 1]],
  25: [["10:00", 0], ["13:30", 2], ["16:30", 4]],
  26: [["14:00", 1]],
  27: [["10:30", 0], ["15:00", 2]],
  28: [["11:00", 3], ["14:30", 1]],
  30: [["12:00", 0]],
  31: [["11:00", 1], ["14:00", 2]],
};
const TODAY = 14;
const YEAR = 2026;
const MONTH = 4; // May (0-indexed)

function Calendar() {
  const { L } = useLang();
  const C = L.calendar;
  const reduced = useReducedMotion();

  // build the grid
  const firstDay = new Date(YEAR, MONTH, 1).getDay(); // 0=Sun..6=Sat
  // Saturday-start; offset for day 1
  const offset = (firstDay - 6 + 7) % 7; // Sat=0 → 1, Sun=1 → 2, ... Fri=5 → 6
  const daysInMonth = new Date(YEAR, MONTH + 1, 0).getDate(); // 31
  const totalCells = Math.ceil((offset + daysInMonth) / 7) * 7;

  // Each cell: { day | null, isFri, isMuted }
  const cells = [];
  for (let i = 0; i < totalCells; i++) {
    const dayNum = i - offset + 1;
    const isInMonth = dayNum >= 1 && dayNum <= daysInMonth;
    const colIdx = i % 7;
    // weekday array: ["Sat","Sun","Mon","Tue","Wed","Thu","Fri"]
    const isFri = colIdx === 6;
    cells.push({
      key: i,
      day: isInMonth ? dayNum : null,
      isFri,
      isMuted: !isInMonth,
    });
  }

  // Animate in cells one by one
  const gridRef = React.useRef(null);
  React.useEffect(() => {
    if (!gridRef.current) return;
    const cellsEl = gridRef.current.querySelectorAll(".cal-cell");
    if (reduced) {
      cellsEl.forEach(c => c.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(es => es.forEach(e => {
      if (e.isIntersecting) {
        cellsEl.forEach((c, i) => {
          c.style.setProperty("--cd", `${i * 18}ms`);
          c.classList.add("in");
        });
        io.disconnect();
      }
    }), { threshold: 0.15 });
    io.observe(gridRef.current);
    return () => io.disconnect();
  }, [reduced, L]);

  // For arabic numerals optionally
  const fmtDay = (d) => d;

  const SlotChip = ({ slot, idx, dayNum }) => {
    const [time, kindIdx] = slot;
    const kind = C.slotKinds[kindIdx];
    const isIntro = kindIdx >= 3;
    const delay = ((dayNum * 7 + idx) % 13) * 0.4;
    return (
      <span className={`cal-slot ${isIntro ? "intro" : ""}`}>
        {!isIntro && <span className="glow" style={{ "--pd": `${delay}s` }} />}
        <span className="mono">{time}</span>
        <span style={{ opacity: 0.75 }}>{"  "}· {kind.split(" · ")[1] || kind}</span>
        <span className="cal-tip">{C.booked}</span>
      </span>
    );
  };

  return (
    <section className="section" id="schedule">
      <div className="container">
        <Reveal><div className="section-eyebrow">{C.eyebrow}</div></Reveal>
        <Reveal delay={60}>
          <h2 className="h-section">
            {C.headline[0]}<br/>{C.headline[1]}
          </h2>
        </Reveal>
        <Reveal delay={120}><p className="lead">{C.sub}</p></Reveal>

        <Reveal delay={180} className="cal-frame">
          <div className="cal-head">
            <div className="cal-month mono">{C.monthLabel}</div>
            <div className="cal-legend">
              {C.legend.map((lg, i) => (
                <span className="item" key={i}>
                  <span className={`lg-dot ${lg.dot}`} />
                  {lg.label}
                </span>
              ))}
            </div>
            <div className="cal-controls">
              <button className="cal-ctrl" aria-label="prev"><Icon name="arrow-left" size={14} /></button>
              <button className="cal-ctrl" aria-label="next"><Icon name="arrow-right" size={14} /></button>
            </div>
          </div>

          <div className="cal-weekdays">
            {C.weekdays.map(w => (
              <div className="cal-weekday" key={w}>{w}</div>
            ))}
          </div>

          <div className="cal-grid" ref={gridRef}>
            {cells.map(cell => {
              const bookings = cell.day ? (BOOKINGS[cell.day] || []) : [];
              const has = bookings.length > 0;
              const isToday = cell.day === TODAY;
              return (
                <div
                  key={cell.key}
                  className={[
                    "cal-cell",
                    cell.isMuted ? "muted" : "",
                    cell.isFri ? "fri" : "",
                    has ? "has" : "",
                    isToday ? "today" : "",
                  ].join(" ")}
                >
                  <div className="cal-date">
                    <span>{cell.day ?? ""}</span>
                    {isToday && <span className="heat">TODAY</span>}
                  </div>
                  {bookings.map((b, i) => (
                    <SlotChip key={i} slot={b} idx={i} dayNum={cell.day} />
                  ))}
                  {cell.isFri && cell.day && (
                    <span className="mono" style={{ fontSize: 10, color: "rgba(255,255,255,0.25)", letterSpacing: "0.1em" }}>
                      OFF
                    </span>
                  )}
                </div>
              );
            })}
          </div>

          <div className="cal-caption">{C.caption}</div>
        </Reveal>

        <div style={{ marginTop: 96 }}><DividerLine /></div>
      </div>
    </section>
  );
}

Object.assign(window, { Calendar });
