// Meetup screens for Rbac46

const safeTopM = (extra = 16) => `calc(var(--safe-t) + ${extra}px)`;
const Dm = () => window.RBAC_DATA;
const personM = (id) => {
  if (!id || id === "me") return RBAC_ME();
  return Dm().alumni.find(a => a.id === id) || RBAC_ME();
};

const VIBE = {
  casual: { label: "เป็นกันเอง", icon: "chat" },
  formal: { label: "งาน Workshop", icon: "spark" },
  outing: { label: "ทริปต่างจังหวัด", icon: "map" },
};

function fmtDate(iso) {
  const [y, m, d] = iso.split("-").map(Number);
  const months = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
  return `${d} ${months[m - 1]} ${y}`;
}
function shortDate(iso) {
  const [, m, d] = iso.split("-").map(Number);
  const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
  return { d, m: months[m - 1] };
}

// ────────────────────────────────────────────────────────────
// 1) MeetupsScreen
// ────────────────────────────────────────────────────────────
function MeetupsScreen({ go, sepia }) {
  const d = Dm();
  const myId = RBAC_ME().id;
  const [filter, setFilter] = React.useState("all");
  // Map of meetupId -> status for the current user (from API)
  const [myRsvps, setMyRsvps] = React.useState({});

  React.useEffect(() => {
    RBAC_API.getUserRsvps(myId).then(data => {
      if (data && Array.isArray(data)) {
        const map = {};
        data.forEach(({ meetup_id, status }) => { map[meetup_id] = status; });
        setMyRsvps(map);
      }
    }).catch(() => {});
  }, [myId]);

  const iAmGoing = (m) => {
    // API data takes precedence over static data
    if (myId in myRsvps ? true : false) {
      const s = myRsvps[m.id];
      return s === "going" || s === "maybe";
    }
    return m.going.includes(myId) || m.going.includes("me") ||
           m.maybe.includes(myId) || m.maybe.includes("me");
  };

  const filtered = d.meetups.filter(m => {
    if (filter === "going") return iAmGoing(m);
    if (filter === "bkk")   return m.district === "กรุงเทพมหานคร";
    if (filter === "upcountry") return m.district !== "กรุงเทพมหานคร";
    return true;
  }).sort((a, b) => a.date.localeCompare(b.date));

  return (
    <div style={{ flex: 1, background: "var(--bg)" }}>
      <div style={{ padding: `${safeTopM(12)} 16px 6px`, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 26, margin: 0 }}>นัดพบเพื่อน</h1>
          <button onClick={() => go("createMeetup")} style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "6px 10px", borderRadius: 999, border: 0, cursor: "pointer",
            background: "var(--accent)", color: "var(--paper)",
            fontFamily: "var(--ui)", fontSize: 12, fontWeight: 600,
          }}>
            <Icon name="plus" size={13} stroke="var(--paper)"/> นัดใหม่
          </button>
        </div>
        <div style={{ marginTop: 8, fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)" }}>
          {d.meetups.length} นัด · กำลังจะมาถึงในเร็ว ๆ นี้
        </div>
        <div style={{ display: "flex", gap: 6, overflowX: "auto", padding: "12px 0", margin: "0 -16px", paddingLeft: 16, paddingRight: 16 }}>
          {[
            ["all", "ทั้งหมด"],
            ["going", "ที่ฉันร่วม"],
            ["bkk", "กรุงเทพฯ"],
            ["upcountry", "ต่างจังหวัด"],
          ].map(([k, l]) => (
            <Chip key={k} active={filter === k} onClick={() => setFilter(k)} size="sm">{l}</Chip>
          ))}
        </div>
      </div>

      <div style={{ padding: "14px 16px 110px", display: "flex", flexDirection: "column", gap: 12 }}>
        {filtered.map(m => <MeetupCard key={m.id} m={m} go={go} sepia={sepia} myId={myId} myRsvps={myRsvps}/>)}
        {filtered.length === 0 && (
          <div style={{ padding: "40px 20px", textAlign: "center", color: "var(--ink-muted)" }}>
            <Icon name="bell" size={40} stroke="var(--border)"/>
            <div style={{ fontFamily: "var(--ui)", fontSize: 14, marginTop: 10 }}>ยังไม่มีนัดในหมวดนี้</div>
            <button onClick={() => go("createMeetup")} style={{
              marginTop: 12, padding: "8px 14px", borderRadius: 999, border: "1px solid var(--accent)",
              background: "transparent", color: "var(--accent)", cursor: "pointer",
              fontFamily: "var(--ui)", fontSize: 13, fontWeight: 500,
            }}>นัดเพื่อนกันเลย</button>
          </div>
        )}
      </div>
    </div>
  );
}

