/* global React, Icon */
/* Chantelle — booking calendar */
const { useState: useStateC } = React;

function Calendar({ selected, onSelect, openDays }){
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const [view, setView] = useStateC({ y: today.getFullYear(), m: today.getMonth() });

  const first = new Date(view.y, view.m, 1);
  const startDow = first.getDay();
  const daysInMonth = new Date(view.y, view.m + 1, 0).getDate();
  const monthLabel = first.toLocaleDateString([], { month: "long", year: "numeric" });

  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const atFloor = view.y === today.getFullYear() && view.m === today.getMonth();
  const prev = () => { if (atFloor) return; setView((v) => (v.m === 0 ? { y: v.y - 1, m: 11 } : { y: v.y, m: v.m - 1 })); };
  const next = () => setView((v) => (v.m === 11 ? { y: v.y + 1, m: 0 } : { y: v.y, m: v.m + 1 }));

  const sameDay = (a, d) => a && a.getFullYear() === view.y && a.getMonth() === view.m && a.getDate() === d;
  const isPast = (d) => new Date(view.y, view.m, d) < today;
  const isClosed = (d) => Array.isArray(openDays) && !openDays[new Date(view.y, view.m, d).getDay()];
  const disabled = (d) => isPast(d) || isClosed(d);

  return (
    <div className="cal">
      <div className="cal-top">
        <h3 className="cal-month">{monthLabel}</h3>
        <div className="cal-nav">
          <button onClick={prev} aria-label="Previous month" disabled={atFloor} style={atFloor ? { opacity: .35, cursor: "default" } : {}}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
          </button>
          <button onClick={next} aria-label="Next month">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
          </button>
        </div>
      </div>
      <div className="cal-grid">
        {["Su","Mo","Tu","We","Th","Fr","Sa"].map((d) => <div key={d} className="cal-dow">{d}</div>)}
        {cells.map((d, k) => d === null
          ? <div key={"e" + k} />
          : (
            <button key={k}
              className={"cal-day" + (sameDay(selected, d) ? " is-sel" : "") + (sameDay(today, d) ? " is-today" : "")}
              disabled={disabled(d)}
              onClick={() => onSelect(new Date(view.y, view.m, d))}>
              {d}
            </button>
          )
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Calendar });
