// Schedule — calendar / list of upcoming and past matches

const SchedulePage = ({ persona, onOpenLobby, matches, onRequestReschedule }) => {
  const D = window.NASEF_DATA;
  const [view, setView] = React.useState("list");
  const [rescheduleMatch, setRescheduleMatch] = React.useState(null);

  const all = matches || D.matches;

  return (
    <div>
      <PageHeader
        eyebrow="Hamilton SSBU · Pacific Coast"
        title="Schedule"
        subtitle="All your team's regular season matches. Click any match to open its lobby."
        actions={[
          <Tabs key="t" value={view} onChange={setView} items={[
            { value: "list", label: "List" },
            { value: "week", label: "By week" },
          ]} />,
          persona === "coach" && <button key="resch" className="btn"><IconCalendar size={14} />Request reschedule</button>,
        ].filter(Boolean)}
      />

      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: 16 }}>
          {view === "list" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {all.map(m => (
                <div key={m.id} style={{ position: "relative" }}>
                  <MatchRow match={m} schools={D.schoolsById} onClick={() => onOpenLobby(m.id)} />
                  {persona === "coach" && m.status === "upcoming" && (
                    <button className="btn ghost sm" style={{ position: "absolute", right: 60, top: "50%", transform: "translateY(-50%)" }}
                      onClick={(e) => { e.stopPropagation(); setRescheduleMatch(m); }}>
                      <IconClock size={12} /> Reschedule
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}
          {view === "week" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {Array.from({ length: 8 }, (_, i) => i + 1).map(week => {
                const wmatches = all.filter(m => m.week === week);
                return (
                  <div key={week} style={{ borderRadius: "var(--r-md)", border: "1px solid var(--border-soft)", overflow: "hidden" }}>
                    <div style={{ padding: "10px 14px", background: "var(--bg-base)", display: "flex", alignItems: "center", gap: 12 }}>
                      <span className="upper" style={{ color: "var(--nasef-orange-soft)" }}>Week {week}</span>
                      <span className="muted" style={{ fontSize: 12 }}>
                        {wmatches[0] ? new Date(wmatches[0].date).toLocaleDateString("en-US", { weekday: "long", month: "short", day: "numeric" }) : "—"}
                      </span>
                      <span className="spacer" />
                      {wmatches[0] && wmatches[0].status === "complete" && <span className="badge complete">Complete</span>}
                      {wmatches[0] && wmatches[0].status === "live" && <span className="badge live"><span className="dot" />LIVE</span>}
                      {wmatches[0] && wmatches[0].status === "upcoming" && <span className="badge upcoming">Upcoming</span>}
                    </div>
                    <div style={{ padding: 6 }}>
                      {wmatches.map(m => <MatchRow key={m.id} match={m} schools={D.schoolsById} onClick={() => onOpenLobby(m.id)} compact />)}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {rescheduleMatch && (
        <RescheduleModal match={rescheduleMatch} onClose={() => setRescheduleMatch(null)} onSubmit={onRequestReschedule} />
      )}
    </div>
  );
};

const RescheduleModal = ({ match, onClose, onSubmit }) => {
  const D = window.NASEF_DATA;
  const [date, setDate] = React.useState(match.date);
  const [time, setTime] = React.useState(match.time);
  const [reason, setReason] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);

  const handleSubmit = () => {
    if (onSubmit) onSubmit({ matchId: match.id, date, time, reason });
    setSubmitted(true);
    setTimeout(() => onClose(), 1600);
  };

  const opp = D.schoolsById[match.away === "ham" ? match.home : match.away];

  return (
    <div style={{ position: "fixed", inset: 0, background: "var(--bg-overlay)", backdropFilter: "blur(4px)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center", padding: 40 }} onClick={onClose}>
      <div className="card" style={{ width: 480, padding: 0 }} onClick={e => e.stopPropagation()}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-soft)", display: "flex", justifyContent: "space-between" }}>
          <div>
            <h2 style={{ fontSize: 18 }}>Request reschedule</h2>
            <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>vs. {opp.name} · Week {match.week}</div>
          </div>
          <button className="btn ghost icon" onClick={onClose}><IconX size={14} /></button>
        </div>
        {submitted ? (
          <div style={{ padding: 40, textAlign: "center" }}>
            <div style={{ width: 48, height: 48, borderRadius: 99, background: "rgba(45,212,120,0.15)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
              <IconCheck size={22} />
            </div>
            <h3 style={{ marginBottom: 6 }}>Request sent</h3>
            <p className="muted" style={{ fontSize: 13 }}>The opposing coach and league admin will be notified. You'll see status in your inbox.</p>
          </div>
        ) : (
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div><label className="label">New date</label><input className="input" type="date" value={date} onChange={e => setDate(e.target.value)} /></div>
              <div><label className="label">New time</label><input className="input" type="time" value={time} onChange={e => setTime(e.target.value)} /></div>
            </div>
            <div>
              <label className="label">Reason (visible to opposing coach + admin)</label>
              <textarea className="textarea" rows={3} placeholder="Conflict with school assembly, AP testing, etc." value={reason} onChange={e => setReason(e.target.value)} />
            </div>
            <Toast kind="info" body="Reschedules require approval from both opposing coach and CIF admin. Default response window is 48 hours." />
            <div className="row" style={{ justifyContent: "flex-end", gap: 8 }}>
              <button className="btn ghost" onClick={onClose}>Cancel</button>
              <button className="btn primary" onClick={handleSubmit}>Send request</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.SchedulePage = SchedulePage;
window.RescheduleModal = RescheduleModal;