function MeetupCard({ m, go, sepia, myId, myRsvps }) {
  const host = m.host === "class" ? null : personM(m.host);
  const sd = shortDate(m.date);

  // Determine my status: API first, then static data
  let meStatus = null;
  if (myId && myId in myRsvps) {
    const s = myRsvps[m.id];
    if (s === "going") meStatus = "going";
    else if (s === "maybe") meStatus = "maybe";
  } else {
    const staticGoing = m.going.includes(myId) || (myId === "me" && m.going.includes("me"));
    const staticMaybe = m.maybe.includes(myId) || (myId === "me" && m.maybe.includes("me"));
    if (staticGoing) meStatus = "going";
    else if (staticMaybe) meStatus = "maybe";
  }

  return (
    <button onClick={() => go("meetup", m.id)} style={{
      width: "100%", padding: 0, border: "1px solid var(--border)", borderRadius: 14,
      background: "var(--paper)", overflow: "hidden", cursor: "pointer", textAlign: "left",
      display: "flex", flexDirection: "column",
    }}>
      <div style={{ position: "relative", height: 110 }}>
        <Photo hue={m.hue} sepia={sepia} kind="scene" label={m.placeNote.toUpperCase()}/>
        <div style={{
          position: "absolute", left: 12, top: 12,
          background: "var(--paper)", borderRadius: 8, padding: "5px 9px",
          display: "flex", flexDirection: "column", alignItems: "center", minWidth: 44,
          boxShadow: "0 2px 8px rgba(0,0,0,0.18)",
        }}>
          <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, letterSpacing: 1, color: "var(--accent)" }}>{sd.m}</div>
          <div style={{ fontFamily: "'Newsreader', serif", fontSize: 22, lineHeight: 1, color: "var(--ink)" }}>{sd.d}</div>
        </div>
        {meStatus && (
          <div style={{
            position: "absolute", right: 12, top: 12,
            padding: "4px 10px", borderRadius: 999,
            background: meStatus === "going" ? "var(--accent)" : "var(--paper)",
            color: meStatus === "going" ? "var(--paper)" : "var(--ink)",
            fontFamily: "var(--ui)", fontSize: 11, fontWeight: 600,
            display: "inline-flex", alignItems: "center", gap: 4,
          }}>
            {meStatus === "going" && <Icon name="check" size={11} stroke="var(--paper)"/>}
            {meStatus === "going" ? "เข้าร่วม" : "อาจไป"}
          </div>
        )}
      </div>

      <div style={{ padding: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase" }}>
          {m.weekday} · {m.time}–{m.endTime}
          <span style={{ width: 3, height: 3, background: "var(--ink-muted)", borderRadius: "50%" }}/>
          {VIBE[m.vibe].label}
        </div>
        <div style={{ fontFamily: "'Newsreader', serif", fontSize: 18, lineHeight: 1.2, color: "var(--ink)", marginTop: 5 }}>
          {m.title}
        </div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 4, marginTop: 6, fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)" }}>
          <Icon name="pin" size={12}/> {m.place} · {m.district}
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12 }}>
          <AvatarStack ids={m.going} sepia={sepia} total={m.going.length}/>
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--ui)", fontSize: 11.5, color: "var(--ink-muted)" }}>
            {host ? <><span>โดย {host.nick}</span><Avatar person={host} size={20} sepia={sepia}/></> :
              <><span>โดย รุ่น 46</span><div style={{
                width: 20, height: 20, borderRadius: "50%", background: "var(--sage)", color: "var(--paper)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "'Newsreader', serif", fontSize: 10,
              }}>46</div></>}
          </div>
        </div>
      </div>
    </button>
  );
}

