/* global React */
// Weekend Schedule page
// Month → list of weekend pairs (Sat/Sun) → for each: table of teams × days
// with dropdowns to pick an agent. Persists to localStorage.

const { useState: useStateW, useMemo: useMemoW, useEffect: useEffectW } = React;

const TEAMS = [
  { id: "APAC",  label: "APAC",     desc: "L1 · Asia-Pacific" },
  { id: "EMEA",  label: "EMEA",     desc: "L1 · Europe / MEA" },
  { id: "LATAM", label: "LATAM",    desc: "L1 · Latin America" },
  { id: "L2",    label: "L2 Team",  desc: "Tier-2 escalations" },
];

function getAgentsForTeam(people, teamId) {
  if (teamId === "L2") return people.filter(p => p.team === "L2");
  return people.filter(p => p.team === "L1" && p.region === teamId);
}

function getWeekendsInMonth(year, month) {
  // month is 0-indexed
  const out = [];
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  for (let d = 1; d <= daysInMonth; d++) {
    const date = new Date(year, month, d);
    if (date.getDay() === 6) { // Saturday
      const sat = new Date(year, month, d);
      const sun = new Date(year, month, d + 1);
      out.push({ sat, sun });
    }
  }
  return out;
}

function fmtMonthYear(y, m) {
  return new Date(y, m, 1).toLocaleString("en-US", { month: "long", year: "numeric" });
}
function fmtDayShort(date) {
  return date.toLocaleString("en-US", { weekday: "short", month: "short", day: "numeric" });
}
function fmtDateKey(date) {
  // Local-date YYYY-MM-DD (toISOString would shift to UTC and miss the day in -tz)
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}
function fmtDayNum(date) {
  return date.getDate();
}

const STORAGE_KEY = "cs_weekend_signup_v1";

// Seed: pre-populate May 30/31 from the spreadsheet
const SEED = {
  "2026-05-30__APAC":  "Aabid",
  "2026-05-30__EMEA":  "Omer",
  "2026-05-30__LATAM": "J.C.",
  "2026-05-30__L2":    "Tomas",
  "2026-05-31__APAC":  "Juhi",
  "2026-05-31__EMEA":  "Milena",
  "2026-05-31__LATAM": "Michael",
  "2026-05-31__L2":    "Tomas",
};

function loadSelections() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { ...SEED };
    return { ...SEED, ...JSON.parse(raw) };
  } catch {
    return { ...SEED };
  }
}

