/* ============================================================
   Manager mode — DIV Tour Setup
   Publish & edit the weekly Saturday/Sunday tee times.
   ============================================================ */
function inputToLabel(v) {
  // "07:30" -> "7:30 AM"
  const [h, m] = v.split(":").map(Number);
  const ap = h >= 12 ? "PM" : "AM";
  const hh = h % 12 === 0 ? 12 : h % 12;
  return `${hh}:${String(m).padStart(2, "0")} ${ap}`;
}
function labelToInput(label) {
  const mins = window.YCC.parseTime(label);
  const h = Math.floor(mins / 60), m = mins % 60;
  return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}

// A full-width add-on toggle row (icon · name · meta · switch) used in Tour Setup.
function SideToggle({ on, icon, name, meta, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 11, padding: "11px 12px", borderRadius: 10, textAlign: "left", width: "100%",
      border: "1.5px solid " + (on ? "var(--accent)" : "var(--line-strong)"),
      background: on ? "color-mix(in srgb,var(--accent) 9%,var(--surface))" : "var(--surface)", transition: "all .14s",
    }}>
      <span style={{ width: 34, height: 34, borderRadius: "50%", flex: "0 0 auto", display: "grid", placeItems: "center", background: on ? "var(--accent)" : "var(--surface-2)", color: on ? "#1b1404" : "var(--ink-soft)" }}>
        <Icon name={icon} size={16} />
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: "block", fontSize: 13.5, fontWeight: 700 }}>{name}</span>
        <span className="faint" style={{ fontSize: 11 }}>{meta}</span>
      </span>
      <span style={{ width: 40, height: 23, borderRadius: 999, padding: 3, background: on ? "var(--brand)" : "var(--line-strong)", display: "flex", justifyContent: on ? "flex-end" : "flex-start", flex: "0 0 auto", transition: "background .18s" }}>
        <span style={{ width: 17, height: 17, borderRadius: "50%", background: "#fff", boxShadow: "0 1px 2px rgba(0,0,0,.25)" }}></span>
      </span>
    </button>
  );
}

