// screens.jsx — Rbac46 production screens

const D      = () => window.RBAC_DATA;
const cat    = (id) => D().helpCategories.find(c => c.id === id);
const person = (id) => {
  if (!id || id === "me") return RBAC_ME();
  return D().alumni.find(a => a.id === id) || RBAC_ME();
};

// Safe-area-aware top padding helper (works in inline styles)
const safeTop = (extra = 16) => `calc(var(--safe-t) + ${extra}px)`;

// ────────────────────────────────────────────────────────────
// 0) Login — LINE OAuth + identity picker
// ────────────────────────────────────────────────────────────
const LINE_ICON = (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
    <path d="M19.365 9.863c.349 0 .63.285.63.631 0 .345-.281.63-.63.63H17.61v1.125h1.755c.349 0 .63.283.63.63 0 .344-.281.629-.63.629h-2.386c-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63h2.386c.346 0 .627.285.627.63 0 .349-.281.63-.63.63H17.61v1.125h1.755zm-3.855 3.016c0 .27-.174.51-.432.596-.064.021-.133.031-.199.031-.211 0-.391-.09-.51-.25l-2.443-3.317v2.94c0 .344-.279.629-.631.629-.346 0-.626-.285-.626-.629V8.108c0-.27.173-.51.43-.595.06-.023.136-.033.194-.033.195 0 .375.104.495.254l2.462 3.33V8.108c0-.345.282-.63.63-.63.345 0 .63.285.63.63v4.771zm-5.741 0c0 .344-.282.629-.631.629-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63.346 0 .628.285.628.63v4.771zm-2.466.629H4.917c-.345 0-.63-.285-.63-.629V8.108c0-.345.285-.63.63-.63.348 0 .63.285.63.63v4.141h1.756c.348 0 .629.283.629.63 0 .344-.281.629-.629.629M24 10.314C24 4.943 18.615.572 12 .572S0 4.943 0 10.314c0 4.811 4.27 8.842 10.035 9.608.391.082.923.258 1.058.59.12.301.079.766.038 1.08l-.164 1.02c-.045.301-.24 1.186 1.049.645 1.291-.539 6.916-4.078 9.436-6.975C23.176 14.393 24 12.458 24 10.314"/>
  </svg>
);

