/* global React, Star, Icon, Photo */
const { useState: useStateHub, useEffect: useEffectHub } = React;

const SCHEDULE_WORKER = "https://ftw-schedule.brigham-freeth.workers.dev";

// Assign show colors to students
const SHOW_COLORS = { "Frozen": "var(--sky)", "Butter Knife": "var(--violet)", "Both": "var(--teal)" };

function isCalled(day, camper) {
  if (!camper) return false;
  const cg = camper.callGroup || "All";
  return day.calls.includes("All") || day.calls.some(c =>
    c === cg || cg.startsWith(c.split("-")[0])
  );
}

function HubPage({ navigate, user }) {
  // Map Airtable students to hub format
  const CAMPERS = (user?.students || []).map((s, i) => ({
    id: s.id,
    name: s.name,
    show: s.role ? s.role.split("·")[0]?.trim() : "FTW",
    role: s.role || null,
    callGroup: s.callGroup || "All",
    color: SHOW_COLORS[s.show] || (i % 2 === 0 ? "var(--sky)" : "var(--gold)"),
    tuition: s.tuition,
    paid: s.paid,
    balance: s.balance,
    isSAE: s.isSAE,
  }));

  const [camperId, setCamperId] = useStateHub(CAMPERS[0]?.id || "");
  const [onlyCalled, setOnlyCalled] = useStateHub(false);
  const [schedule, setSchedule] = useStateHub([]);
  const [scheduleLoading, setScheduleLoading] = useStateHub(true);

  const camper = CAMPERS.find(c => c.id === camperId) || CAMPERS[0];

  // Load real schedule from Google Sheets via Worker
  useEffectHub(() => {
    fetch(`${SCHEDULE_WORKER}/schedule`)
      .then(r => r.json())
      .then(data => {
        if (data.schedule && data.schedule.length > 0) {
          // Group into weeks
          const byWeek = {};
          data.schedule.forEach(row => {
            const wk = row.week || "Rehearsals";
            if (!byWeek[wk]) byWeek[wk] = [];
            byWeek[wk].push({ date: row.date, time: `${row.start} – ${row.end}`, title: row.location, loc: row.location, calls: row.called, scene: row.notes });
          });
          setSchedule(Object.entries(byWeek).map(([wk, days]) => ({ wk, days })));
        }
      })
      .catch(() => {}) // schedule not configured yet — show empty state
      .finally(() => setScheduleLoading(false));
  }, []);

  // find next called rehearsal from live schedule
  const flat = schedule.flatMap(w => w.days.map(d => ({ ...d, wk: w.wk })));
  const nextCall = flat.find(d => isCalled(d, camper));
  const calledCount = flat.filter(d => isCalled(d, camper)).length;

  return (
    <div style={{ background: "var(--paper-2)", minHeight: "100vh" }}>
      <div className="wrap" style={{ paddingBlock: "clamp(28px,5vw,52px)" }}>
        {/* Magic-link breadcrumb */}
        <div className="row gap-8" style={{ background: "var(--white)", border: "var(--bd-ink)", borderRadius: "var(--r-pill)",
          padding: "7px 14px", marginBottom: 20, fontSize: 13, width: "fit-content", maxWidth: "100%", flexWrap: "wrap" }}>
          <Icon name="shield" size={14} color="var(--mint)" />
          <span className="muted">Signed in as {user?.email} — bookmark this page for quick access.</span>
        </div>

        {/* Header */}
        <div className="row between" style={{ flexWrap: "wrap", gap: 16, marginBottom: 24 }}>
          <div>
            <span className="kicker"><Star size={13} fill="var(--gold-deep)" /> Family Hub</span>
            <h1 style={{ fontSize: "clamp(28px,4vw,44px)", marginTop: 8 }}>Welcome back, {user?.name || "your family"}</h1>
          </div>
          <div className="row gap-8" style={{ background: "var(--white)", border: "var(--bd-ink)", borderRadius: "var(--r-pill)", padding: 5 }}>
            {CAMPERS.map(c => (
              <button key={c.id} onClick={() => setCamperId(c.id)}
                style={{ border: 0, borderRadius: "var(--r-pill)", padding: "9px 16px", fontFamily: "var(--display)",
                  fontWeight: 500, fontSize: 15, background: camperId === c.id ? "var(--ink)" : "transparent",
                  color: camperId === c.id ? "var(--paper)" : "var(--ink)" }}>
                {c.name.split(" ")[0]}
              </button>
            ))}
          </div>
        </div>

        {/* Top cards */}
        <div className="hub-top" style={{ display: "grid", gridTemplateColumns: "1.1fr 1.5fr 1fr", gap: 18, marginBottom: 22 }}>
          {/* Role card */}
          <div className="card" style={{ padding: 22, background: "var(--white)" }}>
            <div className="row gap-12">
              <div style={{ width: 56, height: 56, borderRadius: 16, background: camper.color, border: "var(--bd-ink)",
                display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name="mask" size={28} color="var(--ink)" />
              </div>
              <div>
                <div className="muted" style={{ fontSize: 13 }}>{camper.show || "FTW 2026"}</div>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, lineHeight: 1.1 }}>
                  {camper.role || "Role TBD"}
                </div>
              </div>
            </div>
            <div className="row gap-8" style={{ marginTop: 16 }}>
              <span className="tag tag--sky"><Icon name="user" size={13} stroke={2.4} /> {camper.name}</span>
            </div>
          </div>

          {/* Next call — the hero answer */}
          <div className="card" style={{ padding: 22, background: "var(--ink)", color: "var(--paper)", position: "relative", overflow: "hidden" }}>
            <Star size={70} fill="rgba(244,166,35,.16)" style={{ position: "absolute", right: -14, bottom: -16 }} />
            <div className="row gap-8" style={{ color: "var(--gold)", fontFamily: "var(--display)", fontWeight: 600, fontSize: 13.5, letterSpacing: ".08em", textTransform: "uppercase" }}>
              <Icon name="bell" size={16} /> {camper?.name?.split(" ")[0]}'s next call
            </div>
            {nextCall ? (
              <>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, marginTop: 10 }}>{nextCall.title}</div>
                <div className="row gap-16" style={{ marginTop: 12, flexWrap: "wrap", color: "#E4DAC8" }}>
                  <span className="row gap-8" style={{ fontSize: 14.5 }}><Icon name="calendar" size={16} color="var(--gold)" /> {nextCall.date}</span>
                  <span className="row gap-8" style={{ fontSize: 14.5 }}><Icon name="clock" size={16} color="var(--gold)" /> {nextCall.time}</span>
                  <span className="row gap-8" style={{ fontSize: 14.5 }}><Icon name="pin" size={16} color="var(--gold)" /> {nextCall.loc}</span>
                </div>
              </>
            ) : (
              <div style={{ fontFamily: "var(--display)", fontWeight: 500, fontSize: 18, marginTop: 10, color: "#E4DAC8" }}>
                {scheduleLoading ? "Loading schedule…" : "Schedule coming soon!"}
              </div>
            )}
          </div>

          {/* Stat */}
          <div className="card" style={{ padding: 22, background: "var(--gold)", display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 48, lineHeight: 1 }}>{calledCount}</div>
            <div style={{ fontFamily: "var(--display)", fontWeight: 500, fontSize: 15, marginTop: 4 }}>
              rehearsals {camper.name.split(" ")[0]} is called this summer
            </div>
          </div>
        </div>

        <div className="hub-main" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 22, alignItems: "start" }}>
          {/* Schedule */}
          <div className="card" style={{ padding: "clamp(18px,3vw,28px)", background: "var(--white)" }}>
            <div className="row between" style={{ marginBottom: 18, flexWrap: "wrap", gap: 12 }}>
              <h2 style={{ fontSize: 24 }}>Rehearsal schedule</h2>
              <button onClick={() => setOnlyCalled(o => !o)} className="row gap-8"
                style={{ border: "var(--bd-ink)", background: onlyCalled ? "var(--mint)" : "var(--white)", borderRadius: "var(--r-pill)",
                  padding: "8px 14px", fontFamily: "var(--display)", fontWeight: 500, fontSize: 14 }}>
                <span style={{ width: 30, height: 18, borderRadius: 999, background: onlyCalled ? "var(--ink)" : "var(--paper-2)",
                  border: "2px solid var(--ink)", position: "relative", display: "inline-block" }}>
                  <span style={{ position: "absolute", top: 1, left: onlyCalled ? 13 : 1, width: 12, height: 12, borderRadius: "50%",
                    background: onlyCalled ? "var(--mint)" : "var(--ink)", transition: "left .15s" }} />
                </span>
                Only when {camper.name.split(" ")[0]} is called
              </button>
            </div>

            {scheduleLoading && (
              <div style={{ textAlign: "center", padding: "32px 0", color: "var(--ink-muted)", fontSize: 14 }}>
                Loading schedule…
              </div>
            )}
            {!scheduleLoading && schedule.length === 0 && (
              <div style={{ textAlign: "center", padding: "32px 0", color: "var(--ink-muted)", fontSize: 14 }}>
                Schedule coming soon — the FTW staff will post it here.
              </div>
            )}
            {schedule.map(week => {
              const visible = week.days.filter(d => !onlyCalled || isCalled(d, camper));
              if (!visible.length) return null;
              return (
                <div key={week.wk} style={{ marginBottom: 26 }}>
                  <div className="row gap-8" style={{ marginBottom: 12 }}>
                    <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 14, letterSpacing: ".06em",
                      textTransform: "uppercase", color: "var(--gold-deep)" }}>{week.wk}</span>
                    <div style={{ flex: 1, height: 2, background: "var(--paper-2)", borderRadius: 2 }} />
                  </div>
                  <div style={{ display: "grid", gap: 10 }}>
                    {visible.map((d, i) => {
                      const called = isCalled(d, camper);
                      return (
                        <div key={i} className="sched-row" style={{ display: "grid", gridTemplateColumns: "92px 1fr auto", gap: 14,
                          alignItems: "center", padding: 14, borderRadius: "var(--r-md)",
                          border: called ? "var(--bd-ink)" : "2px solid var(--paper-2)",
                          background: d.show ? "var(--coral-tint)" : called ? "var(--gold-tint)" : "var(--paper)",
                          opacity: called ? 1 : .62 }}>
                          <div>
                            <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 14.5 }}>{d.date}</div>
                            <div className="muted" style={{ fontSize: 11.5 }}>{d.time.split("–")[0].replace("Call ", "")}</div>
                          </div>
                          <div>
                            <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16.5 }}>{d.title}</div>
                            <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>{d.scene} · {d.loc}</div>
                          </div>
                          <div style={{ textAlign: "right" }}>
                            {called ? (
                              <span className="tag" style={{ background: d.show ? "var(--coral)" : "var(--mint)", color: d.show ? "#fff" : "var(--ink)", borderColor: "var(--ink)" }}>
                                <Icon name="check" size={13} stroke={3} /> {d.show ? "Show!" : "Called"}
                              </span>
                            ) : (
                              <span className="tag" style={{ background: "transparent" }}>Not needed</span>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
            <div className="row gap-12" style={{ marginTop: 6, flexWrap: "wrap" }}>
              <button className="btn btn--sm"><Icon name="calendar" size={16} /> Add to my calendar</button>
              <button className="btn btn--sm btn--ghost"><Icon name="arrow" size={15} /> Download full PDF</button>
            </div>
          </div>

          {/* Right rail */}
          <div style={{ display: "grid", gap: 18 }}>
            <div className="card" style={{ padding: 22, background: "var(--white)" }}>
              <h3 style={{ fontSize: 19, marginBottom: 14 }}>Announcements</h3>
              <div style={{ display: "grid", gap: 14 }}>
                <div style={{ paddingLeft: 14, borderLeft: "3px solid var(--teal)", fontSize: 13.5, color: "var(--ink-muted)" }}>
                  Updates and announcements from the FTW staff will appear here each week.
                </div>
              </div>
            </div>

            <div className="card" style={{ padding: 22, background: "var(--white)" }}>
              <h3 style={{ fontSize: 19, marginBottom: 14 }}>Family balance</h3>
              <div style={{ display: "grid", gap: 8, marginBottom: 14 }}>
                {CAMPERS.map(c => (
                  <div key={c.id} className="row between" style={{ fontSize: 14 }}>
                    <span className="muted">{c.name}</span>
                    <span style={{ fontFamily: "var(--display)", fontWeight: 500 }}>
                      ${c.balance.toFixed(0)}
                    </span>
                  </div>
                ))}
              </div>
              <div className="row between" style={{ paddingTop: 10, borderTop: "1.5px dashed rgba(33,29,23,.2)" }}>
                <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 15 }}>Total due</span>
                <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22 }}>
                  ${(user?.totalBalance || 0).toFixed(0)}
                </span>
              </div>
              {(user?.totalBalance > 0) && (() => {
                const totalTuition = CAMPERS.reduce((s, c) => s + (c.tuition || 0), 0);
                const totalPaid = CAMPERS.reduce((s, c) => s + (c.paid || 0), 0);
                const pct = totalTuition > 0 ? Math.round((totalPaid / totalTuition) * 100) : 0;
                return (
                  <div style={{ height: 10, borderRadius: 999, background: "var(--paper-2)", border: "2px solid var(--ink)", overflow: "hidden", margin: "12px 0 8px" }}>
                    <div style={{ width: `${pct}%`, height: "100%", background: "var(--gold)" }} />
                  </div>
                );
              })()}
              <div className="muted" style={{ fontSize: 12, marginBottom: 14 }}>Balance due in full by July 13, 2026</div>
              <button className="btn btn--gold btn--sm" style={{ width: "100%", justifyContent: "center" }}
                onClick={() => navigate("payment")}><Icon name="card" size={16} /> Make a payment</button>
            </div>

            <div className="card" style={{ padding: 22, background: "var(--white)" }}>
              <div className="row gap-8" style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
                <Icon name="bell" size={18} color="var(--coral)" /> Get text updates on Remind
              </div>
              <p className="muted" style={{ fontSize: 13.5 }}>
                Same updates the directors post on Remind — right to your phone. Join the class to get them.
              </p>
              <div className="row between" style={{ marginTop: 12, padding: "10px 14px", background: "var(--paper)",
                border: "1.5px solid var(--paper-2)", borderRadius: 10 }}>
                <span className="muted" style={{ fontSize: 12.5 }}>Text to <b style={{ color: "var(--ink)" }}>81010</b></span>
                <span style={{ fontFamily: "var(--mono)", fontWeight: 700, fontSize: 14 }}>@ftw26</span>
              </div>
            </div>

            <div className="card" style={{ padding: 22, background: "var(--sky-tint)" }}>
              <div className="row gap-8" style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
                <Icon name="ticket" size={18} /> Get your tickets
              </div>
              <p className="muted" style={{ fontSize: 14 }}>Tickets are on sale now — same price today as at the door.</p>
              <button className="btn btn--sky btn--sm" style={{ marginTop: 12 }} onClick={() => navigate("tickets")}>Reserve seats</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HubPage });