function ManagerDay({ day, slots, onAdd, onEdit, onRemove }) {
  const Y = window.YCC;
  const sorted = Y.sortByTime(slots);
  const [newTime, setNewTime] = useState("");
  const [editingId, setEditingId] = useState(null);
  const [editVal, setEditVal] = useState("");
  const claimed = sorted.reduce((n, s) => n + s.players.length, 0);
  const capacity = sorted.length * 4;

  return (
    <div className="card" style={{ overflow: "hidden" }}>
      <div className="card-head">
        <div>
          <h3 style={{ whiteSpace: "nowrap" }}>{day.long}</h3>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{sorted.length} tee times · {claimed}/{capacity} spots claimed</div>
        </div>
        <Icon name="calendar" size={20} style={{ color: "var(--accent-deep)" }} />
      </div>

      <div className="stack" style={{ gap: 0 }}>
        {sorted.length === 0 && (
          <div className="muted" style={{ padding: "26px var(--card-pad)", fontSize: 14, textAlign: "center" }}>No tee times yet — add the first one below.</div>
        )}
        {sorted.map((s, idx) => {
          const editing = editingId === s.id;
          return (
            <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px var(--card-pad)", borderBottom: "1px solid var(--line)", flexWrap: "wrap" }}>
              {editing ? (
                <div style={{ display: "flex", alignItems: "center", gap: 8, flex: 1 }}>
                  <input type="time" className="input" value={editVal} onChange={e => setEditVal(e.target.value)} style={{ width: 150 }} />
                  <button className="btn btn-primary btn-sm" onClick={() => { if (editVal) { onEdit(s.id, inputToLabel(editVal)); } setEditingId(null); }}><Icon name="check" size={14} /> Save</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditingId(null)}>Cancel</button>
                </div>
              ) : (
                <>
                  <div className="serif" style={{ fontSize: 23, fontWeight: 700, minWidth: 96, whiteSpace: "nowrap" }}>{s.time}</div>
                  <div style={{ display: "flex", gap: 4, flex: 1, flexWrap: "wrap" }}>
                    {[0, 1, 2, 3].map(i => {
                      const p = s.players[i];
                      return (
                        <span key={i} title={p ? `${p.name} · HI ${p.hi} · GHIN ${p.ghin}` : "Open"} style={{
                          width: 30, height: 30, borderRadius: "50%", display: "grid", placeItems: "center", fontSize: 10.5, fontWeight: 700,
                          background: p ? "var(--brand-soft)" : "transparent", color: "var(--brand)",
                          border: p ? "none" : "1px dashed var(--line-strong)",
                        }}>{p ? p.initials : ""}</span>
                      );
                    })}
                  </div>
                  <span className="pill pill-green" style={{ whiteSpace: "nowrap" }}>{s.players.length}/4</span>
                  <div style={{ display: "flex", gap: 6 }}>
                    <button className="btn btn-ghost btn-sm" style={{ padding: "7px 10px" }} onClick={() => { setEditingId(s.id); setEditVal(labelToInput(s.time)); }} title="Edit time"><Icon name="edit" size={14} /></button>
                    <button className="btn btn-danger btn-sm" style={{ padding: "7px 10px" }} onClick={() => onRemove(s)} title="Remove time"><Icon name="trash" size={14} /></button>
                  </div>
                </>
              )}
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px var(--card-pad)", background: "var(--surface-2)", flexWrap: "wrap" }}>
        <span className="eyebrow" style={{ marginRight: 2 }}>Add tee time</span>
        <input type="time" className="input" value={newTime} onChange={e => setNewTime(e.target.value)} style={{ width: 150 }} />
        <button className="btn btn-primary btn-sm" disabled={!newTime} onClick={() => { onAdd(inputToLabel(newTime)); setNewTime(""); }}>
          <Icon name="plus" size={14} /> Add
        </button>
      </div>
    </div>
  );
}

function ManagerCard({ m, onDuty, isAdmin, onToggleAvail, onSave }) {
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState({ name: m.name, email: m.email, phone: m.phone });
  const blank = !m.name;

  function save() { onSave({ name: form.name.trim(), email: form.email.trim(), phone: form.phone.trim() }); setEditing(false); }

  const cardStyle = {
    display: "flex", flexDirection: "column", gap: 0, padding: 16, borderRadius: "var(--radius-sm)",
    border: "1px solid " + (onDuty ? "var(--accent)" : blank ? "var(--line-strong)" : "var(--line)"),
    background: onDuty ? "color-mix(in srgb,var(--accent) 8%,var(--surface))" : blank ? "var(--surface-2)" : "var(--surface)",
    opacity: m.available || blank ? 1 : .6,
  };

  if (blank && !editing) {
    return (
      <div style={cardStyle}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 42, height: 42, borderRadius: "50%", border: "1.5px dashed var(--line-strong)", display: "grid", placeItems: "center", color: "var(--ink-faint)" }}><Icon name="user" size={18} /></span>
          <div>
            <div style={{ fontSize: 14.5, fontWeight: 700 }}>{m.role} manager</div>
            <div className="faint" style={{ fontSize: 12 }}>Not assigned yet</div>
          </div>
        </div>
        {isAdmin ? (
          <button className="btn btn-primary btn-sm" style={{ marginTop: 14, alignSelf: "flex-start" }} onClick={() => setEditing(true)}><Icon name="plus" size={13} /> Add {m.role.toLowerCase()} manager</button>
        ) : (
          <div className="faint" style={{ fontSize: 11.5, marginTop: 12 }}>The administrator assigns this role.</div>
        )}
      </div>
    );
  }

  if (editing) {
    return (
      <div style={cardStyle}>
        <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>{blank ? `Add ${m.role.toLowerCase()} manager` : "Edit manager"}</div>
        <div className="field" style={{ marginBottom: 9 }}><label>Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Full name" /></div>
        <div className="field" style={{ marginBottom: 9 }}><label>Email</label><input className="input" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="name@email.com" /></div>
        <div className="field" style={{ marginBottom: 12 }}><label>Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: window.YCC.formatPhone(e.target.value) })} placeholder="(215) 555-0100" inputMode="tel" /></div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-primary btn-sm" disabled={!form.name.trim() || !form.email.trim()} onClick={save}><Icon name="check" size={13} /> Save</button>
          <button className="btn btn-ghost btn-sm" onClick={() => { setForm({ name: m.name, email: m.email, phone: m.phone }); setEditing(false); }}>Cancel</button>
        </div>
      </div>
    );
  }

  return (
    <div style={cardStyle}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 13 }}>
        <Avatar initials={m.initials} size={42} tone={onDuty ? "accent" : "brand"} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 700, whiteSpace: "nowrap" }}>{m.name}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap", marginTop: 5 }}>
            <span className="pill" style={{ background: "var(--surface-2)", color: "var(--ink-soft)" }}>{m.role}</span>
            {m.admin && <span className="pill" style={{ background: "color-mix(in srgb,var(--accent) 20%,transparent)", color: "var(--accent-deep)" }}>Admin</span>}
            {onDuty && <span className="pill pill-accent" style={{ whiteSpace: "nowrap" }}><Icon name="check" size={11} /> On duty</span>}
          </div>
          <div className="faint" style={{ fontSize: 12, marginTop: 6 }}>{m.title}</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 8, display: "flex", flexDirection: "column", gap: 3 }}>
            <span style={{ display: "flex", alignItems: "center", gap: 7, whiteSpace: "nowrap" }}><Icon name="mail" size={13} /> {m.email}</span>
            {m.phone && <span style={{ display: "flex", alignItems: "center", gap: 7, whiteSpace: "nowrap" }}><Icon name="user" size={13} /> {m.phone}</span>}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <button className="btn btn-sm" style={{ background: m.available ? "var(--brand-soft)" : "var(--accent)", color: m.available ? "var(--brand)" : "#1b1404" }} onClick={onToggleAvail}>
          <Icon name={m.available ? "check" : "clock"} size={13} /> {m.available ? "Available" : "Away"}
        </button>
        {isAdmin && <button className="btn btn-ghost btn-sm" onClick={() => setEditing(true)}><Icon name="edit" size={13} /> Edit</button>}
      </div>
    </div>
  );
}