function SplashScreen({ onEnter }) {
  const [step,      setStep]      = React.useState("check"); // check|line|pick
  const [lineName,  setLineName]  = React.useState("");
  const [linePic,   setLinePic]   = React.useState("");
  const [mode,      setMode]      = React.useState("search"); // search|add
  const [pickedId,  setPickedId]  = React.useState("");
  const [search,    setSearch]    = React.useState("");
  const [formName,  setFormName]  = React.useState("");
  const [formNick,  setFormNick]  = React.useState("");
  const [formRole,  setFormRole]  = React.useState("");
  const [linking,   setLinking]   = React.useState(false);
  const [authErr,   setAuthErr]   = React.useState(false);
  const lineUidRef = React.useRef(null);

  React.useEffect(() => {
    try {
      const params   = new URLSearchParams(window.location.search);
      const lUid     = params.get("line_uid");
      const alumniId = params.get("alumni_id");
      const lName    = params.get("line_name") || "";
      const lPic     = params.get("line_picture") || "";
      const isErr    = params.get("auth_error");

      if (params.toString()) window.history.replaceState({}, "", window.location.pathname);

      if (isErr) { setAuthErr(true); setStep("line"); return; }

      if (lUid && alumniId) {
        RBAC_SET_ME(alumniId, lUid);
        onEnter(); return;
      }

      if (lUid) {
        lineUidRef.current = lUid;
        setLineName(lName);
        setLinePic(lPic);
        setFormName(lName);
        setStep("pick"); return;
      }

      // Restore existing session
      const uid = localStorage.getItem("rbac46_uid");
      if (uid) {
        if (D().alumni.find(a => a.id === uid)) { onEnter(); return; }
        try {
          const p = JSON.parse(localStorage.getItem("rbac46_profile") || "null");
          if (p && p.id === uid) { onEnter(); return; }
        } catch {}
      }
    } catch {}
    setStep("line");
  }, []);

  // ── confirm from alumni list ───────────────────────────────
  const handlePickAlumni = async () => {
    if (!pickedId) return;
    setLinking(true);
    const lUid = lineUidRef.current;
    if (lUid) await RBAC_API.linkLine(lUid, pickedId);
    RBAC_SET_ME(pickedId, lUid || undefined);
    onEnter();
  };

  // ── confirm from add-yourself form ────────────────────────
  const handleAddSelf = async () => {
    const name = formName.trim();
    if (!name) return;
    setLinking(true);
    const lUid = lineUidRef.current;
    const id   = lUid ? `line_${lUid}` : `manual_${Date.now()}`;
    const profile = {
      id, name,
      nick:       formNick.trim() || name.split(" ")[0],
      role:       formRole.trim(),
      province:   "",
      hue:        210,
      help:       [],
      since:      2546,
      active:     true,
      pictureUrl: linePic,
    };
    if (lUid) {
      await RBAC_API.createProfile({
        line_uid: lUid, name: profile.name, nick: profile.nick,
        role: profile.role, picture_url: linePic,
      });
    }
    RBAC_SET_PROFILE(profile);
    onEnter();
  };

  const filtered = D().alumni.filter(a =>
    !search || a.name.includes(search) || a.nick.includes(search)
  );

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

  // ── loading ────────────────────────────────────────────────
  if (step === "check") return (
    <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)" }}>
      <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, letterSpacing: 2, color: "var(--ink-muted)", textTransform: "uppercase" }}>กำลังโหลด…</div>
    </div>
  );

  // ── LINE login ─────────────────────────────────────────────
  if (step === "line") return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "space-between", padding: `${safeTop(48)} 28px max(var(--safe-b), 48px)`, background: "var(--bg)" }}>
      <div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "4px 10px 4px 8px", borderRadius: 4, border: "1px dashed var(--ink-muted)", marginBottom: 28 }}>
          <div style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--accent)" }}/>
          <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1.5, color: "var(--ink-muted)", textTransform: "uppercase" }}>CL.46 · Alumni Network</span>
        </div>
        <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 500, fontStyle: "italic", fontSize: 72, lineHeight: 0.88, letterSpacing: -3, color: "var(--ink)", margin: 0 }}>
          Rbac<span style={{ fontStyle: "normal", color: "var(--accent)" }}>.</span>
        </h1>
        <p style={{ fontFamily: "var(--ui)", fontSize: 15, color: "var(--ink-muted)", marginTop: 14, lineHeight: 1.6 }}>
          เพื่อนเก่า · เครือข่ายใหม่<br/>เครือข่ายศิษย์เก่ารุ่น 46
        </p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {authErr && (
          <div style={{ padding: "12px 16px", borderRadius: 12, background: "var(--accent-tint)", fontFamily: "var(--ui)", fontSize: 13, color: "var(--accent-dark)", textAlign: "center" }}>
            เข้าสู่ระบบไม่สำเร็จ — กรุณาลองอีกครั้ง
          </div>
        )}
        <a href="/api/auth/line" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "18px", borderRadius: 14, textDecoration: "none", background: "#06C755", color: "#fff", fontFamily: "var(--ui)", fontSize: 16, fontWeight: 700 }}>
          {LINE_ICON} เข้าสู่ระบบด้วย LINE
        </a>
        <p style={{ textAlign: "center", fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", margin: 0 }}>สำหรับศิษย์เก่า Rbac เท่านั้น</p>
      </div>
    </div>
  );

  // ── identity picker ────────────────────────────────────────
  return (
    <div style={{ flex: 1, background: "var(--bg)", display: "flex", flexDirection: "column", overflow: "hidden" }}>

      {/* LINE profile card */}
      <div style={{ padding: `${safeTop(14)} 20px 14px`, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
          {linePic ? (
            <img src={linePic} alt="" style={{ width: 52, height: 52, borderRadius: "50%", objectFit: "cover", border: "2px solid var(--border)" }}/>
          ) : (
            <div style={{ width: 52, height: 52, borderRadius: "50%", background: "#06C755", display: "flex", alignItems: "center", justifyContent: "center" }}>
              {LINE_ICON}
            </div>
          )}
          <div>
            <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)", letterSpacing: 0.5 }}>เชื่อมต่อด้วย LINE แล้ว</div>
            <div style={{ fontFamily: "'Newsreader', serif", fontSize: 20, color: "var(--ink)", lineHeight: 1.2 }}>{lineName || "ผู้ใช้ LINE"}</div>
          </div>
        </div>

        {/* tabs */}
        <div style={{ display: "flex", gap: 6 }}>
          {[["search", "ค้นจากทำเนียบรุ่น"], ["add", "เพิ่มข้อมูลตัวเอง"]].map(([m, label]) => (
            <button key={m} onClick={() => { setMode(m); setPickedId(""); }} style={{
              flex: 1, padding: "9px 6px", borderRadius: 10, border: 0, cursor: "pointer",
              background: mode === m ? "var(--ink)" : "var(--border)",
              color: mode === m ? "var(--paper)" : "var(--ink-muted)",
              fontFamily: "var(--ui)", fontSize: 13, fontWeight: mode === m ? 600 : 400,
              transition: "background .15s",
            }}>{label}</button>
          ))}
        </div>
      </div>

      {/* content */}
      {mode === "search" ? (
        <>
          <div style={{ padding: "10px 16px 4px", background: "var(--bg)" }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="ค้นชื่อ-สกุล หรือชื่อเล่น…" style={{ ...inp, background: "var(--paper)" }}/>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: "8px 16px 8px", display: "flex", flexDirection: "column", gap: 8 }}>
            {filtered.map(a => (
              <button key={a.id} onClick={() => setPickedId(a.id)} style={{
                display: "flex", gap: 12, alignItems: "center", padding: "12px 14px", borderRadius: 14,
                border: `1.5px solid ${pickedId === a.id ? "var(--accent)" : "var(--border)"}`,
                background: pickedId === a.id ? "var(--accent-tint)" : "var(--paper)",
                cursor: "pointer", textAlign: "left", width: "100%", transition: "border-color .15s, background .15s",
              }}>
                <Avatar person={a} size={46}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "'Newsreader', serif", fontSize: 16, color: "var(--ink)", lineHeight: 1.15 }}>
                    {a.name}<span style={{ fontStyle: "italic", color: "var(--ink-muted)", fontSize: 14 }}> ({a.nick})</span>
                  </div>
                  <div style={{ fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", marginTop: 2 }}>{a.role}</div>
                </div>
                {pickedId === a.id && <Icon name="check" size={18} stroke="var(--accent)"/>}
              </button>
            ))}
            {filtered.length === 0 && (
              <div style={{ textAlign: "center", padding: "30px 0", fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-muted)" }}>
                ไม่พบชื่อ — ลองค้นคำอื่น หรือเปลี่ยนแท็บ "เพิ่มข้อมูลตัวเอง"
              </div>
            )}
            <div style={{ height: 8 }}/>
          </div>
          <div style={{ padding: `10px 16px max(var(--safe-b), 20px)`, background: "var(--paper)", borderTop: "1px solid var(--border)" }}>
            <button disabled={!pickedId || linking} onClick={handlePickAlumni} style={{
              width: "100%", padding: "17px", borderRadius: 14, border: 0,
              background: pickedId && !linking ? "var(--ink)" : "var(--border)",
              color: pickedId && !linking ? "var(--paper)" : "var(--ink-muted)",
              fontFamily: "var(--ui)", fontSize: 16, fontWeight: 600,
              cursor: pickedId && !linking ? "pointer" : "default", transition: "background .2s",
            }}>{linking ? "กำลังเข้าสู่ระบบ…" : "ยืนยัน — นี่คือฉัน"}</button>
          </div>
        </>
      ) : (
        <>
          <div style={{ flex: 1, overflowY: "auto", padding: "16px 16px 8px", display: "flex", flexDirection: "column", gap: 14 }}>
            <div>
              <label style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase" }}>ชื่อ-สกุล *</label>
              <input value={formName} onChange={e => setFormName(e.target.value)} placeholder="กรอกชื่อ-นามสกุล" style={{ ...inp, marginTop: 6 }}/>
            </div>
            <div>
              <label style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase" }}>ชื่อเล่น</label>
              <input value={formNick} onChange={e => setFormNick(e.target.value)} placeholder="ชื่อเล่น (ถ้ามี)" style={{ ...inp, marginTop: 6 }}/>
            </div>
            <div>
              <label style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase" }}>อาชีพ / ตำแหน่ง</label>
              <input value={formRole} onChange={e => setFormRole(e.target.value)} placeholder="เช่น วิศวกร, ครู, นักธุรกิจ" style={{ ...inp, marginTop: 6 }}/>
            </div>
            <div style={{ padding: "10px 14px", borderRadius: 10, background: "var(--accent-tint)", fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)", lineHeight: 1.5 }}>
              ข้อมูลจาก LINE: <b style={{ color: "var(--ink)" }}>{lineName || "—"}</b><br/>
              ชื่อและรูปโปรไฟล์ LINE จะถูกนำมาใช้ในระบบ
            </div>
          </div>
          <div style={{ padding: `10px 16px max(var(--safe-b), 20px)`, background: "var(--paper)", borderTop: "1px solid var(--border)" }}>
            <button disabled={!formName.trim() || linking} onClick={handleAddSelf} style={{
              width: "100%", padding: "17px", borderRadius: 14, border: 0,
              background: formName.trim() && !linking ? "var(--ink)" : "var(--border)",
              color: formName.trim() && !linking ? "var(--paper)" : "var(--ink-muted)",
              fontFamily: "var(--ui)", fontSize: 16, fontWeight: 600,
              cursor: formName.trim() && !linking ? "pointer" : "default", transition: "background .2s",
            }}>{linking ? "กำลังบันทึก…" : "บันทึกและเข้าสู่ระบบ"}</button>
          </div>
        </>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 1) Home
// ────────────────────────────────────────────────────────────
function HomeScreen({ go, sepia }) {
  const d  = D();
  const me = RBAC_ME();
  const [broadcasts, setBroadcasts] = React.useState(d.broadcasts);

  React.useEffect(() => {
    RBAC_API.getBroadcasts().then(data => {
      if (Array.isArray(data) && data.length > 0) {
        setBroadcasts(data.map(b => ({
          id: b.id, kind: b.kind || "help", from: b.from_id,
          title: b.title, body: b.body,
          ago: fmtAgo(b.created_at), replies: 0,
        })));
      }
    }).catch(() => {});
  }, []);

  return (
    <div style={{ flex: 1, background: "var(--bg)" }}>
      {/* hero */}
      <div style={{
        padding: `${safeTop(20)} 22px 22px`,
        background: "var(--paper)", borderBottom: "1px solid var(--border)",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", right: -30, top: -30, width: 180, height: 180,
          borderRadius: "50%", background: "var(--accent-tint)", opacity: 0.5,
        }}/>
        <YearStamp serial="CL.46">Today</YearStamp>
        <h1 style={{
          fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 28, lineHeight: 1.2,
          color: "var(--ink)", margin: "10px 0 0", maxWidth: 290, position: "relative",
        }}>
          สวัสดี <i style={{ color: "var(--accent)" }}>{me.nick}</i> —<br/>
          วันนี้รุ่นเรา <b style={{ fontWeight: 600 }}>กระดิกตัว</b> นิดหน่อย
        </h1>
        <div style={{ display: "flex", gap: 8, marginTop: 16, position: "relative" }}>
          <Stat n={d.classInfo.members} l="สมาชิก"/>
          <Stat n={d.classInfo.activeProvinces} l="จังหวัด"/>
          <Stat n="12" l="ออนไลน์"/>
        </div>
      </div>

      {/* quick actions */}
      <div style={{ padding: "16px 16px 4px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
        <Action icon="search" label="ค้นหาเพื่อน" onClick={() => go("directory")}/>
        <Action icon="bell"   label="นัดพบเพื่อน" onClick={() => go("meetups")}/>
        <Action icon="spark"  label="ขอความช่วย" accent onClick={() => go("compose")}/>
      </div>

      <Section title="กระดานรุ่น" trailing="ดูทั้งหมด">
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {broadcasts.map(b => <BroadcastCard key={b.id} b={b} go={go} sepia={sepia}/>)}
        </div>
      </Section>

      <Section title="ออนไลน์ตอนนี้" trailing="ดูทำเนียบ" onTrailing={() => go("directory")}>
        <div style={{ display: "flex", gap: 14, overflowX: "auto", padding: "0 16px 4px", margin: "0 -16px" }}>
          {d.alumni.filter(a => a.online).map(a => (
            <button key={a.id} onClick={() => go("profile", a.id)} style={{
              background: "none", border: 0, padding: 0,
              display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
              cursor: "pointer", minWidth: 58,
            }}>
              <Avatar person={a} size={56} sepia={sepia} ring="var(--accent)"/>
              <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink)" }}>{a.nick}</div>
            </button>
          ))}
        </div>
      </Section>

      <Section title="ความทรงจำสัปดาห์นี้" trailing="คลังภาพ" onTrailing={() => go("gallery")}>
        <button onClick={() => go("gallery")} style={{
          width: "100%", height: 190, borderRadius: 16, overflow: "hidden",
          border: "1px solid var(--border)", padding: 0, background: "transparent",
          cursor: "pointer", position: "relative",
        }}>
          <Photo hue={35} kind="scene" sepia label="GRADUATION · 2546" year="ปี 4"/>
          <div style={{
            position: "absolute", left: 14, bottom: 12, color: "var(--paper)",
            fontFamily: "'Newsreader', serif", fontSize: 22, fontStyle: "italic",
            textShadow: "0 2px 6px rgba(0,0,0,0.5)",
          }}>
            วันรับปริญญา<br/>
            <span style={{ fontFamily: "var(--ui)", fontSize: 12, fontStyle: "normal", opacity: 0.9 }}>23 ภาพ · 2546</span>
          </div>
        </button>
      </Section>

      <div style={{ height: 120 }}/>
    </div>
  );
}

function fmtAgo(ts) {
  if (!ts) return "";
  const diff = Date.now() - ts;
  const h = Math.floor(diff / 3600000);
  if (h < 1) return "เมื่อกี้";
  if (h < 24) return `${h} ชม.`;
  const d = Math.floor(h / 24);
  return d === 1 ? "เมื่อวาน" : `${d} วัน`;
}

function Stat({ n, l }) {
  return (
    <div style={{ flex: 1, padding: "10px 12px", borderRadius: 10, background: "var(--bg)", border: "1px solid var(--border)" }}>
      <div style={{ fontFamily: "'Newsreader', serif", fontSize: 22, color: "var(--ink)", lineHeight: 1 }}>{n}</div>
      <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)", marginTop: 4 }}>{l}</div>
    </div>
  );
}

function Action({ icon, label, accent, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 10,
      padding: "14px 12px", borderRadius: 14,
      background: accent ? "var(--accent)" : "var(--paper)",
      color: accent ? "var(--paper)" : "var(--ink)",
      border: accent ? "none" : "1px solid var(--border)",
      fontFamily: "var(--ui)", fontSize: 13.5, fontWeight: 500,
      cursor: "pointer", textAlign: "left",
    }}>
      <Icon name={icon} size={22}/>
      {label}
    </button>
  );
}

function Section({ title, children, trailing, onTrailing }) {
  return (
    <div style={{ padding: "18px 16px 0" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
        <h3 style={{
          fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 18,
          color: "var(--ink)", margin: 0, letterSpacing: -0.3,
        }}>{title}</h3>
        {trailing && (
          <button onClick={onTrailing} style={{
            background: "none", border: 0, color: "var(--ink-muted)",
            cursor: onTrailing ? "pointer" : "default",
            fontFamily: "var(--ui)", fontSize: 12.5,
          }}>{trailing} {onTrailing ? "→" : ""}</button>
        )}
      </div>
      {children}
    </div>
  );
}

function BroadcastCard({ b, go, sepia }) {
  const fromP     = b.from === "class" ? null : person(b.from);
  const kindColor = b.kind === "help" ? "var(--accent)" : "var(--sage)";
  const kindLabel = b.kind === "help" ? "ขอความช่วยเหลือ" : "กิจกรรมรุ่น";
  return (
    <div style={{
      padding: 14, borderRadius: 14, background: "var(--paper)",
      border: "1px solid var(--border)", display: "flex", gap: 12,
    }}>
      {fromP ? <Avatar person={fromP} size={40} sepia={sepia}/> : (
        <div style={{
          width: 40, height: 40, borderRadius: "50%", background: "var(--sage)",
          color: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "'Newsreader', serif", fontWeight: 500, fontSize: 18, flexShrink: 0,
        }}>46</div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
          <div style={{
            fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, letterSpacing: 0.8,
            textTransform: "uppercase", color: kindColor, fontWeight: 600,
          }}>· {kindLabel}</div>
          <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)" }}>{b.ago}</div>
        </div>
        <div style={{ fontFamily: "'Newsreader', serif", fontSize: 15.5, color: "var(--ink)", lineHeight: 1.25 }}>
          {b.title}
        </div>
        <div style={{
          fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)", marginTop: 4, lineHeight: 1.45,
          display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
        }}>{b.body}</div>
        <div style={{ display: "flex", gap: 14, marginTop: 8, fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)" }}>
          <span style={{ display: "inline-flex", gap: 4, alignItems: "center" }}>
            <Icon name="chat" size={13}/> ตอบ {b.replies || 0}
          </span>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 2) Directory
// ────────────────────────────────────────────────────────────
function DirectoryScreen({ go, sepia }) {
  const d = D();
  const [q, setQ]             = React.useState("");
  const [activeCat, setAC]    = React.useState(null);
  const [view, setView]       = React.useState("list");

  const filtered = d.alumni.filter(a => {
    if (activeCat && !a.help.includes(activeCat)) return false;
    if (q) {
      const t = q.toLowerCase();
      const cats = a.help.map(h => (cat(h)?.th + " " + cat(h)?.en).toLowerCase()).join(" ");
      if (!(a.name + a.nick + a.en + a.province + a.role + cats).toLowerCase().includes(t)) return false;
    }
    return true;
  });

  return (
    <div style={{ flex: 1, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <div style={{ padding: `${safeTop(12)} 16px 0`, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 26, margin: 0 }}>ทำเนียบรุ่น</h1>
          <div style={{ display: "flex", gap: 4, padding: 3, background: "var(--bg)", borderRadius: 8, border: "1px solid var(--border)" }}>
            {["list", "grid", "map"].map(v => (
              <button key={v} onClick={() => setView(v)} style={{
                border: 0, padding: "6px 8px", borderRadius: 6, cursor: "pointer",
                background: view === v ? "var(--ink)" : "transparent",
                color: view === v ? "var(--paper)" : "var(--ink-muted)",
              }}>
                <Icon name={v === "list" ? "list" : v === "grid" ? "grid" : "map"} size={16}/>
              </button>
            ))}
          </div>
        </div>

        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "10px 14px", borderRadius: 12, background: "var(--bg)", border: "1px solid var(--border)",
        }}>
          <Icon name="search" size={17} stroke="var(--ink-muted)"/>
          <input
            value={q} onChange={e => setQ(e.target.value)} placeholder="ค้นหาชื่อ, จังหวัด, ทักษะ..."
            style={{ flex: 1, border: 0, background: "transparent", outline: "none", fontFamily: "var(--ui)", fontSize: 14, color: "var(--ink)" }}
          />
          {q && (
            <button onClick={() => setQ("")} style={{ background: "none", border: 0, cursor: "pointer", padding: 0 }}>
              <Icon name="close" size={15} stroke="var(--ink-muted)"/>
            </button>
          )}
        </div>

        <div style={{ display: "flex", gap: 6, overflowX: "auto", padding: "10px 0 12px", margin: "0 -16px", paddingLeft: 16, paddingRight: 16 }}>
          <Chip active={!activeCat} onClick={() => setAC(null)}>
            ทั้งหมด <span style={{ opacity: 0.6, fontFamily: "'IBM Plex Mono', monospace", fontSize: 11 }}>{d.alumni.length}</span>
          </Chip>
          {d.helpCategories.map(c => (
            <Chip key={c.id} active={activeCat === c.id} onClick={() => setAC(activeCat === c.id ? null : c.id)} count={c.count}>
              {c.th}
            </Chip>
          ))}
        </div>
      </div>

      <div style={{ padding: "8px 16px 4px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10.5, letterSpacing: 1, color: "var(--ink-muted)", textTransform: "uppercase" }}>
          พบ {filtered.length} คน {activeCat && `· ${cat(activeCat).th}`}
        </div>
      </div>

      {view === "list" && (
        <div style={{ padding: "0 16px 110px", display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(a => <AlumniRow key={a.id} a={a} go={go} sepia={sepia}/>)}
          {!filtered.length && <EmptyState/>}
        </div>
      )}
      {view === "grid" && (
        <div style={{ padding: "0 16px 110px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {filtered.map(a => <AlumniCard key={a.id} a={a} go={go} sepia={sepia}/>)}
        </div>
      )}
      {view === "map" && <MapView alumni={filtered} go={go} sepia={sepia}/>}
    </div>
  );
}

function AlumniRow({ a, go, sepia }) {
  return (
    <button onClick={() => go("profile", a.id)} style={{
      background: "var(--paper)", border: "1px solid var(--border)", borderRadius: 14,
      padding: 14, display: "flex", gap: 12, alignItems: "flex-start", width: "100%", cursor: "pointer", textAlign: "left",
    }}>
      <Avatar person={a} size={50} sepia={sepia}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
          <div style={{ fontFamily: "'Newsreader', serif", fontSize: 16.5, color: "var(--ink)" }}>{a.name}</div>
          <div style={{ fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", fontStyle: "italic" }}>({a.nick})</div>
          {a.verified && <Icon name="check" size={12} stroke="var(--accent)"/>}
        </div>
        <div style={{ fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", marginTop: 2 }}>{a.role} · {a.company}</div>
        <div style={{ display: "flex", gap: 5, marginTop: 8, flexWrap: "wrap", alignItems: "center" }}>
          {a.help.slice(0, 2).map(h => (
            <span key={h} style={{
              fontFamily: "var(--ui)", fontSize: 11, padding: "3px 8px", borderRadius: 5,
              background: "var(--accent-tint)", color: "var(--accent-dark)", fontWeight: 500,
            }}>{cat(h).th}</span>
          ))}
          <span style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)", display: "inline-flex", alignItems: "center", gap: 3 }}>
            <Icon name="pin" size={11}/> {a.province}
          </span>
        </div>
      </div>
      <Icon name="chev" size={16} stroke="var(--ink-muted)"/>
    </button>
  );
}

function AlumniCard({ a, go, sepia }) {
  return (
    <button onClick={() => go("profile", a.id)} style={{
      background: "var(--paper)", border: "1px solid var(--border)", borderRadius: 14, padding: 0,
      display: "flex", flexDirection: "column", overflow: "hidden", cursor: "pointer", textAlign: "left",
    }}>
      <div style={{ height: 140, position: "relative" }}>
        <Photo hue={a.hue} sepia={sepia} kind="portrait"/>
        <div style={{
          position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "'Newsreader', serif", fontSize: 40, color: "rgba(255,255,255,0.95)",
          textShadow: "0 2px 8px rgba(0,0,0,0.4)", fontStyle: "italic",
        }}>{a.nick}</div>
        {a.verified && (
          <div style={{
            position: "absolute", top: 8, right: 8, padding: "3px 7px", borderRadius: 4,
            background: "var(--paper)", display: "flex", gap: 3, alignItems: "center",
            fontFamily: "'IBM Plex Mono', monospace", fontSize: 9, color: "var(--accent)", letterSpacing: 0.5,
          }}>
            <Icon name="check" size={10} stroke="var(--accent)"/> VER
          </div>
        )}
      </div>
      <div style={{ padding: "10px 12px" }}>
        <div style={{ fontFamily: "'Newsreader', serif", fontSize: 14.5, color: "var(--ink)", lineHeight: 1.2 }}>{a.name}</div>
        <div style={{ fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)", marginTop: 3 }}>{a.role}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 3, marginTop: 6, fontFamily: "var(--ui)", fontSize: 11, color: "var(--ink-muted)" }}>
          <Icon name="pin" size={10}/> {a.province}
        </div>
      </div>
    </button>
  );
}

function EmptyState() {
  return (
    <div style={{ padding: "48px 20px", textAlign: "center", color: "var(--ink-muted)" }}>
      <Icon name="search" size={44} stroke="var(--border)"/>
      <div style={{ fontFamily: "var(--ui)", fontSize: 14, marginTop: 12 }}>ไม่พบเพื่อนที่ค้นหา</div>
      <div style={{ fontSize: 12, marginTop: 6 }}>ลองคำอื่นหรือล้างตัวกรอง</div>
    </div>
  );
}

function MapView({ alumni, go }) {
  const provs  = window.PROVINCE_COORDS;
  const groups = {};
  alumni.forEach(a => { (groups[a.province] = groups[a.province] || []).push(a); });
  return (
    <div style={{ padding: "0 16px 110px" }}>
      <div style={{ position: "relative", aspectRatio: "0.78", borderRadius: 16, overflow: "hidden", background: "var(--paper)", border: "1px solid var(--border)" }}>
        <svg viewBox="0 0 100 100" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} preserveAspectRatio="none">
          <path d="M30 12 C 38 16, 50 22, 55 34 C 60 44, 62 54, 60 62 C 56 68, 50 70, 48 75" fill="oklch(0.92 0.04 80)" stroke="var(--border)" strokeWidth="0.3"/>
          <path d="M28 78 C 30 82, 34 86, 36 92 C 38 96, 44 97, 47 96" fill="oklch(0.92 0.04 80)" stroke="var(--border)" strokeWidth="0.3"/>
        </svg>
        {Object.entries(groups).map(([prov, list]) => {
          const c = provs[prov]; if (!c) return null;
          return (
            <button key={prov} onClick={() => list[0] && go("profile", list[0].id)} style={{
              position: "absolute", left: `${c[0]}%`, top: `${c[1]}%`, transform: "translate(-50%,-100%)",
              background: "var(--accent)", color: "var(--paper)", border: "2px solid var(--paper)",
              borderRadius: 999, padding: "3px 8px", fontFamily: "var(--ui)", fontSize: 11, fontWeight: 600,
              cursor: "pointer", whiteSpace: "nowrap", boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
            }}>{prov} · {list.length}</button>
          );
        })}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
        {Object.entries(groups).map(([prov, list]) => (
          <div key={prov} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 12px", borderRadius: 10, background: "var(--paper)", border: "1px solid var(--border)" }}>
            <Icon name="pin" size={14} stroke="var(--accent)"/>
            <span style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink)", flex: 1 }}>{prov}</span>
            <span style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, color: "var(--ink-muted)" }}>{list.length} คน</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 3) Profile detail
// ────────────────────────────────────────────────────────────
function ProfileScreen({ id, go, sepia, thenNow }) {
  const a     = person(id) || D().alumni[0];
  const [tab, setTab] = React.useState("about");
  const isThen = thenNow === "then";

  return (
    <div style={{ flex: 1, background: "var(--bg)", overflow: "auto" }}>
      <div style={{ position: "relative", height: 300 }}>
        <Photo hue={a.hue} sepia={sepia || isThen} kind="portrait"/>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,transparent 35%,rgba(35,28,22,0.6))" }}/>
        <button onClick={() => go("directory")} style={{
          position: "absolute", left: 14, top: safeTop(12),
          width: 38, height: 38, borderRadius: "50%",
          background: "rgba(251,247,237,0.88)", 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: safeTop(12),
          display: "flex", padding: 3, borderRadius: 999,
          background: "rgba(251,247,237,0.88)", backdropFilter: "blur(8px)", gap: 2,
        }}>
          {["now", "then"].map(k => (
            <button key={k} onClick={() => window.__setThenNow?.(k)} style={{
              padding: "5px 12px", border: 0, borderRadius: 999, cursor: "pointer",
              background: thenNow === k ? "var(--ink)" : "transparent",
              color: thenNow === k ? "var(--paper)" : "var(--ink)",
              fontFamily: "var(--ui)", fontSize: 11.5, fontWeight: 500,
            }}>{k === "now" ? "ปัจจุบัน" : "สมัยเรียน"}</button>
          ))}
        </div>
        <div style={{ position: "absolute", left: 18, bottom: 16, color: "var(--paper)" }}>
          <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, textTransform: "uppercase", opacity: 0.85 }}>
            {isThen ? a.tenure || "CL.46 · UNDERGRAD" : "CL.46 · ALUMNI"}
          </div>
          <div style={{ fontFamily: "'Newsreader', serif", fontSize: 32, lineHeight: 1.05, marginTop: 4 }}>{a.name}</div>
          <div style={{ fontFamily: "'Newsreader', serif", fontStyle: "italic", fontSize: 17, opacity: 0.9, marginTop: 2 }}>"{a.nick}"</div>
        </div>
      </div>

      <div style={{ padding: "16px 16px 120px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
          <div>
            <div style={{ fontFamily: "var(--ui)", fontSize: 14.5, color: "var(--ink)", fontWeight: 500 }}>{a.role}</div>
            <div style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-muted)", marginTop: 3 }}>{a.company}</div>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 4, marginTop: 6, fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)" }}>
              <Icon name="pin" size={13}/> {a.province}
            </div>
          </div>
          {a.verified && (
            <div style={{ display: "inline-flex", gap: 4, alignItems: "center", padding: "5px 9px", borderRadius: 6, border: "1px dashed var(--accent)", color: "var(--accent)", fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1 }}>
              <Icon name="check" size={11}/> VERIFIED
            </div>
          )}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 8, marginTop: 16 }}>
          <CTA icon="chat" label="ทักทาย" primary onClick={() => alert("ส่งข้อความผ่าน LINE")}/>
          <CTA icon="phone" label="โทร"/>
          <CTA icon="share" label="แชร์"/>
        </div>

        <div style={{
          marginTop: 16, padding: 16, borderRadius: 14,
          background: "var(--paper)", border: "1px solid var(--border)",
        }}>
          <YearStamp>What I can help</YearStamp>
          <div style={{ fontFamily: "'Newsreader', serif", fontStyle: "italic", fontSize: 17, color: "var(--ink)", marginTop: 10, lineHeight: 1.4 }}>
            "{a.helpNote}"
          </div>
          <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
            {a.help.map(h => (
              <span key={h} style={{
                fontFamily: "var(--ui)", fontSize: 12, padding: "5px 10px", borderRadius: 999,
                background: "var(--accent)", color: "var(--paper)", fontWeight: 500,
              }}>{cat(h).th}</span>
            ))}
          </div>
        </div>

        <div style={{ display: "flex", gap: 4, marginTop: 18, borderBottom: "1px solid var(--border)" }}>
          {[["about", "ข้อมูล"], ["photos", "ภาพ"], ["mutual", "เพื่อนร่วม"]].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              flex: 1, padding: "10px 6px", background: "none", border: 0, cursor: "pointer",
              fontFamily: "var(--ui)", fontSize: 13.5, fontWeight: tab === k ? 600 : 400,
              color: tab === k ? "var(--ink)" : "var(--ink-muted)",
              borderBottom: tab === k ? "2px solid var(--accent)" : "2px solid transparent",
              marginBottom: -1,
            }}>{l}</button>
          ))}
        </div>

        {tab === "about" && (
          <div style={{ marginTop: 14, borderRadius: 12, overflow: "hidden", border: "1px solid var(--border)" }}>
            <InfoRow icon="phone" label="โทร"       value="081-xxx-xxxx" private/>
            <InfoRow icon="mail"  label="อีเมล"     value={`${a.en?.toLowerCase().replace(/\W/g, "")}@example.com`}/>
            <InfoRow icon="line"  label="LINE ID"   value={`@${(a.nick || "x").toLowerCase()}46`}/>
            <InfoRow icon="pin"   label="จังหวัด"   value={a.province}/>
            <InfoRow icon="book"  label="สมัยเรียน" value={a.tenure || "—"} last/>
          </div>
        )}
        {tab === "photos" && (
          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
            {[0,1,2,3,4,5].map(i => (
              <div key={i} style={{ aspectRatio: "1", borderRadius: 8, overflow: "hidden" }}>
                <Photo hue={(a.hue + i * 40) % 360} sepia={sepia} label={`#${i+1}`}/>
              </div>
            ))}
          </div>
        )}
        {tab === "mutual" && (
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
            {D().alumni.filter(x => x.id !== a.id).slice(0, 4).map(m => (
              <div key={m.id} onClick={() => go("profile", m.id)} style={{ display: "flex", gap: 10, alignItems: "center", padding: "10px 4px", borderRadius: 10, cursor: "pointer" }}>
                <Avatar person={m} size={38} sepia={sepia}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--ui)", fontSize: 13.5, color: "var(--ink)" }}>{m.nick} · {m.name}</div>
                  <div style={{ fontFamily: "var(--ui)", fontSize: 11.5, color: "var(--ink-muted)" }}>{m.role}</div>
                </div>
                <Icon name="chev" size={16} stroke="var(--ink-muted)"/>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function CTA({ icon, label, primary, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: "11px 8px", borderRadius: 12, cursor: "pointer",
      background: primary ? "var(--ink)" : "var(--paper)",
      color: primary ? "var(--paper)" : "var(--ink)",
      border: primary ? "none" : "1px solid var(--border)",
      fontFamily: "var(--ui)", fontSize: 13, fontWeight: 500,
      display: "flex", flexDirection: "column", alignItems: "center", gap: 5,
    }}>
      <Icon name={icon} size={18}/>
      {label}
    </button>
  );
}

function InfoRow({ icon, label, value, private: priv, last }) {
  const [reveal, setReveal] = React.useState(!priv);
  return (
    <div style={{
      display: "flex", gap: 12, alignItems: "center", padding: "13px 16px",
      background: "var(--paper)", borderBottom: last ? "none" : "1px solid var(--border)",
    }}>
      <Icon name={icon} size={16} stroke="var(--ink-muted)"/>
      <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: 2, filter: reveal ? "none" : "blur(4px)", userSelect: reveal ? "auto" : "none" }}>{value}</div>
      </div>
      {priv && (
        <button onClick={() => setReveal(!reveal)} style={{ background: "none", border: 0, cursor: "pointer", padding: 4 }}>
          <Icon name={reveal ? "eye" : "eyeoff"} size={15} stroke="var(--ink-muted)"/>
        </button>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 4) Gallery
// ────────────────────────────────────────────────────────────
function GalleryScreen({ go, sepia }) {
  const d  = D();
  const [year, setYear] = React.useState("all");
  const [open, setOpen] = React.useState(null);

  const years    = ["all", ...new Set(d.gallery.map(g => g.year))].sort((a, b) => a === "all" ? -1 : b === "all" ? 1 : a - b);
  const filtered = year === "all" ? d.gallery : d.gallery.filter(g => g.year === year);
  const colA     = filtered.filter((_, i) => i % 2 === 0);
  const colB     = filtered.filter((_, i) => i % 2 === 1);

  return (
    <div style={{ flex: 1, background: "var(--bg)" }}>
      <div style={{ padding: `${safeTop(12)} 16px 0`, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 26, margin: 0 }}>คลังภาพ</h1>
          <YearStamp serial={`${filtered.length} ภาพ`}>Memory</YearStamp>
        </div>
        <div style={{ display: "flex", gap: 6, overflowX: "auto", padding: "0 0 12px", margin: "0 -16px", paddingLeft: 16, paddingRight: 16 }}>
          {years.map(y => (
            <Chip key={y} active={year === y} onClick={() => setYear(y)} size="sm">
              {y === "all" ? "ทั้งหมด" : `พ.ศ. ${y}`}
            </Chip>
          ))}
        </div>
      </div>

      <div style={{ padding: "12px 12px 110px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
        {[colA, colB].map((col, ci) => (
          <div key={ci} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {col.map(g => (
              <button key={g.id} onClick={() => setOpen(g)} style={{
                position: "relative", width: "100%", aspectRatio: `1 / ${g.h}`,
                borderRadius: 10, overflow: "hidden", padding: 0, border: 0, cursor: "pointer",
              }}>
                <Photo hue={g.hue} sepia={sepia} label={g.ph} year={g.year} kind="scene"/>
                <div style={{
                  position: "absolute", left: 7, top: 7, padding: "2px 6px",
                  background: "rgba(251,247,237,0.92)", borderRadius: 3,
                  fontFamily: "'IBM Plex Mono', monospace", fontSize: 9, color: "var(--ink)",
                }}>{g.year}</div>
              </button>
            ))}
          </div>
        ))}
      </div>

      {open && (
        <div onClick={() => setOpen(null)} style={{
          position: "absolute", inset: 0, background: "rgba(20,15,10,0.88)", zIndex: 90,
          display: "flex", flexDirection: "column", justifyContent: "center", padding: 24,
        }}>
          <div style={{ position: "absolute", top: safeTop(16), right: 20 }}>
            <Icon name="close" size={24} stroke="rgba(255,255,255,0.8)"/>
          </div>
          <div style={{ width: "100%", aspectRatio: "1", borderRadius: 12, overflow: "hidden" }}>
            <Photo hue={open.hue} sepia={sepia} label={open.ph} year={open.year} kind="scene"/>
          </div>
          <div style={{ marginTop: 18, color: "var(--paper)" }}>
            <div style={{ fontFamily: "'Newsreader', serif", fontSize: 22, fontStyle: "italic" }}>{open.caption}</div>
            <div style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1, opacity: 0.65, marginTop: 6 }}>
              พ.ศ. {open.year} · #{open.id.toUpperCase()}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 5) Me / Profile settings
// ────────────────────────────────────────────────────────────
function MeScreen({ go, sepia, palette, onPalette, onSepia }) {
  const me = RBAC_ME();
  const fallback = { phone: false, email: true, address: false };
  const [priv, setPriv] = React.useState(me.privacy || fallback);

  const handleLogout = () => {
    RBAC_LOGOUT();
    go("splash");
  };

  return (
    <div style={{ flex: 1, background: "var(--bg)" }}>
      <div style={{ padding: `${safeTop(12)} 16px 18px`, background: "var(--paper)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
          <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 26, margin: 0 }}>โปรไฟล์ของฉัน</h1>
          <button onClick={handleLogout} style={{
            padding: "6px 12px", borderRadius: 8, border: "1px solid var(--border)",
            background: "transparent", color: "var(--ink-muted)", cursor: "pointer",
            fontFamily: "var(--ui)", fontSize: 12.5,
          }}>ออกจากระบบ</button>
        </div>
        <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <Avatar person={me} size={72} sepia={sepia} ring="var(--accent)"/>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "'Newsreader', serif", fontSize: 20, color: "var(--ink)" }}>{me.name}</div>
            <div style={{ fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)", marginTop: 3 }}>{me.role} · {me.company}</div>
            <button onClick={() => go("profile", me.id)} style={{
              marginTop: 8, padding: "5px 11px", borderRadius: 999, border: "1px solid var(--border)",
              background: "var(--bg)", cursor: "pointer", fontFamily: "var(--ui)", fontSize: 11.5,
              display: "inline-flex", alignItems: "center", gap: 5, color: "var(--ink)",
            }}>
              <Icon name="eye" size={11}/> ดูโปรไฟล์
            </button>
          </div>
        </div>
      </div>

      {/* Help note */}
      {me.help?.length > 0 && (
        <Section title="What I can help with">
          <div style={{ padding: 14, borderRadius: 14, background: "var(--paper)", border: "1px dashed var(--accent)" }}>
            <div style={{ fontFamily: "'Newsreader', serif", fontStyle: "italic", fontSize: 15.5, color: "var(--ink)", lineHeight: 1.45 }}>
              "{me.helpNote || "—"}"
            </div>
            <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
              {me.help.map(h => (
                <span key={h} style={{ padding: "4px 10px", borderRadius: 999, background: "var(--accent)", color: "var(--paper)", fontFamily: "var(--ui)", fontSize: 12 }}>
                  {cat(h)?.th}
                </span>
              ))}
            </div>
          </div>
        </Section>
      )}

      {/* Privacy toggles */}
      <Section title="ความเป็นส่วนตัว">
        <div style={{ borderRadius: 14, overflow: "hidden", border: "1px solid var(--border)" }}>
          {[
            ["phone",   "เบอร์โทรศัพท์", me.phone   || "081-xxx-xxxx"],
            ["email",   "อีเมล",          me.email   || `${(me.nick||"x").toLowerCase()}@rbac.local`],
            ["address", "จังหวัด",        me.province],
          ].map(([k, l, v], i, arr) => (
            <div key={k} style={{
              display: "flex", alignItems: "center", padding: "13px 16px", background: "var(--paper)",
              borderBottom: i < arr.length - 1 ? "1px solid var(--border)" : "none",
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: "var(--ui)", fontSize: 13.5, color: "var(--ink)" }}>{l}</div>
                <div style={{ fontFamily: "var(--ui)", fontSize: 12, color: "var(--ink-muted)", marginTop: 2 }}>
                  {priv[k] ? "เห็นเฉพาะเพื่อนที่ Verify แล้ว" : v}
                </div>
              </div>
              <Toggle on={!priv[k]} onChange={() => setPriv(p => ({ ...p, [k]: !p[k] }))}/>
            </div>
          ))}
        </div>
      </Section>

      {/* Theme */}
      <Section title="ธีมสี">
        <div style={{ display: "flex", gap: 10 }}>
          {[["#1f3a8a", "น้ำเงินทอง"], ["#b94a2c", "ดินเผา"], ["#2f5d3a", "เขียวงาช้าง"]].map(([p, l]) => (
            <button key={p} onClick={() => onPalette(p)} style={{
              flex: 1, height: 48, borderRadius: 12, border: `2px solid ${palette === p ? "var(--ink)" : "transparent"}`,
              background: p, cursor: "pointer", display: "flex", alignItems: "flex-end",
              padding: "6px 8px", transition: "border-color .2s",
            }}>
              <span style={{ fontFamily: "var(--ui)", fontSize: 11, color: "rgba(255,255,255,0.9)", fontWeight: 600 }}>{l}</span>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10, padding: "12px 16px", borderRadius: 12, background: "var(--paper)", border: "1px solid var(--border)" }}>
          <span style={{ fontFamily: "var(--ui)", fontSize: 13.5, color: "var(--ink)" }}>ฟิลเตอร์เซเปีย</span>
          <Toggle on={sepia} onChange={() => onSepia(v => !v)}/>
        </div>
      </Section>

      <div style={{ padding: "24px 16px", textAlign: "center", fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, color: "var(--ink-muted)", letterSpacing: 1.2 }}>
        RBAC ALUMNI · CL.46 · v1.1
      </div>
      <div style={{ height: 60 }}/>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={onChange} style={{
      width: 44, height: 26, borderRadius: 999, border: 0, padding: 3, cursor: "pointer",
      background: on ? "var(--accent)" : "var(--border)", transition: "background .2s", flexShrink: 0,
    }}>
      <div style={{
        width: 20, height: 20, borderRadius: "50%", background: "var(--paper)",
        transform: on ? "translateX(18px)" : "translateX(0)",
        transition: "transform .2s", boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
      }}/>
    </button>
  );
}

// ────────────────────────────────────────────────────────────
// 6) Compose
// ────────────────────────────────────────────────────────────
function ComposeScreen({ go }) {
  const [title,   setTitle]   = React.useState("");
  const [body,    setBody]    = React.useState("");
  const [cats,    setCats]    = React.useState([]);
  const [sending, setSending] = React.useState(false);
  const [sent,    setSent]    = React.useState(false);
  const toggle = (id) => setCats(c => c.includes(id) ? c.filter(x => x !== id) : [...c, id]);

  const handleSend = async () => {
    if (!title || !body || sending) return;
    setSending(true);
    const result = await RBAC_API.postBroadcast({ title, body, kind: "help" });
    setSending(false);
    if (result) {
      setSent(true);
      setTimeout(() => go("home"), 1400);
    } else {
      alert("ส่งไม่สำเร็จ — กรุณาลองใหม่");
    }
  };

  if (sent) {
    return (
      <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14, background: "var(--bg)" }}>
        <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--accent-tint)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="check" size={32} stroke="var(--accent)"/>
        </div>
        <div style={{ fontFamily: "'Newsreader', serif", fontSize: 24, color: "var(--ink)" }}>ส่งแล้ว!</div>
        <div style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-muted)" }}>กำลังกลับสู่หน้าหลัก…</div>
      </div>
    );
  }

  return (
    <div style={{ flex: 1, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <div style={{
        padding: `${safeTop(12)} 16px 14px`,
        display: "flex", alignItems: "center", gap: 10,
        background: "var(--paper)", borderBottom: "1px solid var(--border)",
      }}>
        <button onClick={() => go("home")} style={{ background: "none", border: 0, cursor: "pointer", padding: 4 }}>
          <Icon name="close" size={22}/>
        </button>
        <h1 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 20, margin: 0, flex: 1 }}>ขอความช่วยเหลือ</h1>
        <button disabled={!title || !body || sending} onClick={handleSend} style={{
          padding: "8px 16px", borderRadius: 999, border: 0,
          cursor: title && body && !sending ? "pointer" : "default",
          background: title && body && !sending ? "var(--accent)" : "var(--border)",
          color: title && body && !sending ? "var(--paper)" : "var(--ink-muted)",
          fontFamily: "var(--ui)", fontSize: 13.5, fontWeight: 600,
        }}>{sending ? "กำลังส่ง…" : "ส่ง"}</button>
      </div>

      <div style={{ flex: 1, padding: 16, overflowY: "auto" }}>
        <label style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1.5, color: "var(--ink-muted)", textTransform: "uppercase" }}>
          เรื่องที่ต้องการ
        </label>
        <input
          value={title} onChange={e => setTitle(e.target.value)}
          placeholder="เช่น ตามหาทนายที่เชี่ยวชาญสัญญา"
          style={{
            display: "block", width: "100%", marginTop: 8, padding: "14px 16px", borderRadius: 12,
            border: "1px solid var(--border)", background: "var(--paper)",
            fontFamily: "'Newsreader', serif", fontSize: 18, color: "var(--ink)", outline: "none",
          }}
        />
        <textarea
          value={body} onChange={e => setBody(e.target.value)}
          placeholder="อธิบายรายละเอียดเพิ่มเติม…" rows={5}
          style={{
            display: "block", width: "100%", marginTop: 10, padding: "14px 16px", borderRadius: 12,
            border: "1px solid var(--border)", background: "var(--paper)",
            fontFamily: "var(--ui)", fontSize: 14, color: "var(--ink)", outline: "none", resize: "none",
          }}
        />

        <label style={{ display: "block", fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: 1.5, color: "var(--ink-muted)", textTransform: "uppercase", marginTop: 20, marginBottom: 10 }}>
          จะแจ้งเตือนเพื่อนในหมวด
        </label>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {D().helpCategories.map(c => (
            <Chip key={c.id} active={cats.includes(c.id)} onClick={() => toggle(c.id)} count={c.count} size="sm">
              {c.th}
            </Chip>
          ))}
        </div>

        <div style={{ marginTop: 20, padding: 14, borderRadius: 12, background: "var(--paper)", border: "1px solid var(--border)", display: "flex", gap: 10 }}>
          <Icon name="lock" size={16} stroke="var(--accent)"/>
          <div style={{ fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--ink-muted)", lineHeight: 1.55 }}>
            ส่งเฉพาะเพื่อนรุ่นเท่านั้น — ประมาณ <b style={{ color: "var(--ink)" }}>
              {cats.reduce((s, id) => s + (cat(id)?.count || 0), 0) || "—"}
            </b> คน
          </div>
        </div>
        <div style={{ height: 60 }}/>
      </div>
    </div>
  );
}

Object.assign(window, {
  SplashScreen, HomeScreen, DirectoryScreen, ProfileScreen,
  GalleryScreen, MeScreen, ComposeScreen, Section,
});
