/* ============================================================
   Final (locked) Tee Sheet — Friday 9:00 AM ET lock.
   A clean, screenshot-ready sheet per day for the pro shop:
   every DIV Tour tee time, with empty times stamped OK TO RELEASE.
   Includes per-day PNG download + an email composer to the
   Golf Shop and Head Pro.
   ============================================================ */

/* -------- the printable / screenshot-ready sheet for ONE day -------- */
function LockedTeeSheet({ slots, dayLabel, dateLabel, lockLabel, weekendLabel }) {
  const Y = window.YCC;
  const sorted = Y.sortByTime(slots || []);
  const filledTimes = sorted.filter((s) => (s.players || []).length > 0).length;
  const openTimes = sorted.filter((s) => (s.players || []).length === 0).length;
  const golfers = sorted.reduce((n, s) => n + (s.players || []).length, 0);

  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 14, overflow: "hidden", width: "100%", boxShadow: "var(--shadow-sm)" }}>
      {/* header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "18px 22px", background: "var(--brand-deep)", color: "var(--on-brand)", flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 13 }}>
          <div style={{ width: 42, height: 42, borderRadius: "50%", border: "1.5px solid var(--accent)", display: "grid", placeItems: "center", color: "var(--accent)", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14, flex: "0 0 auto" }}>YCC</div>
          <div>
            <div className="serif" style={{ fontSize: 20, fontWeight: 700, lineHeight: 1.05 }}>Yardley Country Club</div>
            <div style={{ fontSize: 10.5, letterSpacing: ".16em", textTransform: "uppercase", color: "rgba(244,241,230,.66)", marginTop: 3, fontWeight: 600 }}>DIV Tour · Final Tee Sheet</div>
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="serif" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1 }}>{dayLabel}</div>
          <div style={{ fontSize: 12, color: "rgba(244,241,230,.78)", marginTop: 3 }}>{dateLabel}</div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 8, padding: "4px 10px", borderRadius: 999, background: "color-mix(in srgb, var(--accent) 24%, transparent)", color: "var(--accent)", fontSize: 10.5, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase" }}>
            <Icon name="shield" size={11} /> Locked {lockLabel ? "· " + lockLabel : "· Fri 9:00 AM ET"}
          </div>
        </div>
      </div>

      {/* tee times */}
      <div>
        {sorted.length === 0 && (
          <div className="muted" style={{ padding: "28px 22px", fontSize: 14, textAlign: "center" }}>No DIV Tour group tee times this day.</div>
        )}
        {sorted.map((s) => {
          const players = s.players || [];
          const empty = players.length === 0;
          return (
            <div key={s.id} style={{ position: "relative", display: "flex", gap: 16, alignItems: "stretch", padding: "13px 22px", borderTop: "1px solid var(--line)", background: empty ? "color-mix(in srgb, var(--accent) 6%, var(--surface))" : "var(--surface)" }}>
              <div style={{ flex: "0 0 96px", display: "flex", flexDirection: "column", justifyContent: "center" }}>
                <div className="serif" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1, whiteSpace: "nowrap", color: empty ? "var(--ink-faint)" : "var(--ink)" }}>{s.time}</div>
                <div className="faint" style={{ fontSize: 10.5, marginTop: 4 }}>{empty ? "0 of 4" : players.length + " of 4"}</div>
              </div>
              <div style={{ flex: 1, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8, minWidth: 0, opacity: empty ? 0.32 : 1 }}>
                {[0, 1, 2, 3].map((i) => {
                  const p = players[i];
                  if (!p) {
                    return <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 8, border: "1px dashed var(--line-strong)", color: "var(--ink-faint)", fontSize: 11, fontWeight: 600, minHeight: 40 }}>Open</div>;
                  }
                  return (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 11px", borderRadius: 8, background: "var(--surface-2)", minWidth: 0, minHeight: 40 }}>
                      <div style={{ width: 26, height: 26, borderRadius: "50%", flex: "0 0 auto", background: "var(--brand-soft)", color: "var(--brand)", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 10 }}>{p.initials}</div>
                      <span style={{ flex: 1, minWidth: 0, fontSize: 12.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}{p.guest ? " *" : ""}</span>
                      <span className="faint" style={{ flex: "0 0 auto", fontSize: 10.5, fontFamily: "ui-monospace, monospace", whiteSpace: "nowrap" }}>HI {p.hi ?? "—"}</span>
                    </div>
                  );
                })}
              </div>
              {empty && (
                <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", pointerEvents: "none" }}>
                  <span style={{ transform: "rotate(-6deg)", border: "2.5px dashed var(--accent-deep)", color: "var(--accent-deep)", fontWeight: 800, letterSpacing: ".14em", fontSize: 16, padding: "5px 16px", borderRadius: 7, textTransform: "uppercase", background: "color-mix(in srgb, var(--accent) 12%, var(--surface))", boxShadow: "0 1px 0 rgba(0,0,0,.04)" }}>OK to release</span>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* footer */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, padding: "11px 22px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 18, fontSize: 11.5, color: "var(--ink-soft)", flexWrap: "wrap" }}>
          <span><strong style={{ color: "var(--ink)" }}>{sorted.length}</strong> tee times</span>
          <span><strong style={{ color: "var(--ink)" }}>{golfers}</strong> golfers</span>
          {openTimes > 0 && <span style={{ color: "var(--accent-deep)", fontWeight: 700 }}>{openTimes} OK to release</span>}
        </div>
        <div className="faint" style={{ fontSize: 10.5 }}>{weekendLabel ? "Weekend of " + weekendLabel : ""} · * = guest</div>
      </div>
    </div>
  );
}

/* -------- plain-text body for the pro-shop email -------- */
function proShopEmailBody(Y, days, weekendLabel) {
  const lines = [];
  lines.push("Golf Shop and Head Pro,");
  lines.push("");
  lines.push("Below is our group for the weekend:");
  days.forEach((d) => {
    lines.push("");
    lines.push("==================================================");
    lines.push(`${d.dayLabel.toUpperCase()} · ${d.dateLabel}`);
    lines.push("DIV Tour — FINAL tee sheet (locked Fri 9:00 AM ET)");
    lines.push("==================================================");
    const sorted = Y.sortByTime(d.slots || []);
    if (!sorted.length) { lines.push("  (no DIV Tour group tee times this day)"); return; }
    sorted.forEach((s) => {
      const players = s.players || [];
      if (!players.length) { lines.push(`${s.time}  —  *** OK TO RELEASE (no members) ***`); return; }
      lines.push(`${s.time}`);
      players.forEach((p, i) => lines.push(`    ${i + 1}. ${p.name}${p.guest ? " (guest)" : ""} — HI ${p.hi ?? "—"}${p.ghin ? " · GHIN " + p.ghin : ""}`));
    });
  });
  lines.push("");
  lines.push("Please release any tee time marked OK TO RELEASE back to the membership.");
  lines.push("");
  lines.push("Thank you,");
  lines.push("DIV Tour");
  return lines.join("\n");
}

/* -------- download one day's sheet as a PNG (screenshot) -------- */
function downloadSheetPng(nodeId, filename, toast) {
  const node = document.getElementById(nodeId);
  if (!node) { if (toast) toast("Tee sheet not ready yet."); return; }
  const lib = window.htmlToImage;
  if (!lib || !lib.toPng) {
    if (toast) toast("Image export unavailable — use your browser screenshot.");
    return;
  }
  if (toast) toast("Building image…");
  lib.toPng(node, { pixelRatio: 2, backgroundColor: "#ffffff", cacheBust: true })
    .then((dataUrl) => {
      const a = document.createElement("a");
      a.download = filename; a.href = dataUrl;
      document.body.appendChild(a); a.click(); a.remove();
      if (toast) toast("Saved " + filename);
    })
    .catch(() => { if (toast) toast("Couldn't build the image — use your browser screenshot."); });
}

/* -------- manager panel: previews + PNG + email actions -------- */
function FinalTeeSheetPanel({ ctx }) {
  const Y = window.YCC;
  const { tour, phase, entry, toast } = ctx;
  const contacts = Y.CLUB_CONTACTS || [];
  const proShopEmails = contacts.map((c) => c.email);
  const fmtET = (d) => d ? d.toLocaleString("en-US", { weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "";
  const lockLabel = entry && entry.fri ? "Fri 9:00 AM ET" : "Fri 9:00 AM ET";

  const days = [
    { key: "sat", dayLabel: "Saturday", iso: tour.satISO },
    { key: "sun", dayLabel: "Sunday", iso: tour.sunISO },
  ].map((d) => ({ ...d, slots: tour.slots[d.iso] || [], dateLabel: Y.fmtDate(new Date(d.iso + "T00:00:00")) }));

  const subject = `DIV Tour — Final Tee Sheet · ${tour.weekendLabel}`;
  const body = proShopEmailBody(Y, days, tour.weekendLabel);

  // Which mail client the action buttons hand off to. Persisted per device.
  const [mailVia, setMailVia] = React.useState(() => {
    try { return localStorage.getItem("ycc_mail_via") || "default"; } catch (e) { return "default"; }
  });
  function chooseMailVia(k) {
    setMailVia(k);
    try { localStorage.setItem("ycc_mail_via", k); } catch (e) {}
  }

  function emailTo(list, who) {
    if (!list.length) { toast && toast("No recipient configured."); return; }
    const to = list.join(",");
    let url, newTab = false;
    if (mailVia === "gmail") {
      url = `https://mail.google.com/mail/?view=cm&fs=1&to=${encodeURIComponent(to)}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      newTab = true;
    } else if (mailVia === "outlook") {
      url = `https://outlook.office.com/mail/deeplink/compose?to=${encodeURIComponent(to)}&subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      newTab = true;
    } else {
      url = `mailto:${encodeURIComponent(to)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    }
    try {
      if (newTab) window.open(url, "_blank", "noopener");
      else window.location.href = url;
    } catch (e) {}
    const dest = mailVia === "gmail" ? "Gmail" : mailVia === "outlook" ? "Outlook on the web" : "your default mail app";
    toast && toast("Opening " + dest + " for " + who + "…");
  }

  const locked = phase === "locked";

  return (
    <div className="card" style={{ marginBottom: 22, overflow: "hidden", border: locked ? "1px solid var(--accent)" : "1px solid var(--line)" }}>
      <div className="card-head" style={{ background: locked ? "color-mix(in srgb, var(--accent) 9%, var(--surface))" : "var(--surface)" }}>
        <div>
          <h3>Final tee sheet · Pro shop</h3>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>
            {locked
              ? <>Tee sheets are <strong style={{ color: "var(--accent-deep)" }}>locked</strong> — send the final groups to the Golf Shop &amp; Head Pro.</>
              : <>At the Friday 9:00 AM ET lock, send the final groups to the Golf Shop &amp; Head Pro. Empty times are stamped <strong>OK to release</strong>.</>}
          </div>
        </div>
        <Icon name="mail" size={20} style={{ color: "var(--accent-deep)" }} />
      </div>

      <div className="card-pad">
        {/* mail-client preference */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
          <span style={{ fontSize: 12, color: "var(--ink-soft)", fontWeight: 600 }}>Open emails in:</span>
          <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 8, overflow: "hidden" }}>
            {[["default", "Default mail app"], ["gmail", "Gmail"], ["outlook", "Outlook web"]].map(([k, lbl], i) => (
              <button
                key={k}
                onClick={() => chooseMailVia(k)}
                style={{
                  border: "none",
                  borderLeft: i === 0 ? "none" : "1px solid var(--line)",
                  padding: "6px 12px",
                  fontSize: 12,
                  fontWeight: 600,
                  cursor: "pointer",
                  background: mailVia === k ? "#142519" : "transparent",
                  color: mailVia === k ? "#f4f1e6" : "var(--ink-soft)",
                }}
              >
                {lbl}
              </button>
            ))}
          </div>
        </div>
        {/* actions */}
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 18 }}>
          <button className="btn btn-primary btn-sm" onClick={() => emailTo(proShopEmails, "the pro shop")}>
            <Icon name="mail" size={14} /> Email Pro Shop &amp; Head Pro
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => emailTo(["grahamat6@gmail.com"], "your proof copy")}>
            <Icon name="mail" size={14} /> Email me a proof
          </button>
          <span style={{ width: 1, background: "var(--line)", margin: "0 2px" }}></span>
          <button className="btn btn-quiet btn-sm" onClick={() => downloadSheetPng("locked-sheet-sat", `DIV-Tour-Saturday-${tour.satISO}.png`, toast)}>
            <Icon name="logout" size={13} style={{ transform: "rotate(90deg)" }} /> Saturday image
          </button>
          <button className="btn btn-quiet btn-sm" onClick={() => downloadSheetPng("locked-sheet-sun", `DIV-Tour-Sunday-${tour.sunISO}.png`, toast)}>
            <Icon name="logout" size={13} style={{ transform: "rotate(90deg)" }} /> Sunday image
          </button>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 16, fontSize: 12, color: "var(--ink-soft)" }}>
          <Icon name="info" size={14} style={{ color: "var(--accent-deep)", flex: "0 0 auto" }} />
          <span>The email opens pre-addressed to {contacts.map((c) => c.name).join(" & ") || "the pro shop"} with the greeting and both days' groups. Attach the day images above so they have a screenshot of each sheet.</span>
        </div>

        {/* live previews (also the capture targets for the PNG download) */}
        <div className="stack" style={{ gap: 18 }}>
          {days.map((d) => (
            <div key={d.key} id={"locked-sheet-" + d.key}>
              <LockedTeeSheet slots={d.slots} dayLabel={d.dayLabel} dateLabel={d.dateLabel} lockLabel={lockLabel} weekendLabel={tour.weekendLabel} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LockedTeeSheet, FinalTeeSheetPanel, proShopEmailBody, downloadSheetPng });