function AvatarStack({ ids, sepia, total }) {
  const list = ids.slice(0, 4);
  return (
    <div style={{ display: "flex", alignItems: "center" }}>
      <div style={{ display: "flex" }}>
        {list.map((id, i) => {
          const p = personM(id); if (!p) return null;
          return <div key={id} style={{ marginLeft: i === 0 ? 0 : -8, borderRadius: "50%", boxShadow: "0 0 0 2px var(--paper)" }}>
            <Avatar person={p} size={24} sepia={sepia}/>
          </div>;
        })}
      </div>
      <div style={{ marginLeft: 8, fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink)" }}>
        <b style={{ fontWeight: 600 }}>{total}</b> <span style={{ color: "var(--ink-muted)" }}>คนร่วม</span>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 2) MeetupDetailScreen — with live RSVP from D1
// ────────────────────────────────────────────────────────────
function MeetupDetailScreen({ id, go, sepia }) {
  const base = Dm().meetups.find(m => m.id === id) || Dm().meetups[0];
  const host = base.host === "class" ? null : personM(base.host);
  const myId = RBAC_ME().id;

  // rsvpMap: {userId: status} — null means not yet loaded from API
  const [rsvpMap, setRsvpMap] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    RBAC_API.getMeetupRsvps(id).then(data => {
      if (data && Array.isArray(data)) {
        const map = {};
        data.forEach(({ user_id, status }) => { map[user_id] = status; });
        setRsvpMap(map);
      } else {
        setRsvpMap({}); // API unavailable — use empty map (fall back to static)
      }
    }).catch(() => setRsvpMap({}));
  }, [id]);

  // Compute the going/maybe lists by merging static data with API overrides
  const staticGoing = new Set(base.going);
  const staticMaybe = new Set(base.maybe);
  const staticDecline = new Set(base.decline);

  // All known participant IDs
  const allIds = new Set([
    ...base.going, ...base.maybe, ...base.decline,
    ...(rsvpMap ? Object.keys(rsvpMap) : []),
    myId,
  ]);

  const statusOf = (uid) => {
    if (rsvpMap && uid in rsvpMap) return rsvpMap[uid];
    // Fall back to static data — "me" in static maps to myId
    if (staticGoing.has(uid) || (uid === myId && staticGoing.has("me"))) return "going";
    if (staticMaybe.has(uid) || (uid === myId && staticMaybe.has("me"))) return "maybe";
    if (staticDecline.has(uid) || (uid === myId && staticDecline.has("me"))) return "decline";
    return null;
  };

  const goingIds = [...allIds].filter(uid => statusOf(uid) === "going");
  const maybeIds = [...allIds].filter(uid => statusOf(uid) === "maybe");
  const myStatus = statusOf(myId);

  const handleRsvp = async (k) => {
    if (saving) return;
    const newStatus = myStatus === k ? "none" : k;
    // Optimistic UI update
    setRsvpMap(prev => {
      const m = { ...(prev || {}) };
      if (newStatus === "none") delete m[myId];
      else m[myId] = newStatus;
      return m;
    });
    setSaving(true);
    await RBAC_API.setRsvp(id, newStatus);
    setSaving(false);
  };

  return (
    <div style={{ flex: 1, background: "var(--bg)", overflow: "auto" }}>
      <div style={{ position: "relative", height: 240 }}>
        <Photo hue={base.hue} sepia={sepia} kind="scene" label={`MEETUP · ${base.placeNote.toUpperCase()}`} year={base.weekday.toUpperCase()}/>
        <div style={{
          position: "absolute", inset: 0,
          background: "linear-gradient(180deg, rgba(35,28,22,0.3) 0%, transparent 30%, rgba(35,28,22,0.55) 100%)",
        }}/>
        <button onClick={() => go("meetups")} style={{
          position: "absolute", left: 14, top: safeTopM(12), width: 36, height: 36, borderRadius: "50%",
          background: "rgba(251,247,237,0.92)", backdropFilter: "blur(8px)",
          border: 0, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon name="back" size={18}/>
        </button>
        <div style={{ position: "absolute", right: 14, top: safeTopM(12), display: "flex", gap: 6 }}>
          <button style={{
            width: 36, height: 36, borderRadius: "50%", background: "rgba(251,247,237,0.92)",
            border: 0, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
          }}><Icon name="share" size={16}/></button>
        </div>
        <div style={{ position: "absolute", left: 18, bottom: 16, right: 18, color: "var(--paper)" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 9px", borderRadius: 999, background: "rgba(251,247,237,0.18)", backdropFilter: "blur(6px)", fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, textTransform: "uppercase" }}>
            <Icon name={VIBE[base.vibe].icon} size={11} stroke="var(--paper)"/> {VIBE[base.vibe].label}
          </div>
          <div style={{ fontFamily: "'Newsreader', serif", fontSize: 28, lineHeight: 1.1, marginTop: 8 }}>
            {base.title}
          </div>
        </div>
      </div>

      <div style={{ padding: "14px 16px 120px" }}>
        <div style={{
          padding: 14, borderRadius: 12, background: "var(--paper)", border: "1px solid var(--border)",
          display: "flex", flexDirection: "column", gap: 12,
        }}>
          <Fact icon="bell" label="วันและเวลา">
            {base.weekday} · {fmtDate(base.date)}<br/>
            <span style={{ color: "var(--ink-muted)", fontSize: 12 }}>{base.time} – {base.endTime}</span>
          </Fact>
          <Fact icon="pin" label="สถานที่">
            {base.place}<br/>
            <span style={{ color: "var(--ink-muted)", fontSize: 12 }}>{base.placeNote}</span>
          </Fact>
          <Fact icon="user" label="ผู้นัด">
            {host ? <><b style={{ fontWeight: 600 }}>{host.nick}</b> · {host.name}</> : "รุ่น 46 · ทีมรวมรุ่น"}
          </Fact>
        </div>

        <div style={{ marginTop: 16, fontFamily: "var(--ui)", fontSize: 13.5, color: "var(--ink)", lineHeight: 1.55, textWrap: "pretty" }}>
          {base.description}
        </div>

        {/* capacity bar */}
        <div style={{ marginTop: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)" }}>
            <span><b style={{ color: "var(--ink)", fontWeight: 600 }}>{goingIds.length}</b> / {base.capacity} เข้าร่วม
              {rsvpMap === null && <span style={{ marginLeft: 8, opacity: 0.5 }}>กำลังโหลด…</span>}
            </span>
            <span>{Math.round(goingIds.length / base.capacity * 100)}% เต็ม</span>
          </div>
          <div style={{ marginTop: 6, height: 6, borderRadius: 3, background: "var(--border)", overflow: "hidden" }}>
            <div style={{ height: "100%", width: `${Math.min(100, goingIds.length / base.capacity * 100)}%`, background: "var(--accent)", transition: "width .3s" }}/>
          </div>
        </div>

        {/* attendee list */}
        <Section title="ใครมาบ้าง">
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {goingIds.map(uid => {
              const p = personM(uid); if (!p) return null;
              const isMe = uid === myId;
              return (
                <div key={uid} onClick={() => !isMe && go("profile", uid)} style={{
                  display: "flex", alignItems: "center", gap: 10, padding: "8px 10px",
                  background: "var(--paper)", borderRadius: 10, border: "1px solid var(--border)",
                  cursor: isMe ? "default" : "pointer",
                }}>
                  <Avatar person={p} size={36} sepia={sepia}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink)" }}>
                      {p.nick}{isMe ? " (ฉัน)" : ""} · {p.name}
                    </div>
                    <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)" }}>
                      {p.role} · {p.province}
                    </div>
                  </div>
                  <Icon name="check" size={14} stroke="var(--accent)"/>
                </div>
              );
            })}
            {maybeIds.length > 0 && (
              <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase", padding: "10px 4px 4px" }}>
                อาจมา · {maybeIds.length} คน
              </div>
            )}
            {maybeIds.map(uid => {
              const p = personM(uid); if (!p) return null;
              const isMe = uid === myId;
              return (
                <div key={uid} style={{
                  display: "flex", alignItems: "center", gap: 10, padding: "8px 10px",
                  background: "transparent", borderRadius: 10, border: "1px dashed var(--border)",
                }}>
                  <Avatar person={p} size={32} sepia={sepia}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink)" }}>{p.nick}{isMe ? " (ฉัน)" : ""}</div>
                    <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)" }}>{p.province}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Section>
      </div>

      {/* sticky RSVP bar */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 70,
        padding: "12px 14px 28px", background: "rgba(251,247,237,0.92)",
        backdropFilter: "blur(14px)", borderTop: "1px solid var(--border)",
        display: "flex", gap: 8,
      }}>
        {[
          { k: "going",   label: "ไปแน่",  icon: "check", primary: true },
          { k: "maybe",   label: "อาจไป",  icon: "spark" },
          { k: "decline", label: "ไม่ว่าง", icon: "close" },
        ].map(({ k, label, icon, primary }) => {
          const on = myStatus === k;
          return (
            <button key={k} onClick={() => handleRsvp(k)} disabled={saving} style={{
              flex: primary ? 2 : 1, padding: "11px 6px", borderRadius: 12, border: 0, cursor: saving ? "wait" : "pointer",
              background: on ? (primary ? "var(--accent)" : "var(--ink)") : (primary ? "var(--accent-tint)" : "transparent"),
              color: on ? "var(--paper)" : (primary ? "var(--accent-dark)" : "var(--ink)"),
              fontFamily: "var(--ui)", fontSize: 13, fontWeight: 600,
              display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
              border: !on && !primary ? "1px solid var(--border)" : 0,
              transition: "all .2s", opacity: saving ? 0.7 : 1,
            }}>
              <Icon name={icon} size={15} stroke={on ? "var(--paper)" : (primary ? "var(--accent-dark)" : "var(--ink)")}/>
              {label}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Fact({ icon, label, children }) {
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
      <div style={{
        width: 36, height: 36, borderRadius: 8, background: "var(--accent-tint)",
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      }}>
        <Icon name={icon} size={16} stroke="var(--accent-dark)"/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, letterSpacing: 0.8, textTransform: "uppercase", color: "var(--ink-muted)" }}>{label}</div>
        <div style={{ fontFamily: "var(--ui)", fontSize: 14, color: "var(--ink)", marginTop: 3, lineHeight: 1.4 }}>{children}</div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 3) CreateMeetupScreen
// ────────────────────────────────────────────────────────────
function CreateMeetupScreen({ go }) {
  const [title, setTitle] = React.useState("");
  const [date, setDate] = React.useState("2569-05-30");
  const [time, setTime] = React.useState("18:00");
  const [place, setPlace] = React.useState("");
  const [vibe, setVibe] = React.useState("casual");
  const [invite, setInvite] = React.useState("all");
  const valid = title && place;

  return (
    <div style={{ flex: 1, background: "var(--bg)" }}>
      <div style={{ padding: `${safeTopM(12)} 16px 14px`, display: "flex", alignItems: "center", gap: 10, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <button onClick={() => go("meetups")} style={{ background: "none", border: 0, cursor: "pointer" }}>
          <Icon name="close" size={20}/>
        </button>
        <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 20, margin: 0, flex: 1 }}>นัดเพื่อนใหม่</h1>
        <button disabled={!valid} onClick={() => valid && go("meetups")} style={{
          padding: "7px 14px", borderRadius: 999, border: 0, cursor: valid ? "pointer" : "not-allowed",
          background: valid ? "var(--accent)" : "var(--border)",
          color: valid ? "var(--paper)" : "var(--ink-muted)",
          fontFamily: "var(--ui)", fontSize: 13, fontWeight: 600,
        }}>โพสต์</button>
      </div>

      <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="ชื่อนัด">
          <input value={title} onChange={e => setTitle(e.target.value)} placeholder="เช่น ดื่มกาแฟยามเช้า"
            style={inpStyle}/>
        </Field>

        <Field label="วันและเวลา">
          <div style={{ display: "flex", gap: 8 }}>
            <input value={date} onChange={e => setDate(e.target.value)} type="text" style={{ ...inpStyle, flex: 2 }}/>
            <input value={time} onChange={e => setTime(e.target.value)} type="text" style={{ ...inpStyle, flex: 1 }}/>
          </div>
          <div style={{ display: "flex", gap: 5, marginTop: 8, flexWrap: "wrap" }}>
            {["พรุ่งนี้", "เสาร์นี้", "อาทิตย์นี้", "สุดสัปดาห์หน้า"].map(s => (
              <Chip key={s} size="sm">{s}</Chip>
            ))}
          </div>
        </Field>

        <Field label="สถานที่">
          <input value={place} onChange={e => setPlace(e.target.value)} placeholder="ชื่อร้าน หรือพิกัด"
            style={inpStyle}/>
        </Field>

        <Field label="บรรยากาศ">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
            {Object.entries(VIBE).map(([k, v]) => (
              <button key={k} onClick={() => setVibe(k)} style={{
                padding: "10px 8px", borderRadius: 10, cursor: "pointer", textAlign: "center",
                background: vibe === k ? "var(--accent-tint)" : "var(--paper)",
                border: `1px solid ${vibe === k ? "var(--accent)" : "var(--border)"}`,
                fontFamily: "var(--ui)", fontSize: 12, color: vibe === k ? "var(--accent-dark)" : "var(--ink)",
                display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
                fontWeight: vibe === k ? 600 : 400,
              }}>
                <Icon name={v.icon} size={18} stroke={vibe === k ? "var(--accent-dark)" : "var(--ink-muted)"}/>
                {v.label}
              </button>
            ))}
          </div>
        </Field>

        <Field label="ใครได้รับเชิญ">
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {[
              ["all", "เพื่อนทุกคนในรุ่น", "184 คน"],
              ["bkk", "เพื่อนในกรุงเทพฯ", "47 คน"],
              ["nearby", "เพื่อนใกล้สถานที่นัด (5 กม.)", "12 คน"],
              ["select", "เลือกเอง", "—"],
            ].map(([k, l, c]) => (
              <button key={k} onClick={() => setInvite(k)} style={{
                padding: "11px 14px", borderRadius: 10, cursor: "pointer", textAlign: "left",
                background: invite === k ? "var(--accent-tint)" : "var(--paper)",
                border: `1px solid ${invite === k ? "var(--accent)" : "var(--border)"}`,
                display: "flex", alignItems: "center", gap: 10,
              }}>
                <div style={{
                  width: 18, height: 18, borderRadius: "50%",
                  border: `2px solid ${invite === k ? "var(--accent)" : "var(--border)"}`,
                  background: invite === k ? "var(--accent)" : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  {invite === k && <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--paper)" }}/>}
                </div>
                <div style={{ flex: 1, fontFamily: "var(--ui)", fontSize: 13.5, color: "var(--ink)" }}>{l}</div>
                <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10.5, color: "var(--ink-muted)" }}>{c}</div>
              </button>
            ))}
          </div>
        </Field>

        <div style={{
          padding: 12, borderRadius: 10, background: "var(--paper)", border: "1px solid var(--border)",
          display: "flex", gap: 10, alignItems: "flex-start",
        }}>
          <Icon name="line" size={18} stroke="var(--sage)"/>
          <div style={{ fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", lineHeight: 1.5 }}>
            จะส่ง Broadcast ทาง LINE OA ไปยังเพื่อนที่เลือก พร้อมปุ่ม RSVP ตอบกลับในแชต
          </div>
        </div>
      </div>
    </div>
  );
}

const inpStyle = {
  width: "100%", padding: "11px 14px", borderRadius: 10,
  border: "1px solid var(--border)", background: "var(--paper)",
  fontFamily: "var(--ui)", fontSize: 14, color: "var(--ink)", outline: "none",
};

function Field({ label, children }) {
  return (
    <div>
      <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase", marginBottom: 8 }}>
        {label}
      </div>
      {children}
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ padding: "18px 0 0" }}>
      <h3 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 17, color: "var(--ink)", margin: "0 0 10px", letterSpacing: -0.2 }}>{title}</h3>
      {children}
    </div>
  );
}

Object.assign(window, { MeetupsScreen, MeetupDetailScreen, CreateMeetupScreen });