function WeekendSignup({ people: peopleProp, selections: selectionsProp, setSelections: setSelectionsProp }) {
  const people = peopleProp || window.CS_DATA.people;
  const now = new Date(2026, 4, 27); // anchor: May 27, 2026
  const [year, setYear] = useStateW(now.getFullYear());
  const [month, setMonth] = useStateW(now.getMonth());

  // Either driven by parent (shared state) or local fallback
  const [localSelections, setLocalSelections] = useStateW(loadSelections);
  const selections = selectionsProp !== undefined ? selectionsProp : localSelections;
  const setSelections = setSelectionsProp || setLocalSelections;

  const [savedFlash, setSavedFlash] = useStateW(false);

  useEffectW(() => {
    // Only persist locally when parent isn't driving state
    if (selectionsProp === undefined) {
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(localSelections)); } catch {}
    }
  }, [localSelections, selectionsProp]);

  const weekends = useMemoW(() => getWeekendsInMonth(year, month), [year, month]);

  const goPrev = () => {
    const m = month - 1;
    if (m < 0) { setMonth(11); setYear(year - 1); }
    else setMonth(m);
  };
  const goNext = () => {
    const m = month + 1;
    if (m > 11) { setMonth(0); setYear(year + 1); }
    else setMonth(m);
  };

  const setSelection = (dateKey, teamId, name) => {
    setSelections(s => {
      const next = { ...s };
      const k = `${dateKey}__${teamId}`;
      if (!name) delete next[k];
      else next[k] = name;
      return next;
    });
    setSavedFlash(true);
    setTimeout(() => setSavedFlash(false), 1400);
  };

  // counts
  const totalSlots = weekends.length * 2 * TEAMS.length;
  const filledSlots = weekends.reduce((acc, w) => {
    return acc + TEAMS.reduce((a, t) => {
      const sk = selections[`${fmtDateKey(w.sat)}__${t.id}`] ? 1 : 0;
      const dk = selections[`${fmtDateKey(w.sun)}__${t.id}`] ? 1 : 0;
      return a + sk + dk;
    }, 0);
  }, 0);

  // Agents signed up (per agent count) for this month
  const agentCounts = useMemoW(() => {
    const counts = {};
    weekends.forEach(w => {
      [w.sat, w.sun].forEach(d => {
        TEAMS.forEach(t => {
          const n = selections[`${fmtDateKey(d)}__${t.id}`];
          if (n) counts[n] = (counts[n] || 0) + 1;
        });
      });
    });
    return Object.entries(counts).sort((a, b) => b[1] - a[1]);
  }, [selections, weekends]);

  return (
    <div className="ws-root">
      {/* Header */}
      <header className="ws-header">
        <div>
          <div className="ws-eyebrow">
            Weekend coverage schedule
          </div>
          <h1 className="ws-title">{fmtMonthYear(year, month)}</h1>
        </div>

        <div className="ws-month-nav">
          <button className="ws-month-btn" onClick={goPrev} aria-label="Previous month">‹</button>
          <button className="ws-month-btn ws-month-today" onClick={() => { setYear(now.getFullYear()); setMonth(now.getMonth()); }}>
            This month
          </button>
          <button className="ws-month-btn" onClick={goNext} aria-label="Next month">›</button>
        </div>

        <div className="ws-stats">
          <div className="ws-stat">
            <div className="ws-stat-num">{weekends.length}</div>
            <div className="ws-stat-label">Weekends</div>
          </div>
          <div className="ws-stat">
            <div className="ws-stat-num">
              <span className="ws-stat-filled">{filledSlots}</span>
              <span className="ws-stat-total">/ {totalSlots}</span>
            </div>
            <div className="ws-stat-label">Slots filled</div>
          </div>
          <div className={`ws-saved-pill ${savedFlash ? "is-flashing" : ""}`}>
            <span className="ws-saved-dot" />
            Auto-saved
          </div>
        </div>
      </header>

      <div className="ws-body">
        {/* Main: weekend cards */}
        <div className="ws-weekends">
          {weekends.map(({ sat, sun }, idx) => (
            <WeekendCard
              key={fmtDateKey(sat)}
              idx={idx + 1}
              sat={sat}
              sun={sun}
              people={people}
              selections={selections}
              setSelection={setSelection}
            />
          ))}
        </div>

        {/* Sidebar: summary */}
        <aside className="ws-sidebar">
          <section className="ws-side-card">
            <h3>Scheduled this month</h3>
            {agentCounts.length === 0 && (
              <div className="ws-empty">Nobody scheduled yet.</div>
            )}
            <ul className="ws-signup-list">
              {agentCounts.map(([name, count]) => (
                <li key={name}>
                  <span className="mc-avatar mc-avatar-weekend">{name[0]}</span>
                  <span className="ws-signup-name">{name}</span>
                  <span className="ws-signup-count">×{count}</span>
                </li>
              ))}
            </ul>
          </section>

          <section className="ws-side-card ws-side-card-help">
            <h3>How it works</h3>
            <ol className="ws-help">
              <li>Pick the month using the arrows above.</li>
              <li>For each weekend, choose one agent per team for Saturday and Sunday.</li>
              <li>Selections auto-save to your device — coordinator can review the summary →</li>
            </ol>
          </section>
        </aside>
      </div>
    </div>
  );
}