function ManagerScreen({ ctx }) {
  const Y = window.YCC;
  const { tour, dayKeys, addTime, editTime, requestRemoveTime, togglePublish, activeManager, toggleManagerAvail, isAdmin, setManagerInfo, gameConfig, setGameConfig, phase, entry } = ctx;
  const G = window.YCC_GAMES;
  const { TeeSelect, Seg } = window;
  const FinalTeeSheetPanel = window.FinalTeeSheetPanel;
  const PostWeekendCard = window.PostWeekendCard;
  const setCfg = (patch) => setGameConfig({ ...gameConfig, ...patch });
  const STAKE_LABEL = { skins: "Skin value", stableford: "Ante (each)", nassau: "Bet / match", "split-sixes": "Point value" };
  const idsInPlay = Array.from(new Set(gameConfig.splitDays ? [gameConfig.gameSat || "skins", gameConfig.gameSun || "skins"] : [gameConfig.gameType || "skins"]));
  const anySkins = idsInPlay.includes("skins");
  const stakeLabel = idsInPlay.length === 1 ? (STAKE_LABEL[idsInPlay[0]] || "Stake") : "Stake";
  const fmtET = (d) => d.toLocaleString("en-US", { weekday: "long", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
  const phaseCopy = {
    open: { c: "var(--ok)", t: "Open to members", d: `Members can self-serve until Wed 11:59 PM ET (${fmtET(entry.wed)}).` },
    managerOnly: { c: "var(--accent-deep)", t: "Manager-managed", d: `Member sign-ups closed. You can add / move / release until Fri 9:00 AM ET (${fmtET(entry.fri)}).` },
    locked: { c: "var(--ink-faint)", t: "Members final · manager game-day control", d: "Member sign-ups are closed. You can still adjust groups and swap players between foursomes on game day." },
  }[phase];
  const activeGame = G.gameById(gameConfig.gameType || "skins");
  const days = [
    { iso: tour.satISO, long: Y.fmtDate(Y.SAT) },
    { iso: tour.sunISO, long: Y.fmtDate(Y.SUN) },
  ];
  const allSlots = [...(tour.slots[tour.satISO] || []), ...(tour.slots[tour.sunISO] || [])];
  const totalTimes = allSlots.length;
  const totalClaimed = allSlots.reduce((n, s) => n + s.players.length, 0);
  const totalOpen = totalTimes * 4 - totalClaimed;

  return (
    <div className="page fade-in">
      <div className="page-head" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
        <div>
          <div className="eyebrow">Manager · DIV Tour</div>
          <h1 style={{ marginTop: 6 }}>Tour setup</h1>
          <p>Publish the tee times for the weekend of {tour.weekendLabel}. Members claim open spots and their handicaps attach automatically.</p>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: tour.published ? "var(--ok)" : "var(--ink-faint)" }}>
            {tour.published ? "Live to members" : "Draft — hidden"}
          </span>
          <button onClick={togglePublish} role="switch" aria-checked={tour.published} style={{
            width: 50, height: 28, borderRadius: 999, padding: 3, transition: "background .18s",
            background: tour.published ? "var(--brand)" : "var(--line-strong)", display: "flex",
            justifyContent: tour.published ? "flex-end" : "flex-start", flex: "0 0 auto",
          }}>
            <span style={{ width: 22, height: 22, borderRadius: "50%", background: "#fff", boxShadow: "0 1px 3px rgba(0,0,0,.25)" }}></span>
          </button>
        </div>
      </div>

      {/* sign-up window status */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", borderRadius: "var(--radius)", background: "var(--surface)", border: "1px solid var(--line)", marginBottom: 18 }}>
        <span style={{ width: 10, height: 10, borderRadius: "50%", background: phaseCopy.c, boxShadow: `0 0 0 3px color-mix(in srgb, ${phaseCopy.c} 22%, transparent)`, flex: "0 0 auto" }}></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700 }}>Sign-up window · {phaseCopy.t}</div>
          <div className="muted" style={{ fontSize: 12.5 }}>{phaseCopy.d}</div>
        </div>
        <div className="faint" style={{ fontSize: 11, textAlign: "right", lineHeight: 1.5, whiteSpace: "nowrap" }}>
          <div>Members close · {fmtET(entry.wed)}</div>
          <div>Final lock · {fmtET(entry.fri)}</div>
        </div>
      </div>

      {/* stats */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px,1fr))", marginBottom: 22 }}>
        <StatTile value={totalTimes} label="Tee times published" sub="Saturday + Sunday" />
        <StatTile value={totalClaimed} label="Spots claimed" sub={`across ${totalTimes} groups`} accent />
        <StatTile value={totalOpen} label="Spots still open" />
        <StatTile value={Math.round((totalClaimed / Math.max(1, totalTimes * 4)) * 100) + "%"} label="Field filled" />
      </div>

      {/* final tee sheet → pro shop */}
      {FinalTeeSheetPanel && <FinalTeeSheetPanel ctx={ctx} />}

      {/* certify & post weekend results to member season stats */}
      {PostWeekendCard && <PostWeekendCard ctx={ctx} />}

      {/* tour managers */}
      <div className="card" style={{ marginBottom: 22 }}>
        <div className="card-head">
          <div>
            <h3>Tour managers</h3>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>A backup covers sign-ups whenever the primary is away.</div>
          </div>
          <Icon name="users" size={20} style={{ color: "var(--accent-deep)" }} />
        </div>
        <div className="card-pad" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px,1fr))", gap: "var(--gap)" }}>
          {tour.managers.map((m, i) => (
            <ManagerCard key={i} m={m} onDuty={m === activeManager && m.available} isAdmin={isAdmin}
              onToggleAvail={() => toggleManagerAvail(i)} onSave={(patch) => setManagerInfo(i, patch)} />
          ))}
        </div>
        {!tour.managers.some(m => m.available) && (
          <div style={{ padding: "12px var(--card-pad)", borderTop: "1px solid var(--line)", color: "var(--danger)", fontSize: 12.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 8 }}>
            <Icon name="info" size={15} /> No manager is currently on duty — members will see {activeManager.name} as the default contact.
          </div>
        )}
      </div>

      {/* weekend game format */}
      <div className="card" style={{ marginBottom: 22 }}>
        <div className="card-head">
          <div>
            <h3>Weekend Games</h3>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Choose this weekend's format. Members see the rules on their Weekend Games tab.</div>
          </div>
          <Icon name="trophy" size={20} style={{ color: "var(--accent-deep)" }} />
        </div>
        <div className="card-pad">
          {/* scoring controls — these drive every group scorecard (moved here from Weekend Games) */}
          <div style={{ display: "flex", alignItems: "center", gap: 24, flexWrap: "wrap", padding: "14px 16px", borderRadius: "var(--radius-sm)", border: "1px solid var(--line)", background: "var(--surface-2)", marginBottom: 18 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span className="eyebrow">{stakeLabel}</span>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <button className="btn btn-ghost btn-sm" style={{ padding: "6px 11px", background: "var(--surface)" }} onClick={() => setCfg({ skinValue: Math.max(1, (gameConfig.skinValue || 1) - 1) })} aria-label="Decrease"><Icon name="minus" size={12} /></button>
                <span className="serif" style={{ fontSize: 24, fontWeight: 700, color: "var(--brand)", minWidth: 52, textAlign: "center" }}>${gameConfig.skinValue || 0}</span>
                <button className="btn btn-ghost btn-sm" style={{ padding: "6px 11px", background: "var(--surface)" }} onClick={() => setCfg({ skinValue: Math.min(100, (gameConfig.skinValue || 0) + 1) })} aria-label="Increase"><Icon name="plus" size={12} /></button>
              </div>
            </div>
            {anySkins && Seg && <Seg label="Scoring" value={gameConfig.scoring || "gross"} onChange={(v) => setCfg({ scoring: v })} options={[["gross", "Gross"], ["net", "Net"]]} />}
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span className="eyebrow">Group tees</span>
              {TeeSelect && <TeeSelect value={gameConfig.groupTee || "Blue"} onChange={(v) => setCfg({ groupTee: v })} />}
              <span className="faint" style={{ fontSize: 11.5 }}>drives every card</span>
            </div>
            {anySkins && (
              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <span className="eyebrow">Carryover</span>
                <button onClick={() => setCfg({ carryover: !gameConfig.carryover })} role="switch" aria-checked={!!gameConfig.carryover} style={{
                  width: 46, height: 26, borderRadius: 999, padding: 3, transition: "background .18s",
                  background: gameConfig.carryover ? "var(--brand)" : "var(--line-strong)", display: "flex", justifyContent: gameConfig.carryover ? "flex-end" : "flex-start",
                }}>
                  <span style={{ width: 20, height: 20, borderRadius: "50%", background: "#fff", boxShadow: "0 1px 3px rgba(0,0,0,.25)" }}></span>
                </button>
              </div>
            )}
          </div>
          {/* same game both days, or a different game each day */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
            <span className="eyebrow">Schedule</span>
            <div style={{ display: "inline-flex", background: "var(--surface-2)", borderRadius: 9, padding: 3, border: "1px solid var(--line)" }}>
              {[[false, "Same game both days"], [true, "Different each day"]].map(([val, lab]) => (
                <button key={String(val)} onClick={() => setGameConfig({ ...gameConfig, splitDays: val })} style={{
                  padding: "6px 13px", borderRadius: 7, fontSize: 12.5, fontWeight: 600, transition: "all .15s",
                  background: !!gameConfig.splitDays === val ? "var(--surface)" : "transparent",
                  color: !!gameConfig.splitDays === val ? "var(--brand)" : "var(--ink-soft)",
                  boxShadow: !!gameConfig.splitDays === val ? "var(--shadow-sm)" : "none",
                }}>{lab}</button>
              ))}
            </div>
          </div>

          {!gameConfig.splitDays ? (
            <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", marginBottom: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="eyebrow">This weekend's game</span>
                <span style={{ display: "inline-flex", alignItems: "center", padding: "3px 4px 3px 12px", borderRadius: 9, border: "1px solid var(--line-strong)", background: "var(--surface)" }}>
                  <select value={gameConfig.gameType || "skins"} onChange={(e) => setGameConfig({ ...gameConfig, gameType: e.target.value })} style={{ border: "none", background: "transparent", fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 700, color: "var(--ink)", padding: "6px 6px", cursor: "pointer" }}>
                    {G.GAME_LIBRARY.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
                  </select>
                </span>
              </div>
              <span className="pill pill-accent" style={{ whiteSpace: "nowrap" }}><Icon name="check" size={12} /> {G.gameById(gameConfig.gameType || "skins").name} · Sat &amp; Sun</span>
            </div>
          ) : (
            <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: "var(--gap)", marginBottom: 18 }}>
              {[["gameSat", "Saturday", Y.shortDate(Y.SAT)], ["gameSun", "Sunday", Y.shortDate(Y.SUN)]].map(([key, label, sub]) => (
                <div key={key} style={{ padding: "13px 15px", borderRadius: "var(--radius-sm)", border: "1px solid var(--line)", background: "var(--surface-2)" }}>
                  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, marginBottom: 9 }}>
                    <span style={{ fontWeight: 700, fontSize: 14 }}>{label}</span>
                    <span className="faint" style={{ fontSize: 11.5 }}>{sub}</span>
                  </div>
                  <span style={{ display: "inline-flex", alignItems: "center", padding: "3px 4px 3px 12px", borderRadius: 9, border: "1px solid var(--line-strong)", background: "var(--surface)", width: "100%" }}>
                    <select value={gameConfig[key] || "skins"} onChange={(e) => setGameConfig({ ...gameConfig, [key]: e.target.value })} style={{ border: "none", background: "transparent", fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 700, color: "var(--ink)", padding: "6px 6px", cursor: "pointer", width: "100%" }}>
                      {G.GAME_LIBRARY.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
                    </select>
                  </span>
                </div>
              ))}
            </div>
          )}
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 16, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
            <span className="eyebrow">Handicap strokes off</span>
            <div style={{ display: "inline-flex", background: "var(--surface-2)", borderRadius: 9, padding: 3, border: "1px solid var(--line)" }}>
              {[["day", "The day's low (all groups)"], ["group", "Each group's low"]].map(([val, lab]) => {
                const on = (gameConfig.lowMode || "day") === val;
                return (
                  <button key={val} onClick={() => setGameConfig({ ...gameConfig, lowMode: val })} style={{
                    padding: "6px 13px", borderRadius: 7, fontSize: 12.5, fontWeight: 600, transition: "all .15s",
                    background: on ? "var(--surface)" : "transparent", color: on ? "var(--brand)" : "var(--ink-soft)",
                    boxShadow: on ? "var(--shadow-sm)" : "none",
                  }}>{lab}</button>
                );
              })}
            </div>
            <span className="faint" style={{ fontSize: 11.5 }}>Default: every player gets strokes vs the lowest handicap playing that day.</span>
          </div>

          {/* daily add-on games — side contests layered on the main game, set per day */}
          {(() => {
            const sideCfg = gameConfig.sideGames || G.defaultSideGames();
            const par3s = G.parThreeHoles();
            const dayCfg = (k) => sideCfg[k] || {};
            const patchDay = (k, patch) => setGameConfig({ ...gameConfig, sideGames: { ...sideCfg, [k]: { ...(sideCfg[k] || {}), ...patch } } });
            const toggleSide = (k, id) => patchDay(k, { [id]: !(sideCfg[k] && sideCfg[k][id]) });
            const ctpHolesOf = (k) => Array.isArray(dayCfg(k).ctpHoles) ? dayCfg(k).ctpHoles : par3s.slice();
            const toggleCtpHole = (k, n) => {
              const cur = ctpHolesOf(k);
              const next = cur.includes(n) ? cur.filter((x) => x !== n) : [...cur, n].sort((a, b) => a - b);
              patchDay(k, { ctpHoles: next });
            };
            const setAllCtp = (k, all) => patchDay(k, { ctpHoles: all ? par3s.slice() : [] });
            const ldHoleOf = (k) => dayCfg(k).longDriveHole || sideCfg.longDriveHole || 7;
            const yardsOf = (n) => { const h = Y.HOLES.find((x) => x.n === n); return h ? h.yards : ""; };
            return (
              <div style={{ paddingTop: 16, borderTop: "1px solid var(--line)", marginBottom: 16 }}>
                <span className="eyebrow">Daily add-on games</span>
                <div className="muted" style={{ fontSize: 12.5, margin: "6px 0 14px", maxWidth: "62ch" }}>Layer extra contests on top of the main game — pick them, and their holes, for each day. Each group marks the winners on their scorecard during play.</div>
                <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: "var(--gap)" }}>
                  {[["sat", "Saturday", Y.shortDate(Y.SAT)], ["sun", "Sunday", Y.shortDate(Y.SUN)]].map(([key, label, sub]) => {
                    const ctpOn = !!dayCfg(key).ctp;
                    const ldOn = !!dayCfg(key).longDrive;
                    const ctpHoles = ctpHolesOf(key);
                    return (
                      <div key={key} style={{ padding: "14px 15px", borderRadius: "var(--radius-sm)", border: "1px solid var(--line)", background: "var(--surface-2)" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
                          <span style={{ fontWeight: 700, fontSize: 14 }}>{label}</span>
                          <span className="faint" style={{ fontSize: 11.5 }}>{sub}</span>
                        </div>
                        <div className="stack" style={{ gap: 9 }}>
                          {/* Closest to the Pin */}
                          <div>
                            <SideToggle on={ctpOn} icon="pin" name="Closest to the Pin"
                              meta={ctpOn ? (ctpHoles.length ? `${ctpHoles.length} of ${par3s.length} par 3s · ${ctpHoles.map((n) => "#" + n).join(" ")}` : "No holes selected") : `Par 3s · ${par3s.map((n) => "#" + n).join(" ")}`}
                              onClick={() => toggleSide(key, "ctp")} />
                            {ctpOn && (
                              <div style={{ marginTop: 8, padding: "11px 12px", borderRadius: 9, background: "var(--surface)", border: "1px solid var(--line)" }}>
                                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 9 }}>
                                  <span className="eyebrow" style={{ fontSize: 10.5 }}>Holes in play</span>
                                  <span style={{ display: "flex", gap: 6 }}>
                                    <button onClick={() => setAllCtp(key, true)} style={{ fontSize: 11, fontWeight: 700, color: "var(--accent-deep)" }}>All</button>
                                    <span className="faint" style={{ fontSize: 11 }}>·</span>
                                    <button onClick={() => setAllCtp(key, false)} style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-faint)" }}>None</button>
                                  </span>
                                </div>
                                <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
                                  {par3s.map((n) => {
                                    const sel = ctpHoles.includes(n);
                                    return (
                                      <button key={n} onClick={() => toggleCtpHole(key, n)} style={{
                                        display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 11px", borderRadius: 999,
                                        border: "1.5px solid " + (sel ? "var(--accent)" : "var(--line-strong)"),
                                        background: sel ? "color-mix(in srgb,var(--accent) 14%,var(--surface))" : "var(--surface)",
                                        color: sel ? "var(--accent-deep)" : "var(--ink-soft)", transition: "all .12s",
                                      }}>
                                        {sel && <Icon name="check" size={12} />}
                                        <span style={{ fontSize: 12, fontWeight: 700 }}>Hole {n}</span>
                                        <span className="faint" style={{ fontSize: 10.5 }}>{yardsOf(n)}y</span>
                                      </button>
                                    );
                                  })}
                                </div>
                              </div>
                            )}
                          </div>
                          {/* Longest Drive */}
                          <div>
                            <SideToggle on={ldOn} icon="flag" name="Longest Drive"
                              meta={ldOn ? `Hole #${ldHoleOf(key)}` : "One designated hole"}
                              onClick={() => toggleSide(key, "longDrive")} />
                            {ldOn && (
                              <div style={{ marginTop: 8, padding: "11px 12px", borderRadius: 9, background: "var(--surface)", border: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                                <span className="eyebrow" style={{ fontSize: 10.5 }}>Hole</span>
                                <span style={{ display: "inline-flex", alignItems: "center", padding: "2px 4px 2px 10px", borderRadius: 8, border: "1px solid var(--line-strong)", background: "var(--surface)" }}>
                                  <select key={"ld-" + key + "-" + ldHoleOf(key)} defaultValue={String(ldHoleOf(key))} onChange={(e) => patchDay(key, { longDriveHole: Number(e.target.value) })} style={{ border: "none", background: "transparent", fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 700, color: "var(--ink)", padding: "5px 4px", cursor: "pointer" }}>
                                    {Y.HOLES.filter((h) => h.par >= 4).map((h) => <option key={h.n} value={String(h.n)}>Hole {h.n} · Par {h.par} · {h.yards} yds</option>)}
                                  </select>
                                </span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })()}

          <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginBottom: 12, display: "flex", alignItems: "center", gap: 7 }}>
            <Icon name="info" size={14} /> Tap any game below to read its rules &amp; scoring. The group scorecard uses the selected game's scoring &amp; winnings.
          </div>
          <G.GameRulesGrid activeId={gameConfig.splitDays ? (gameConfig.gameSat || "skins") : (gameConfig.gameType || "skins")} />
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", alignItems: "start", gap: "var(--gap)" }}>
        {days.map(d => (
          <ManagerDay
            key={d.iso} day={d} slots={tour.slots[d.iso] || []}
            onAdd={(label) => addTime(d.iso, label)}
            onEdit={(slotId, label) => editTime(d.iso, slotId, label)}
            onRemove={(slot) => requestRemoveTime(d.iso, slot)}
          />
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ManagerScreen, ManagerDay });
