// Horizontal timeline: regions as rows, dates as columns.
// The "at a glance" view for comparing holidays across countries.

const { useState, useMemo, useRef, useEffect } = React;

// ---- date helpers ----
const ISO = (d) => {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
};
const parseISO = (s) => {
  const [y, m, d] = s.split("-").map(Number);
  return new Date(y, m - 1, d);
};
const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
const sameDay = (a, b) => a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate();
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const DOW = ["S","M","T","W","T","F","S"];

// Build an array of day cells for a given window
function buildDays(start, count) {
  const days = [];
  for (let i = 0; i < count; i++) days.push(addDays(start, i));
  return days;
}

// Map holidays per country into a quick-lookup object: { "US": {"2026-01-01": {...}} }
function buildLookup() {
  const out = {};
  for (const [code, list] of Object.entries(window.HOLIDAYS)) {
    out[code] = {};
    for (const h of list) out[code][h.d] = h;
  }
  return out;
}

function HolidayTimeline({ selectedCodes, windowDays, startDate, showWeekends, onCellClick, highlightDate }) {
  const lookup = useMemo(buildLookup, []);
  const countries = useMemo(
    () => window.COUNTRIES.filter(c => selectedCodes.includes(c.code)),
    [selectedCodes]
  );
  const allDays = useMemo(() => buildDays(startDate, windowDays), [startDate, windowDays]);
  const days = useMemo(
    () => showWeekends ? allDays : allDays.filter(d => d.getDay() !== 0 && d.getDay() !== 6),
    [allDays, showWeekends]
  );

  // cell width scales based on window size — tighter for quarters, roomier for weeks
  const cellW = windowDays <= 7 ? 96 : windowDays <= 31 ? 44 : 22;
  const rowH = 56;

  // Month header spans
  const monthSpans = useMemo(() => {
    const spans = [];
    let cur = null;
    for (const d of days) {
      const key = `${d.getFullYear()}-${d.getMonth()}`;
      if (!cur || cur.key !== key) {
        cur = { key, month: d.getMonth(), year: d.getFullYear(), count: 1 };
        spans.push(cur);
      } else {
        cur.count++;
      }
    }
    return spans;
  }, [days]);

  // Today marker index
  const today = new Date();
  today.setHours(0,0,0,0);
  const todayIdx = days.findIndex(d => sameDay(d, today));

  // count holidays across selected countries per day — for the "overlap" heat strip on top
  const overlapByIdx = useMemo(() => {
    return days.map(d => {
      const iso = ISO(d);
      let c = 0;
      for (const code of selectedCodes) if (lookup[code]?.[iso]) c++;
      return c;
    });
  }, [days, selectedCodes, lookup]);

  return (
    <div className="ght-wrap">
      <div className="ght-scroll">
        <div className="ght-grid" style={{ "--cell-w": `${cellW}px`, "--row-h": `${rowH}px`, "--label-w": `220px` }}>
          {/* corner */}
          <div className="ght-corner">
            <div className="ght-corner-label">REGION</div>
            <div className="ght-corner-sub">{selectedCodes.length} selected</div>
          </div>

          {/* overlap heat strip */}
          <div className="ght-overlap-row">
            {days.map((d, i) => {
              const n = overlapByIdx[i];
              const max = selectedCodes.length || 1;
              const intensity = n / max;
              return (
                <div key={i} className="ght-overlap-cell" title={n ? `${n} of ${max} regions off` : ""}>
                  {n > 0 && (
                    <div
                      className="ght-overlap-bar"
                      style={{
                        height: `${Math.max(4, intensity * 100)}%`,
                        opacity: 0.25 + intensity * 0.75,
                      }}
                    />
                  )}
                </div>
              );
            })}
          </div>

          {/* month header */}
          <div className="ght-month-corner" />
          <div className="ght-month-row">
            {monthSpans.map((s, i) => (
              <div key={i} className="ght-month" style={{ width: `calc(var(--cell-w) * ${s.count})` }}>
                <span className="ght-month-name">{MONTHS[s.month]}</span>
                <span className="ght-month-year">{s.year}</span>
              </div>
            ))}
          </div>

          {/* day header */}
          <div className="ght-day-corner" />
          <div className="ght-day-row">
            {days.map((d, i) => {
              const isWeekend = d.getDay() === 0 || d.getDay() === 6;
              const isToday = todayIdx === i;
              return (
                <div
                  key={i}
                  className={`ght-day ${isWeekend ? "is-weekend" : ""} ${isToday ? "is-today" : ""}`}
                >
                  <div className="ght-day-num">{d.getDate()}</div>
                  {windowDays <= 31 && <div className="ght-day-dow">{DOW[d.getDay()]}</div>}
                </div>
              );
            })}
          </div>

          {/* country rows */}
          {countries.map((c) => (
            <React.Fragment key={c.code}>
              <div className="ght-row-label">
                <div className="ght-flag">{c.flag}</div>
                <div className="ght-row-text">
                  <div className="ght-row-name">{c.name}</div>
                  <div className="ght-row-meta">{c.code} · {c.tz}</div>
                </div>
              </div>
              <div className="ght-row-cells">
                {days.map((d, i) => {
                  const iso = ISO(d);
                  const h = lookup[c.code]?.[iso];
                  const isWeekend = d.getDay() === 0 || d.getDay() === 6;
                  const isToday = todayIdx === i;
                  const isHighlighted = highlightDate && sameDay(d, highlightDate);
                  return (
                    <div
                      key={i}
                      className={`ght-cell ${isWeekend ? "is-weekend" : ""} ${isToday ? "is-today" : ""} ${h ? "is-holiday" : ""} ${isHighlighted ? "is-highlighted" : ""}`}
                      onClick={() => onCellClick && onCellClick({ country: c, date: d, holiday: h })}
                      title={h ? `${h.n} — ${c.name}` : ""}
                    >
                      {h && (
                        <div className="ght-holiday">
                          <div className="ght-holiday-dot" />
                          {windowDays <= 31 && <div className="ght-holiday-name">{h.n}</div>}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}

window.HolidayTimeline = HolidayTimeline;
window.hlpBuildLookup = buildLookup;
window.hlpISO = ISO;
window.hlpParseISO = parseISO;
window.hlpAddDays = addDays;
window.hlpSameDay = sameDay;
window.hlpMonths = MONTHS;