function WeekendCard({ idx, sat, sun, people, selections, setSelection }) {
  const satKey = fmtDateKey(sat);
  const sunKey = fmtDateKey(sun);

  const peopleByName = useMemoW(() => {
    const m = new Map();
    people.forEach(p => m.set(p.name, p));
    return m;
  }, [people]);

  const hasAnySelection = TEAMS.some(t =>
    selections[`${satKey}__${t.id}`] || selections[`${sunKey}__${t.id}`]
  );

  return (
    <section className="ws-weekend-card">
      <header className="ws-weekend-head">
        <div className="ws-weekend-label">Weekend {idx}</div>
        <div className="ws-weekend-dates">
          <span className="ws-date-block">
            <span className="ws-date-dow">SAT</span>
            <span className="ws-date-num">{fmtDayNum(sat)}</span>
          </span>
          <span className="ws-date-block">
            <span className="ws-date-dow">SUN</span>
            <span className="ws-date-num">{fmtDayNum(sun)}</span>
          </span>
        </div>
      </header>

      <div className="ws-table">
        <div className="ws-table-row ws-table-head">
          <div>Team</div>
          <div>{fmtDayShort(sat)}</div>
          <div>{fmtDayShort(sun)}</div>
        </div>
        {TEAMS.map(team => {
          const agents = getAgentsForTeam(people, team.id);
          const satVal = selections[`${satKey}__${team.id}`] || "";
          const sunVal = selections[`${sunKey}__${team.id}`] || "";
          return (
            <div key={team.id} className="ws-table-row">
              <div className="ws-team-cell">
                <div className="ws-team-name">{team.label}</div>
                <div className="ws-team-desc">{team.desc}</div>
              </div>
              <AgentSelect
                value={satVal}
                agents={agents}
                onChange={(v) => setSelection(satKey, team.id, v)}
                filled={!!satVal}
              />
              <AgentSelect
                value={sunVal}
                agents={agents}
                onChange={(v) => setSelection(sunKey, team.id, v)}
                filled={!!sunVal}
              />
            </div>
          );
        })}
      </div>

      {hasAnySelection && (
        <div className="ws-coverage">
          <div className="ws-coverage-head">
            <span className="ws-coverage-title">Shift coverage</span>
            <span className="ws-coverage-sub">UTC · 24h</span>
          </div>
          <div className="ws-coverage-grid">
            <ShiftTimeline label={fmtDayShort(sat)} dayKey={satKey}
              peopleByName={peopleByName} selections={selections} />
            <ShiftTimeline label={fmtDayShort(sun)} dayKey={sunKey}
              peopleByName={peopleByName} selections={selections} />
          </div>
        </div>
      )}
    </section>
  );
}

function ShiftTimeline({ label, dayKey, peopleByName, selections }) {
  const TICKS = [0, 4, 8, 12, 16, 20, 24];
  return (
    <div className="ws-tl">
      <div className="ws-tl-label">{label}</div>
      <div className="ws-tl-rows">
        {TEAMS.map(team => {
          const name = selections[`${dayKey}__${team.id}`];
          const person = name ? peopleByName.get(name) : null;
          const ws = person?.weekendShift;
          const frags = ws
            ? buildShiftFragments(ws.start, ws.end)
            : [];
          return (
            <div key={team.id} className="ws-tl-row">
              <div className="ws-tl-row-label">{team.label}</div>
              <div className="ws-tl-track">
                {frags.map((f, i) => (
                  <div
                    key={i}
                    className={`ws-tl-bar ws-tl-bar-${team.id.toLowerCase()}`}
                    style={{ left: `${f.start * 100}%`, width: `${f.width * 100}%` }}
                    title={`${name} · ${ws.start}–${ws.end} UTC`}
                  >
                    {f.width > 0.10 && <span className="ws-tl-bar-name">{name}</span>}
                  </div>
                ))}
                {!person && <div className="ws-tl-empty">not scheduled</div>}
              </div>
            </div>
          );
        })}
      </div>
      <div className="ws-tl-axis">
        {TICKS.map(h => (
          <span key={h} style={{ left: `${(h / 24) * 100}%` }}>
            {String(h).padStart(2, "0")}
          </span>
        ))}
      </div>
    </div>
  );
}

function buildShiftFragments(start, end) {
  const s = parseShiftHour(start);
  const e = parseShiftHour(end);
  if (s == null || e == null) return [];
  // wraps past midnight → split into two fragments
  if (e <= s) {
    return [
      { start: s / 24,  width: (24 - s) / 24 },
      { start: 0,       width: e / 24 },
    ];
  }
  return [{ start: s / 24, width: (e - s) / 24 }];
}

function parseShiftHour(t) {
  if (!t) return null;
  const m = /^(\d{1,2}):(\d{2})$/.exec(t);
  if (!m) return null;
  return +m[1] + (+m[2]) / 60;
}

function AgentSelect({ value, agents, onChange, filled }) {
  return (
    <div className={`ws-select-wrap ${filled ? "is-filled" : "is-empty"}`}>
      <select
        className="ws-select"
        value={value}
        onChange={(e) => onChange(e.target.value)}
      >
        <option value="">— pick agent —</option>
        {agents.map(a => (
          <option key={a.name} value={a.name}>{a.name}</option>
        ))}
      </select>
      <span className="ws-select-caret">▾</span>
    </div>
  );
}

window.WeekendSignup = WeekendSignup;
