// people-profile.jsx — Employee profile page, gifts admin, birthdays.
//
// Exposes (on window):
//   PpProfile          — the attractive profile page (self or, for an
//                        owner/admin, anyone). canEdit comes from the API.
//   PpProfileModal     — owner wrapper that opens a profile over a dim.
//   PpGiftsAdmin       — owner gift-type CRUD (the People → Gifts tab).
//   PpBirthdayHost     — global confetti + banner on the user's birthday.
//   PpSidebarBirthdays — compact "Birthdays today / upcoming" sidebar card.
//
// All data via /api/people/profile/full, /benefits, /gifts/*, /birthdays.

(function () {
  if (typeof window === "undefined") return;
  const R = window.React;
  if (!R) return;

  function cls(...a) { return a.filter(Boolean).join(" "); }
  function ordinal(n) {
    const v = Number(n) || 0; const s = ["th", "st", "nd", "rd"], m = v % 100;
    return v + (s[(m - 20) % 10] || s[m] || s[0]);
  }
  function fmtDate(iso) {
    if (!iso) return "—";
    const d = new Date(String(iso).slice(0, 10) + "T00:00:00");
    if (isNaN(d.getTime())) return iso;
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  }
  function avatarOf(p) {
    if (window.PpAvatar) return R.createElement(window.PpAvatar, { person: p, size: "lg" });
    return null;
  }

  // ── confetti ──────────────────────────────────────────────
  function fireConfetti() {
    try {
      const cv = document.createElement("canvas");
      cv.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:99999";
      cv.width = window.innerWidth; cv.height = window.innerHeight;
      document.body.appendChild(cv);
      const ctx = cv.getContext("2d");
      const colors = ["#ff6b6b", "#ffd93d", "#6bcB77", "#4d96ff", "#c77dff", "#ff9f1c"];
      const parts = [];
      for (let i = 0; i < 150; i++) parts.push({
        x: Math.random() * cv.width, y: -20 - Math.random() * cv.height * 0.4,
        r: 6 + Math.random() * 7, c: colors[i % colors.length],
        vy: 2 + Math.random() * 4, vx: -2.5 + Math.random() * 5,
        rot: Math.random() * 6, vr: -0.25 + Math.random() * 0.5,
      });
      const t0 = performance.now();
      function frame(t) {
        ctx.clearRect(0, 0, cv.width, cv.height);
        parts.forEach(p => {
          p.x += p.vx; p.y += p.vy; p.vy += 0.05; p.rot += p.vr;
          ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.rot);
          ctx.fillStyle = p.c; ctx.fillRect(-p.r / 2, -p.r / 2, p.r, p.r * 0.6); ctx.restore();
        });
        if (t - t0 < 5000) requestAnimationFrame(frame); else cv.remove();
      }
      requestAnimationFrame(frame);
    } catch {}
  }

  function userId() {
    try { const u = window.api && window.api.getUser && window.api.getUser(); return (u && u.id) || null; } catch { return null; }
  }

  // ════════════════════════════════════════════════════════════
  //  PpProfile
  // ════════════════════════════════════════════════════════════
  function PpProfile({ userId: targetId, onClose }) {
    const [data, setData] = R.useState(null);
    const [loading, setLoading] = R.useState(true);
    const [editDetails, setEditDetails] = R.useState(false);
    const [editIns, setEditIns] = R.useState(false);
    const [giving, setGiving] = R.useState(false);

    const reload = R.useCallback(async () => {
      setLoading(true);
      try { setData(await window.api.people.profileFull(targetId ? { userId: targetId } : {})); }
      catch (e) { setData({ error: (e && e.body && e.body.message) || "Couldn't load profile" }); }
      setLoading(false);
    }, [targetId]);
    R.useEffect(() => { reload(); }, [reload]);

    if (loading) return R.createElement("div", { className: "pp-card", style: { padding: 24, color: "var(--ink-muted)" } }, "Loading profile…");
    if (!data || data.error) return R.createElement("div", { className: "pp-card", style: { padding: 24, color: "var(--ink-muted)" } }, (data && data.error) || "No profile.");

    const u = data.user, p = data.profile, ins = data.insurance || {}, g = data.gifts || {};
    const canEdit = !!data.canEdit;

    const insEl = data.insuranceEligible || { eligible: false };
    const initials = (u.name || "?").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

    function fact(label, value) {
      return R.createElement("div", { className: "pp-pf-fact", key: label },
        R.createElement("div", { className: "pp-pf-fact-l" }, label),
        R.createElement("div", { className: "pp-pf-fact-v" }, value || "—"));
    }

    // header chips
    const chips = [];
    if (p.employee_code) chips.push(R.createElement("span", { key: "code", className: "pp-pf-chip pp-pf-chip-code" }, p.employee_code));
    if (ins.insured) chips.push(R.createElement("span", { key: "ins", className: "pp-pf-chip pp-pf-chip-ins" },
      R.createElement(window.PpIcon, { name: "Heart", size: 12, key: "i" }), " Insured"));
    else if (insEl.eligible) chips.push(R.createElement("span", { key: "insE", className: "pp-pf-chip pp-pf-chip-warn" }, "Insurance eligible"));
    if (data.isBirthdayToday) chips.push(R.createElement("span", { key: "bd", className: "pp-pf-chip pp-pf-chip-bday" }, "🎂 Birthday"));
    if (p.employee_status) chips.push(R.createElement("span", { key: "st", className: "pp-pf-chip pp-pf-chip-muted" }, p.employee_status));

    // insurance card body
    let insBody;
    if (editIns) {
      insBody = R.createElement(InsuranceForm, { key: "f", userId: u.id,
        insurance: editIns === "enroll" ? { ...ins, insured: true } : ins,
        onDone: () => { setEditIns(false); reload(); } });
    } else if (ins.insured) {
      insBody = R.createElement("div", { key: "v" }, [
        R.createElement("span", { className: "pp-pf-ins-pill", key: "b" }, [
          R.createElement(window.PpIcon, { name: "Heart", size: 13, key: "i" }), " Covered"]),
        R.createElement("div", { className: "pp-pf-rows", key: "f", style: { marginTop: 12 } }, [
          fact("Provider", ins.provider),
          fact("Policy no.", ins.policy_no),
          fact("Valid till", ins.valid_till ? fmtDate(ins.valid_till) : null),
        ]),
      ]);
    } else if (insEl.eligible) {
      insBody = R.createElement("div", { className: "pp-pf-ins-elig", key: "e" }, [
        R.createElement("div", { className: "pp-pf-ins-elig-txt", key: "t" }, [
          R.createElement("div", { className: "pp-pf-ins-elig-h", key: "h" }, "Eligible for insurance"),
          R.createElement("div", { className: "pp-pf-ins-elig-s", key: "s" },
            `${insEl.months} months completed (threshold ${insEl.threshold})`),
        ]),
        canEdit
          ? R.createElement("button", { className: "pp-btn pp-btn-primary", key: "b", onClick: () => setEditIns("enroll") }, "Enroll")
          : R.createElement("span", { className: "pp-pf-chip pp-pf-chip-warn", key: "p" }, "Pending HR"),
      ]);
    } else {
      insBody = R.createElement("div", { className: "pp-pf-muted", key: "n" },
        insEl.months != null ? `Not enrolled · ${insEl.months}/${insEl.threshold} months` : "Not enrolled.");
    }

    return R.createElement("div", { className: "pp-pf" }, [
      // Header card
      R.createElement("div", { className: "pp-pf-head", key: "head" }, [
        R.createElement("div", { className: "pp-pf-accent", key: "ac" }),
        onClose && R.createElement("button", { className: "pp-pf-close", onClick: onClose, key: "x", title: "Close" }, "×"),
        R.createElement("div", { className: "pp-pf-head-row", key: "row" }, [
          (u.avatar
            ? R.createElement("img", { className: "pp-pf-av", src: u.avatar, alt: u.name, key: "av" })
            : R.createElement("div", { className: "pp-pf-av pp-pf-av-ini", key: "av" }, initials)),
          R.createElement("div", { className: "pp-pf-id", key: "id" }, [
            R.createElement("div", { className: "pp-pf-name", key: "n" }, u.name),
            R.createElement("div", { className: "pp-pf-role", key: "r" },
              [p.designation, p.department].filter(Boolean).join(" · ") || "Employee"),
            R.createElement("div", { className: "pp-pf-chips", key: "c" }, chips),
          ]),
          R.createElement("div", { className: "pp-pf-stats", key: "st" }, [
            data.tenure && R.createElement("div", { className: "pp-pf-stat", key: "t" }, [
              R.createElement("div", { className: "pp-pf-stat-l", key: "l" }, "Tenure"),
              R.createElement("div", { className: "pp-pf-stat-v", key: "v" }, data.tenure.label)]),
            p.date_of_joining && R.createElement("div", { className: "pp-pf-stat", key: "j" }, [
              R.createElement("div", { className: "pp-pf-stat-l", key: "l" }, "Joined"),
              R.createElement("div", { className: "pp-pf-stat-v", key: "v" }, fmtDate(p.date_of_joining))]),
            canEdit && R.createElement("button", { className: "pp-btn", key: "e", onClick: () => setEditDetails(v => !v) },
              editDetails ? "Cancel" : "Edit"),
          ]),
        ]),
      ]),

      // Body grid
      R.createElement("div", { className: "pp-pf-grid", key: "grid" }, [
        // Left — details + about
        R.createElement("div", { className: "pp-pf-col", key: "left" }, [
          R.createElement("div", { className: "pp-card pp-pf-card", key: "facts" }, [
            R.createElement("div", { className: "pp-pf-card-title", key: "t" }, "Details"),
            editDetails
              ? R.createElement(DetailsForm, { key: "f", userId: u.id, profile: p, onDone: () => { setEditDetails(false); reload(); } })
              : R.createElement("div", { className: "pp-pf-rows", key: "g" }, [
                  fact("Email", u.email),
                  fact("Mobile", p.personal_mobile || p.work_phone),
                  fact("Date of birth", p.date_of_birth ? fmtDate(p.date_of_birth) : null),
                  fact("Reporting to", p.reporting_manager),
                  fact("Team", p.team),
                  fact("Employment", p.employment_type),
                  fact("Gender", p.gender),
                  fact("Seating", p.seating_location),
                ]),
            (p.about_me && !editDetails) && R.createElement("div", { className: "pp-pf-about-wrap", key: "ab" }, [
              R.createElement("div", { className: "pp-pf-rowlabel", key: "l" }, "About"),
              R.createElement("div", { className: "pp-pf-about", key: "a" }, p.about_me),
            ]),
          ]),
        ]),

        // Right — insurance + gifts
        R.createElement("div", { className: "pp-pf-col", key: "right" }, [
          R.createElement("div", { className: "pp-card pp-pf-card", key: "ins" }, [
            R.createElement("div", { className: "pp-pf-card-head", key: "h" }, [
              R.createElement("div", { className: "pp-pf-card-title", key: "t", style: { margin: 0 } }, "Insurance"),
              canEdit && ins.insured && R.createElement("button", { className: "pp-pf-link", key: "e", onClick: () => setEditIns(editIns ? false : "edit") }, editIns ? "Cancel" : "Edit"),
              canEdit && !ins.insured && editIns && R.createElement("button", { className: "pp-pf-link", key: "c", onClick: () => setEditIns(false) }, "Cancel"),
            ]),
            insBody,
          ]),

          R.createElement("div", { className: "pp-card pp-pf-card", key: "gifts" }, [
            R.createElement("div", { className: "pp-pf-card-head", key: "h" }, [
              R.createElement("div", { className: "pp-pf-card-title", key: "t", style: { margin: 0 } }, "Gifts & rewards"),
              canEdit && R.createElement("button", { className: "pp-pf-link", key: "give", onClick: () => setGiving(true) }, "+ Give"),
            ]),
            (g.eligible && g.eligible.length > 0) && R.createElement("div", { key: "el" }, [
              R.createElement("div", { className: "pp-pf-sub", key: "s" }, "Eligible now"),
              ...g.eligible.map((e, i) => R.createElement("div", { className: "pp-pf-gift pp-pf-gift-elig", key: i }, [
                R.createElement("span", { className: "pp-pf-gift-emoji", key: "e" }, e.emoji || "🎁"),
                R.createElement("div", { className: "pp-pf-gift-txt", key: "t" }, [
                  R.createElement("div", { className: "pp-pf-gift-title", key: "n" }, e.name),
                  R.createElement("div", { className: "pp-pf-gift-occ", key: "o" }, e.occasion)]),
                canEdit
                  ? R.createElement("button", { className: "pp-btn pp-btn-primary", key: "b", onClick: () => giveQuick(u.id, e, reload) }, "Give")
                  : R.createElement("span", { className: "pp-pf-gift-tag", key: "tg" }, "Earned"),
              ])),
            ]),
            R.createElement("div", { key: "rc" }, [
              R.createElement("div", { className: "pp-pf-sub", key: "s" }, `Received (${(g.received || []).length})`),
              (g.received && g.received.length)
                ? g.received.map((it, i) => R.createElement("div", { className: "pp-pf-gift", key: i }, [
                    R.createElement("span", { className: "pp-pf-gift-emoji pp-pf-gift-token", key: "e" }, it.emoji || "🎁"),
                    R.createElement("div", { className: "pp-pf-gift-txt", key: "t" }, [
                      R.createElement("div", { className: "pp-pf-gift-title", key: "n" }, it.title),
                      R.createElement("div", { className: "pp-pf-gift-occ", key: "o" },
                        [it.occasion, it.awarded_at ? fmtDate(it.awarded_at) : null].filter(Boolean).join(" · "))]),
                    canEdit && R.createElement("button", { className: "pp-pf-x", key: "d", title: "Remove", onClick: () => removeGift(it.id, reload) }, "×"),
                  ]))
                : R.createElement("div", { className: "pp-pf-muted", key: "z" }, "No gifts yet."),
            ]),
          ]),
        ]),
      ]),

      giving && R.createElement(GiveGiftModal, { key: "gm", userId: u.id, catalog: g.catalog || [],
        onClose: () => setGiving(false), onDone: () => { setGiving(false); reload(); } }),
    ]);
  }

  async function giveQuick(uid, elig, reload) {
    try {
      await window.api.people.awardGift({ user_id: uid, gift_type_id: elig.gift_type_id, occasion: elig.occasion });
      if (window.fbToast) window.fbToast("Gift given 🎁", 2200);
      reload();
    } catch (e) { if (window.fbToast) window.fbToast("Couldn't give gift", 3000); }
  }
  async function removeGift(id, reload) {
    if (!window.confirm("Remove this gift record?")) return;
    try { await window.api.people.unawardGift(id); reload(); } catch {}
  }

  // ── details edit form ─────────────────────────────────────
  function DetailsForm({ userId: uid, profile, onDone }) {
    const [f, setF] = R.useState({
      designation: profile.designation || "", department: profile.department || "",
      date_of_joining: profile.date_of_joining || "", date_of_birth: profile.date_of_birth || "",
      gender: profile.gender || "", reporting_manager: profile.reporting_manager || "",
      employment_type: profile.employment_type || "", work_phone: profile.work_phone || "",
      personal_mobile: profile.personal_mobile || "", personal_email: profile.personal_email || "",
      seating_location: profile.seating_location || "", marital_status: profile.marital_status || "",
      present_address: profile.present_address || "", about_me: profile.about_me || "",
      employee_code: profile.employee_code || "",
    });
    const [saving, setSaving] = R.useState(false);
    function set(k, v) { setF(s => ({ ...s, [k]: v })); }
    async function save() {
      setSaving(true);
      try { await window.api.people.setProfileDetails({ user_id: uid, ...f }); if (window.fbToast) window.fbToast("Profile updated", 2000); onDone(); }
      catch (e) { if (window.fbToast) window.fbToast("Couldn't save", 3000); setSaving(false); }
    }
    const field = (label, k, type) => R.createElement("label", { className: "pp-pf-ff", key: k }, [
      R.createElement("span", { key: "l" }, label),
      type === "textarea"
        ? R.createElement("textarea", { key: "i", rows: 3, value: f[k], onChange: e => set(k, e.target.value) })
        : R.createElement("input", { key: "i", type: type || "text", value: f[k], onChange: e => set(k, e.target.value) }),
    ]);
    return R.createElement("div", { className: "pp-pf-form" }, [
      R.createElement("div", { className: "pp-pf-form-grid", key: "g" }, [
        field("Designation", "designation"),
        field("Department", "department"),
        field("Date of joining", "date_of_joining", "date"),
        field("Date of birth", "date_of_birth", "date"),
        field("Gender", "gender"),
        field("Employment type", "employment_type"),
        field("Reporting manager", "reporting_manager"),
        field("Employee code", "employee_code"),
        field("Work phone", "work_phone"),
        field("Personal mobile", "personal_mobile"),
        field("Personal email", "personal_email", "email"),
        field("Seating", "seating_location"),
        field("Marital status", "marital_status"),
        field("Present address", "present_address"),
      ]),
      field("About", "about_me", "textarea"),
      R.createElement("div", { className: "pp-pf-form-actions", key: "a" },
        R.createElement("button", { className: "pp-btn pp-btn-primary", onClick: save, disabled: saving }, saving ? "Saving…" : "Save details")),
    ]);
  }

  // ── insurance edit form ───────────────────────────────────
  function InsuranceForm({ userId: uid, insurance, onDone }) {
    const [f, setF] = R.useState({
      insured: !!insurance.insured, provider: insurance.provider || "",
      policy_no: insurance.policy_no || "", valid_till: insurance.valid_till || "", note: insurance.note || "",
    });
    const [saving, setSaving] = R.useState(false);
    function set(k, v) { setF(s => ({ ...s, [k]: v })); }
    async function save() {
      setSaving(true);
      try { await window.api.people.setBenefits({ user_id: uid, ...f }); if (window.fbToast) window.fbToast("Insurance updated", 2000); onDone(); }
      catch (e) { if (window.fbToast) window.fbToast("Couldn't save", 3000); setSaving(false); }
    }
    return R.createElement("div", { className: "pp-pf-form" }, [
      R.createElement("label", { className: "pp-pf-check", key: "c" }, [
        R.createElement("input", { type: "checkbox", checked: f.insured, onChange: e => set("insured", e.target.checked), key: "i" }),
        R.createElement("span", { key: "s" }, "Enrolled / covered"),
      ]),
      R.createElement("div", { className: "pp-pf-form-grid", key: "g" }, [
        R.createElement("label", { className: "pp-pf-ff", key: "p" }, [R.createElement("span", { key: "l" }, "Provider"),
          R.createElement("input", { key: "i", value: f.provider, onChange: e => set("provider", e.target.value) })]),
        R.createElement("label", { className: "pp-pf-ff", key: "n" }, [R.createElement("span", { key: "l" }, "Policy no."),
          R.createElement("input", { key: "i", value: f.policy_no, onChange: e => set("policy_no", e.target.value) })]),
        R.createElement("label", { className: "pp-pf-ff", key: "v" }, [R.createElement("span", { key: "l" }, "Valid till"),
          R.createElement("input", { key: "i", type: "date", value: f.valid_till || "", onChange: e => set("valid_till", e.target.value) })]),
      ]),
      R.createElement("div", { className: "pp-pf-form-actions", key: "a" },
        R.createElement("button", { className: "pp-btn pp-btn-primary", onClick: save, disabled: saving }, saving ? "Saving…" : "Save insurance")),
    ]);
  }

  // ── give-a-gift modal ─────────────────────────────────────
  function GiveGiftModal({ userId: uid, catalog, onClose, onDone }) {
    const [typeId, setTypeId] = R.useState("");
    const [title, setTitle] = R.useState("");
    const [emoji, setEmoji] = R.useState("🎁");
    const [occasion, setOccasion] = R.useState("");
    const [note, setNote] = R.useState("");
    const [saving, setSaving] = R.useState(false);
    async function give() {
      if (!typeId && !title.trim()) { if (window.fbToast) window.fbToast("Pick a gift or enter a title", 2500); return; }
      setSaving(true);
      try {
        await window.api.people.awardGift({ user_id: uid, gift_type_id: typeId || null,
          title: typeId ? null : title.trim(), emoji, occasion: occasion || null, note: note || null });
        if (window.fbToast) window.fbToast("Gift given 🎁", 2200);
        onDone();
      } catch (e) { if (window.fbToast) window.fbToast("Couldn't give gift", 3000); setSaving(false); }
    }
    const overlay = R.createElement("div", { className: "pp-pf-modal-ov", onMouseDown: onClose },
      R.createElement("div", { className: "pp-pf-modal", onMouseDown: e => e.stopPropagation() }, [
        R.createElement("div", { className: "pp-pf-modal-h", key: "h" }, "Give a gift"),
        R.createElement("label", { className: "pp-pf-ff", key: "t" }, [R.createElement("span", { key: "l" }, "From catalog"),
          R.createElement("select", { key: "s", value: typeId, onChange: e => setTypeId(e.target.value) },
            [R.createElement("option", { value: "", key: "0" }, "— custom gift —"),
             ...catalog.map(c => R.createElement("option", { value: c.id, key: c.id }, `${c.emoji || "🎁"} ${c.name}`))])]),
        !typeId && R.createElement("div", { className: "pp-pf-form-grid", key: "cu" }, [
          R.createElement("label", { className: "pp-pf-ff", key: "ti" }, [R.createElement("span", { key: "l" }, "Title"),
            R.createElement("input", { key: "i", value: title, onChange: e => setTitle(e.target.value), placeholder: "e.g. Festival hamper" })]),
          R.createElement("label", { className: "pp-pf-ff", key: "em" }, [R.createElement("span", { key: "l" }, "Emoji"),
            R.createElement("input", { key: "i", value: emoji, onChange: e => setEmoji(e.target.value), maxLength: 4 })]),
        ]),
        R.createElement("label", { className: "pp-pf-ff", key: "oc" }, [R.createElement("span", { key: "l" }, "Occasion"),
          R.createElement("input", { key: "i", value: occasion, onChange: e => setOccasion(e.target.value), placeholder: "e.g. 3-year anniversary" })]),
        R.createElement("label", { className: "pp-pf-ff", key: "no" }, [R.createElement("span", { key: "l" }, "Note (optional)"),
          R.createElement("input", { key: "i", value: note, onChange: e => setNote(e.target.value) })]),
        R.createElement("div", { className: "pp-pf-form-actions", key: "a" }, [
          R.createElement("button", { className: "pp-btn", key: "c", onClick: onClose }, "Cancel"),
          R.createElement("button", { className: "pp-btn pp-btn-primary", key: "g", onClick: give, disabled: saving }, saving ? "Giving…" : "Give gift"),
        ]),
      ]));
    return (window.ReactDOM && window.ReactDOM.createPortal) ? window.ReactDOM.createPortal(overlay, document.body) : overlay;
  }

  // ── manager: profile modal ────────────────────────────────
  function PpProfileModal({ userId: uid, onClose }) {
    const overlay = R.createElement("div", { className: "pp-pf-modal-ov pp-pf-modal-ov-wide", onMouseDown: onClose },
      R.createElement("div", { className: "pp-pf-modal-wide", onMouseDown: e => e.stopPropagation() },
        R.createElement(PpProfile, { userId: uid, onClose })));
    return (window.ReactDOM && window.ReactDOM.createPortal) ? window.ReactDOM.createPortal(overlay, document.body) : overlay;
  }

  // ════════════════════════════════════════════════════════════
  //  PpGiftsAdmin — owner gift-type catalog
  // ════════════════════════════════════════════════════════════
  function PpGiftsAdmin() {
    const [items, setItems] = R.useState(null);
    const [adding, setAdding] = R.useState(false);
    const reload = R.useCallback(async () => {
      try { const r = await window.api.people.giftTypes(); setItems(r.items || []); } catch { setItems([]); }
    }, []);
    R.useEffect(() => { reload(); }, [reload]);
    if (items === null) return R.createElement("div", { className: "pp-card", style: { padding: 22, color: "var(--ink-muted)" } }, "Loading gifts…");
    const kindLabel = { anniversary: "Work anniversary", birthday: "Birthday", tenure: "Tenure", manual: "Manual / anytime" };
    return R.createElement("div", { className: "pp-gifts" }, [
      R.createElement("div", { className: "pp-card pp-pf-sec", key: "head" }, [
        R.createElement("div", { className: "pp-pf-sec-head", key: "h" }, [
          R.createElement("div", { key: "t" }, [
            R.createElement("div", { className: "pp-card-title", key: "a" }, "Gift catalog"),
            R.createElement("div", { className: "pp-card-sub", key: "b" }, "Define the gifts you give. Anniversary / birthday / tenure gifts auto-flag eligible people on their profile."),
          ]),
          R.createElement("button", { className: "pp-btn pp-btn-primary", key: "add", onClick: () => setAdding(true) }, "+ New gift"),
        ]),
      ]),
      adding && R.createElement(GiftTypeForm, { key: "form", onClose: () => setAdding(false), onDone: () => { setAdding(false); reload(); } }),
      R.createElement("div", { className: "pp-gifts-list", key: "list" }, items.map(t =>
        R.createElement("div", { className: cls("pp-gift-row", !Number(t.active) && "is-archived"), key: t.id }, [
          R.createElement("span", { className: "pp-gift-emoji", key: "e" }, t.emoji || "🎁"),
          R.createElement("div", { className: "pp-gift-meta", key: "m" }, [
            R.createElement("div", { className: "pp-gift-name", key: "n" }, t.name),
            R.createElement("div", { className: "pp-gift-rule", key: "r" },
              kindLabel[t.trigger_kind] + (t.trigger_value ? ` · ${t.trigger_value}${t.trigger_kind === "anniversary" ? " yr" : t.trigger_kind === "tenure" ? " mo" : ""}` : "")
              + (t.description ? " — " + t.description : "")),
          ]),
          Number(t.active)
            ? R.createElement("button", { className: "pp-btn", key: "d", onClick: () => archive(t.id, reload) }, "Archive")
            : R.createElement("span", { className: "pp-pf-gift-tag", key: "z" }, "Archived"),
        ]))),
      items.length === 0 && R.createElement("div", { className: "pp-pf-ins-no", key: "empty", style: { padding: 16 } }, "No gifts yet — add your first one."),
    ]);
  }
  async function archive(id, reload) {
    if (!window.confirm("Archive this gift type? Past gifts stay on record.")) return;
    try { await window.api.people.deleteGiftType(id); reload(); } catch {}
  }
  function GiftTypeForm({ onClose, onDone }) {
    const [f, setF] = R.useState({ name: "", emoji: "🎁", description: "", trigger_kind: "anniversary", trigger_value: 1, color: "#0073ea" });
    const [saving, setSaving] = R.useState(false);
    function set(k, v) { setF(s => ({ ...s, [k]: v })); }
    async function save() {
      if (!f.name.trim()) { if (window.fbToast) window.fbToast("Name required", 2000); return; }
      setSaving(true);
      try { await window.api.people.createGiftType(f); onDone(); }
      catch (e) { if (window.fbToast) window.fbToast("Couldn't save", 3000); setSaving(false); }
    }
    const needsValue = f.trigger_kind === "anniversary" || f.trigger_kind === "tenure";
    return R.createElement("div", { className: "pp-card pp-pf-sec pp-gift-form" }, [
      R.createElement("div", { className: "pp-pf-form-grid", key: "g" }, [
        R.createElement("label", { className: "pp-pf-ff", key: "n" }, [R.createElement("span", { key: "l" }, "Gift name"),
          R.createElement("input", { key: "i", value: f.name, onChange: e => set("name", e.target.value), placeholder: "e.g. 5-year reward" })]),
        R.createElement("label", { className: "pp-pf-ff", key: "e" }, [R.createElement("span", { key: "l" }, "Emoji"),
          R.createElement("input", { key: "i", value: f.emoji, onChange: e => set("emoji", e.target.value), maxLength: 4 })]),
        R.createElement("label", { className: "pp-pf-ff", key: "k" }, [R.createElement("span", { key: "l" }, "Trigger"),
          R.createElement("select", { key: "i", value: f.trigger_kind, onChange: e => set("trigger_kind", e.target.value) },
            [R.createElement("option", { value: "anniversary", key: "a" }, "Work anniversary (years)"),
             R.createElement("option", { value: "birthday", key: "b" }, "Birthday"),
             R.createElement("option", { value: "tenure", key: "t" }, "Tenure (months)"),
             R.createElement("option", { value: "manual", key: "m" }, "Manual / anytime")])]),
        needsValue && R.createElement("label", { className: "pp-pf-ff", key: "v" }, [
          R.createElement("span", { key: "l" }, f.trigger_kind === "anniversary" ? "Years" : "Months"),
          R.createElement("input", { key: "i", type: "number", min: 1, value: f.trigger_value, onChange: e => set("trigger_value", e.target.value) })]),
        R.createElement("label", { className: "pp-pf-ff", key: "d" }, [R.createElement("span", { key: "l" }, "Description"),
          R.createElement("input", { key: "i", value: f.description, onChange: e => set("description", e.target.value), placeholder: "optional" })]),
      ]),
      R.createElement("div", { className: "pp-pf-form-actions", key: "a" }, [
        R.createElement("button", { className: "pp-btn", key: "c", onClick: onClose }, "Cancel"),
        R.createElement("button", { className: "pp-btn pp-btn-primary", key: "s", onClick: save, disabled: saving }, saving ? "Saving…" : "Add gift"),
      ]),
    ]);
  }

  // ════════════════════════════════════════════════════════════
  //  Birthdays
  // ════════════════════════════════════════════════════════════
  function PpBirthdayHost() {
    const [bd, setBd] = R.useState(null);
    const [dismissed, setDismissed] = R.useState(false);
    R.useEffect(() => {
      let alive = true;
      (async () => {
        if (!(window.api && window.api.people && window.api.people.birthdays)) return;
        try {
          const r = await window.api.people.birthdays();
          if (!alive) return;
          setBd(r);
          const me = r && r.me;
          if (me && (me.isBirthday || me.isAnniversary)) {
            const key = "fb.celebrate:" + (userId() || "x") + ":" + new Date().toISOString().slice(0, 10);
            let seen = false; try { seen = localStorage.getItem(key) === "1"; } catch {}
            if (!seen) { fireConfetti(); try { localStorage.setItem(key, "1"); } catch {} }
          }
        } catch {}
      })();
      return () => { alive = false; };
    }, []);
    const me = bd && bd.me;
    if (!me || (!me.isBirthday && !me.isAnniversary) || dismissed) return null;
    const first = (() => { try { return (window.api.getUser().name || "").split(" ")[0]; } catch { return "you"; } })();
    const annOnly = me.isAnniversary && !me.isBirthday;
    let msg;
    const yrs = me.anniversaryYears;
    if (me.isBirthday && me.isAnniversary)
      msg = (yrs && yrs >= 1)
        ? `Happy Birthday & ${ordinal(yrs)} work anniversary, ${first}! 🎉`
        : `Happy Birthday & welcome to the team, ${first}! 🎉`;
    else if (me.isBirthday)
      msg = `Happy Birthday, ${first}! Wishing you a wonderful year ahead.`;
    else
      msg = (yrs && yrs >= 1)
        ? `Happy ${ordinal(yrs)} work anniversary, ${first}! Thank you for all you do.`
        : `Welcome to the team, ${first}! So glad to have you on board.`;
    const banner = R.createElement("div", { className: "pp-bday-banner" }, [
      R.createElement("span", { className: "pp-bday-emoji", key: "e" }, annOnly ? "🎊" : "🎉"),
      R.createElement("span", { className: "pp-bday-txt", key: "t" }, msg),
      R.createElement("button", { className: "pp-bday-cake", key: "c", onClick: fireConfetti, title: "More confetti!" }, annOnly ? "🎉" : "🎂"),
      R.createElement("button", { className: "pp-bday-x", key: "x", onClick: () => setDismissed(true), title: "Dismiss" }, "×"),
    ]);
    return (window.ReactDOM && window.ReactDOM.createPortal) ? window.ReactDOM.createPortal(banner, document.body) : banner;
  }

  function PpSidebarBirthdays() {
    const [bd, setBd] = R.useState(null);
    R.useEffect(() => {
      let alive = true;
      (async () => {
        if (!(window.api && window.api.people && window.api.people.birthdays)) return;
        try { const r = await window.api.people.birthdays(); if (alive) setBd(r); } catch {}
      })();
      return () => { alive = false; };
    }, []);
    if (!bd) return null;
    const meId = userId();
    const notMe = t => { try { return t.id !== meId; } catch { return true; } };
    const bToday = (bd.today || []).filter(notMe).map(t => ({ ...t, kind: "b" }));
    const aToday = (bd.anniversaries || []).filter(notMe).map(t => ({ ...t, kind: "a" }));
    const todayAll = [...bToday, ...aToday];
    const inLbl = d => d === 1 ? "tomorrow" : `${d}d`;
    const up = [
      ...(bd.upcoming || []).map(t => ({ ...t, kind: "b" })),
      ...(bd.anniversariesUpcoming || []).map(t => ({ ...t, kind: "a" })),
    ].sort((x, y) => x.inDays - y.inDays).slice(0, 5);
    if (!todayAll.length && !up.length) return null;

    function avatar(t) {
      if (window.PpAvatar) return R.createElement(window.PpAvatar, { person: { name: t.name, color: t.color, avatar: t.avatar }, size: "sm" });
      const initials = (t.name || "?").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();
      return R.createElement("span", { className: "pp-side-bday-av-fb", style: { background: t.color || "#0073ea" } }, initials);
    }
    function rowToday(t, i) {
      return R.createElement("div", { className: "pp-side-bday-row pp-side-bday-row-today", key: t.kind + (t.id || i) }, [
        R.createElement("span", { className: "pp-side-bday-pulse", key: "p" }),
        avatar(t),
        R.createElement("div", { className: "pp-side-bday-meta", key: "m" }, [
          R.createElement("div", { className: "pp-side-bday-name", key: "n" }, t.name),
          R.createElement("div", { className: "pp-side-bday-sub", key: "s" },
            t.kind === "a"
              ? (t.years && t.years >= 1
                  ? `🎊 ${t.years} yr · work anniversary`
                  : "🎊 Welcome to the team")
              : "🎂 Birthday today"),
        ]),
      ]);
    }
    function rowUp(t, i) {
      return R.createElement("div", { className: "pp-side-bday-row", key: t.kind + (t.id || i) }, [
        R.createElement("span", { className: "pp-side-bday-emoji", key: "e" }, t.kind === "a" ? "🎊" : "🎂"),
        avatar(t),
        R.createElement("div", { className: "pp-side-bday-meta", key: "m" }, [
          R.createElement("div", { className: "pp-side-bday-name", key: "n" }, t.name),
          R.createElement("div", { className: "pp-side-bday-sub", key: "s" },
            (t.kind === "a" ? `${t.years} yr · ` : "") + "in " + inLbl(t.inDays)),
        ]),
      ]);
    }

    return R.createElement("div", { className: "pp-side-bday" + (todayAll.length ? " has-today" : "") }, [
      R.createElement("div", { className: "pp-side-bday-head", key: "head" }, [
        R.createElement("span", { className: "pp-side-bday-icon", key: "i" }, "🎉"),
        R.createElement("span", { className: "pp-side-bday-title", key: "t" }, "Celebrations"),
        todayAll.length > 0 && R.createElement("span", { className: "pp-side-bday-count", key: "c" }, todayAll.length),
      ]),
      todayAll.length > 0 && R.createElement("div", { className: "pp-side-bday-sec", key: "today" }, [
        R.createElement("div", { className: "pp-side-bday-label", key: "l" }, "Today"),
        ...todayAll.map(rowToday),
      ]),
      up.length > 0 && R.createElement("div", { className: "pp-side-bday-sec", key: "up" }, [
        R.createElement("div", { className: "pp-side-bday-label", key: "l" }, "Coming up"),
        ...up.map(rowUp),
      ]),
    ]);
  }

  // ── CSS ───────────────────────────────────────────────────
  const CSS = `
  .pp-pf { display: flex; flex-direction: column; gap: 14px; }
  /* header card */
  .pp-pf-head { position:relative; background:var(--bg-card,#fff); border:1px solid var(--border-row,#eaecf1); border-radius:14px; overflow:hidden; }
  .pp-pf-accent { height:6px; background:var(--brand,#0073ea); }
  .pp-pf-close { position:absolute; top:13px; right:13px; z-index:2; background:var(--bg-subtle,#f1f3f7); border:1px solid var(--border-row,#e6e9ef); color:var(--ink-muted,#6c7385); width:30px; height:30px; border-radius:8px; font-size:18px; cursor:pointer; }
  .pp-pf-close:hover { background:#e8ebf1; }
  .pp-pf-head-row { display:flex; align-items:center; gap:16px; padding:18px 20px; flex-wrap:wrap; }
  .pp-pf-av { width:64px; height:64px; border-radius:50%; flex:none; object-fit:cover; }
  .pp-pf-av-ini { display:flex; align-items:center; justify-content:center; background:#e7f0fe; color:#0b5cad; font-size:22px; font-weight:700; }
  .pp-pf-id { flex:1; min-width:0; }
  .pp-pf-name { font-size:20px; font-weight:700; color:var(--ink-strong,#0f1729); letter-spacing:-0.01em; }
  .pp-pf-role { font-size:13.5px; color:var(--ink-muted,#6c7385); margin-top:1px; }
  .pp-pf-chips { display:flex; gap:6px; margin-top:9px; flex-wrap:wrap; }
  .pp-pf-chip { display:inline-flex; align-items:center; gap:4px; font-size:11px; font-weight:600; padding:3px 9px; border-radius:99px; background:var(--bg-subtle,#eef1f6); color:var(--ink-muted,#5f6675); }
  .pp-pf-chip svg { width:12px; height:12px; }
  .pp-pf-chip-code { font-family:ui-monospace,Menlo,monospace; }
  .pp-pf-chip-ins { background:#e9f7ef; color:#1a8a55; }
  .pp-pf-chip-warn { background:#fdf2da; color:#a8740f; }
  .pp-pf-chip-bday { background:#fde9ef; color:#c2410c; }
  .pp-pf-chip-muted { background:var(--bg-subtle,#eef1f6); color:var(--ink-muted,#6c7385); }
  .pp-pf-stats { display:flex; align-items:center; gap:20px; }
  .pp-pf-stat { text-align:right; }
  .pp-pf-stat-l { font-size:11px; color:var(--ink-faint,#9aa0ad); }
  .pp-pf-stat-v { font-size:15px; font-weight:600; color:var(--ink-strong,#0f1729); margin-top:1px; }
  /* body */
  .pp-pf-grid { display:grid; grid-template-columns: minmax(0,1.5fr) minmax(0,1fr); gap:14px; align-items:start; }
  .pp-pf-col { display:flex; flex-direction:column; gap:14px; min-width:0; }
  .pp-pf-card { padding:16px 18px; }
  .pp-pf-card-title { font-size:15px; font-weight:600; color:var(--ink-strong,#0f1729); margin-bottom:14px; }
  .pp-pf-card-head { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:12px; }
  .pp-pf-rows { display:grid; grid-template-columns:1fr 1fr; gap:14px 20px; }
  .pp-pf-fact-l { font-size:11px; color:var(--ink-faint,#9aa0ad); text-transform:uppercase; letter-spacing:.04em; }
  .pp-pf-fact-v { font-size:13.5px; color:var(--ink-strong,#0f1729); margin-top:3px; word-break:break-word; }
  .pp-pf-about-wrap { border-top:1px solid var(--border-row,#eef0f5); margin-top:16px; padding-top:14px; }
  .pp-pf-rowlabel { font-size:11px; color:var(--ink-faint,#9aa0ad); text-transform:uppercase; letter-spacing:.04em; margin-bottom:5px; }
  .pp-pf-about { font-size:13.5px; line-height:1.6; color:var(--ink-muted,#5f6675); }
  .pp-pf-muted { font-size:13px; color:var(--ink-muted,#8a90a0); }
  .pp-pf-link { background:transparent; border:0; cursor:pointer; font:inherit; font-size:12.5px; font-weight:600; color:var(--brand,#0073ea); padding:4px 6px; border-radius:6px; }
  .pp-pf-link:hover { background:rgba(0,115,234,.08); }
  .pp-pf-x { background:transparent; border:0; cursor:pointer; color:var(--ink-faint,#9aa0ad); font-size:16px; width:24px; height:24px; border-radius:6px; flex:none; }
  .pp-pf-x:hover { background:var(--bg-subtle,#f1f3f7); color:var(--ink-strong,#0f1729); }
  /* insurance states */
  .pp-pf-ins-pill { display:inline-flex; align-items:center; gap:5px; font-size:12px; font-weight:600; color:#1a8a55; background:#e9f7ef; padding:4px 11px; border-radius:99px; }
  .pp-pf-ins-pill svg { width:13px; height:13px; }
  .pp-pf-ins-elig { display:flex; align-items:center; gap:12px; background:#fff8ec; border:1px solid #fadc9b; border-radius:10px; padding:12px 14px; }
  .pp-pf-ins-elig-txt { flex:1; min-width:0; }
  .pp-pf-ins-elig-h { font-size:13.5px; font-weight:700; color:#9a6a08; }
  .pp-pf-ins-elig-s { font-size:11.5px; color:#a8740f; margin-top:1px; }
  /* gifts */
  .pp-pf-sub { font-size:10.5px; font-weight:600; letter-spacing:.05em; text-transform:uppercase; color:var(--ink-faint,#9aa0ad); margin:8px 0 8px; }
  .pp-pf-gift { display:flex; align-items:center; gap:11px; padding:8px 4px; border-bottom:1px solid var(--border-row,#f1f3f7); }
  .pp-pf-gift:last-child { border-bottom:0; }
  .pp-pf-gift-elig { background:#fff8ec; border:1px solid #fadc9b; border-radius:10px; padding:9px 11px; margin-bottom:8px; }
  .pp-pf-gift-emoji { font-size:20px; flex:none; }
  .pp-pf-gift-token { width:34px; height:34px; border-radius:50%; background:var(--bg-subtle,#eef1f6); display:flex; align-items:center; justify-content:center; font-size:17px; }
  .pp-pf-gift-txt { flex:1; min-width:0; }
  .pp-pf-gift-title { font-size:13px; font-weight:600; color:var(--ink-strong,#0f1729); }
  .pp-pf-gift-occ { font-size:11.5px; color:var(--ink-faint,#9aa0ad); }
  .pp-pf-gift-tag { font-size:11px; font-weight:700; color:#a8740f; background:#fdf2da; padding:3px 9px; border-radius:99px; }
  /* forms */
  .pp-pf-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px 14px; }
  .pp-pf-ff { display:flex; flex-direction:column; gap:4px; font-size:11.5px; font-weight:700; color:var(--ink-muted,#6c7385); }
  .pp-pf-ff input, .pp-pf-ff select, .pp-pf-ff textarea {
    font:inherit; font-size:13px; font-weight:400; padding:8px 10px;
    border:1px solid var(--border-row,#d6dae3); border-radius:8px; background:#fff; color:var(--ink-strong,#0f1729);
  }
  .pp-pf-ff input:focus, .pp-pf-ff select:focus, .pp-pf-ff textarea:focus { outline:none; border-color:#0073ea; box-shadow:0 0 0 3px rgba(0,115,234,.12); }
  .pp-pf-form { margin-top:4px; }
  .pp-pf-form > .pp-pf-ff { margin-top:10px; }
  .pp-pf-form-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:14px; }
  .pp-pf-check { display:flex; align-items:center; gap:8px; font-size:13.5px; font-weight:600; color:var(--ink-strong,#0f1729); margin-bottom:12px; }
  /* modals */
  .pp-pf-modal-ov { position:fixed; inset:0; z-index:9600; background:rgba(15,23,41,.45); display:flex; align-items:center; justify-content:center; padding:18px; }
  .pp-pf-modal { width:min(440px,94vw); background:var(--bg-card,#fff); border-radius:14px; padding:18px 20px; display:flex; flex-direction:column; gap:10px; box-shadow:0 24px 60px rgba(15,23,41,.34); }
  .pp-pf-modal-h { font-size:16px; font-weight:800; color:var(--ink-strong,#0f1729); }
  .pp-pf-modal-wide { width:min(900px,96vw); max-height:92vh; overflow:auto; background:var(--bg-page,#f6f7fb); border-radius:16px; padding:14px; }
  /* gifts admin */
  .pp-gifts { display:flex; flex-direction:column; gap:14px; }
  .pp-gifts-list { display:flex; flex-direction:column; gap:8px; }
  .pp-gift-row { display:flex; align-items:center; gap:12px; padding:11px 14px; border:1px solid var(--border-row,#eef0f5); border-radius:10px; background:var(--bg-card,#fff); }
  .pp-gift-row.is-archived { opacity:.55; }
  .pp-gift-emoji { font-size:22px; flex:none; }
  .pp-gift-meta { flex:1; min-width:0; }
  .pp-gift-name { font-size:13.5px; font-weight:700; color:var(--ink-strong,#0f1729); }
  .pp-gift-rule { font-size:11.5px; color:var(--ink-muted,#8a90a0); }
  .pp-gift-form { margin-top:0; }
  /* birthday banner */
  .pp-bday-banner { position:fixed; top:14px; left:50%; transform:translateX(-50%); z-index:99000;
    display:flex; align-items:center; gap:10px; max-width:92vw;
    background:linear-gradient(90deg,#ff8a3d,#ff5d8f,#9b5cff); color:#fff;
    padding:10px 14px; border-radius:999px; box-shadow:0 10px 30px rgba(0,0,0,.25); font-size:13.5px; font-weight:600; }
  .pp-bday-emoji { font-size:18px; }
  .pp-bday-cake, .pp-bday-x { background:rgba(255,255,255,.25); border:0; color:#fff; border-radius:50%; width:26px; height:26px; cursor:pointer; font-size:15px; line-height:1; }
  .pp-bday-cake:hover, .pp-bday-x:hover { background:rgba(255,255,255,.4); }
  /* sidebar birthdays / anniversaries */
  .pp-side-bday {
    margin: 12px 10px; padding: 11px 12px 9px;
    border-radius: 12px;
    background:
      linear-gradient(135deg, rgba(255,138,61,.10) 0%, rgba(255,93,143,.10) 45%, rgba(155,92,255,.10) 100%);
    border: 1px solid rgba(255,93,143,.32);
    box-shadow: 0 1px 6px rgba(155,92,255,.06), inset 0 0 0 0.5px rgba(255,255,255,.5);
  }
  .pp-side-bday.has-today {
    border-color: rgba(255,93,143,.55);
    background:
      linear-gradient(135deg, rgba(255,138,61,.18) 0%, rgba(255,93,143,.20) 45%, rgba(155,92,255,.18) 100%);
  }
  .pp-side-bday-head { display: flex; align-items: center; gap: 7px; margin-bottom: 6px; }
  .pp-side-bday-icon {
    font-size: 15px; line-height: 1;
    display: inline-block; transform-origin: 50% 70%;
    animation: pp-side-bday-bounce 2.4s ease-in-out infinite;
  }
  .pp-side-bday.has-today .pp-side-bday-icon { animation-duration: 1.6s; }
  @keyframes pp-side-bday-bounce {
    0%,100% { transform: translateY(0) rotate(0deg); }
    50%     { transform: translateY(-3px) rotate(10deg); }
  }
  .pp-side-bday-title {
    font-size: 12px; font-weight: 800; letter-spacing: .02em;
    background: linear-gradient(90deg, #d24a78 0%, #9b5cff 100%);
    -webkit-background-clip: text; background-clip: text;
    -webkit-text-fill-color: transparent; color: #9b5cff;
  }
  .pp-side-bday-count {
    margin-left: auto;
    font-size: 10px; font-weight: 800; color: #fff;
    background: linear-gradient(90deg, #ff5d8f, #9b5cff);
    padding: 1px 8px; border-radius: 99px; min-width: 18px; text-align: center;
    box-shadow: 0 1px 3px rgba(155,92,255,.35);
  }
  .pp-side-bday-sec + .pp-side-bday-sec { margin-top: 8px; }
  .pp-side-bday-label {
    font-size: 9.5px; font-weight: 800; letter-spacing: .08em;
    text-transform: uppercase; color: rgba(241,243,247,.6);
    margin: 2px 0 5px;
  }
  .pp-side-bday-row { display: flex; align-items: center; gap: 8px; padding: 3px 0; min-width: 0; }
  .pp-side-bday-row-today { padding: 4px 0; }
  .pp-side-bday-row .pp-av { width: 22px !important; height: 22px !important; font-size: 9.5px !important; flex: none; }
  .pp-side-bday-av-fb {
    width: 22px; height: 22px; border-radius: 50%; flex: none;
    color: #fff; font-size: 9.5px; font-weight: 700;
    display: inline-flex; align-items: center; justify-content: center;
  }
  .pp-side-bday-emoji { font-size: 13px; flex: none; width: 16px; text-align: center; }
  .pp-side-bday-pulse {
    width: 7px; height: 7px; border-radius: 50%;
    background: #ff5d8f; flex: none;
    box-shadow: 0 0 0 0 rgba(255,93,143,.6);
    animation: pp-side-bday-pulse 1.5s ease-out infinite;
  }
  @keyframes pp-side-bday-pulse {
    0%   { box-shadow: 0 0 0 0   rgba(255,93,143,.55); }
    70%  { box-shadow: 0 0 0 7px rgba(255,93,143,0); }
    100% { box-shadow: 0 0 0 0   rgba(255,93,143,0); }
  }
  .pp-side-bday-meta { flex: 1; min-width: 0; line-height: 1.2; }
  .pp-side-bday-name {
    font-size: 12.5px; font-weight: 600;
    color: #f4f5f8; /* light text for the dark sidebar */
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
  }
  .pp-side-bday-sub {
    font-size: 10.5px; color: rgba(244,245,248,.65);
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px;
  }

  /* ── Global avatar birthday celebration ──────────────────── */
  /* Wraps any avatar (project-wide <Avatar> or People <PpAvatar>) with
     a rotating rainbow ring + a bouncing 🎂 badge on the wearer's
     birthday. Wrapper is inline-block so it slots into existing flex
     rows and table cells without disturbing layout. */
  .avatar-bday-wrap {
    position: relative; display: inline-block; line-height: 0;
    vertical-align: middle;
  }
  .avatar-bday-wrap > * { position: relative; z-index: 1; }
  .avatar-bday-wrap::before {
    content: ""; position: absolute; inset: -3px;
    border-radius: 50%; padding: 2px;
    background: conic-gradient(from 0deg,
      #ff5d8f, #9b5cff, #4d96ff, #6bcB77, #ffd93d, #ff8a3d, #ff5d8f);
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor; mask-composite: exclude;
    animation: avatar-bday-spin 3.5s linear infinite;
    pointer-events: none; z-index: 2;
  }
  @keyframes avatar-bday-spin { to { transform: rotate(360deg); } }
  .avatar-bday-wrap::after {
    content: "🎂"; position: absolute; bottom: -5px; right: -5px;
    font-size: 13px; line-height: 1; z-index: 3;
    filter: drop-shadow(0 1px 2px rgba(0,0,0,.35));
    animation: avatar-bday-bounce 1.6s ease-in-out infinite;
    pointer-events: none;
  }
  @keyframes avatar-bday-bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-3px); } }
  .avatar-bday-sm::before { inset: -2px; }
  .avatar-bday-sm::after  { font-size: 10px; bottom: -3px; right: -3px; }
  .avatar-bday-md::after  { font-size: 12px; }
  .avatar-bday-lg::after  { font-size: 15px; bottom: -6px; right: -6px; }
  .avatar-bday-xl::after  { font-size: 18px; bottom: -7px; right: -7px; }

  /* ── Global avatar work-anniversary celebration ─────────────
     Mirrors the birthday treatment but uses a gold/teal gradient
     ring and a 🎉 badge so the two celebrations stay visually
     distinct. If a person has both today, the birthday wrap wins
     (cake takes priority). */
  .avatar-anniv-wrap {
    position: relative; display: inline-block; line-height: 0;
    vertical-align: middle;
  }
  .avatar-anniv-wrap > * { position: relative; z-index: 1; }
  .avatar-anniv-wrap::before {
    content: ""; position: absolute; inset: -3px;
    border-radius: 50%; padding: 2px;
    background: conic-gradient(from 0deg,
      #f5c542, #00c2a8, #4d96ff, #b48cff, #f5c542);
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor; mask-composite: exclude;
    animation: avatar-anniv-spin 4.2s linear infinite;
    pointer-events: none; z-index: 2;
  }
  @keyframes avatar-anniv-spin { to { transform: rotate(360deg); } }
  .avatar-anniv-wrap::after {
    content: "🎉"; position: absolute; bottom: -5px; right: -5px;
    font-size: 13px; line-height: 1; z-index: 3;
    filter: drop-shadow(0 1px 2px rgba(0,0,0,.35));
    animation: avatar-anniv-bounce 1.8s ease-in-out infinite;
    pointer-events: none;
  }
  @keyframes avatar-anniv-bounce { 0%,100% { transform: translateY(0) rotate(-6deg); } 50% { transform: translateY(-3px) rotate(6deg); } }
  .avatar-anniv-sm::before { inset: -2px; }
  .avatar-anniv-sm::after  { font-size: 10px; bottom: -3px; right: -3px; }
  .avatar-anniv-md::after  { font-size: 12px; }
  .avatar-anniv-lg::after  { font-size: 15px; bottom: -6px; right: -6px; }
  .avatar-anniv-xl::after  { font-size: 18px; bottom: -7px; right: -7px; }

  @media (max-width:760px) { .pp-pf-grid { grid-template-columns:1fr; } .pp-pf-rows, .pp-pf-form-grid { grid-template-columns:1fr; } .pp-pf-stats { gap:14px; } }
  `;
  (function inject() {
    if (document.getElementById("pp-profile-css")) return;
    const s = document.createElement("style"); s.id = "pp-profile-css"; s.textContent = CSS;
    document.head.appendChild(s);
  })();

  // ── global birthday host mount ─────────────────────────────
  function mountBirthday() {
    if (document.getElementById("pp-bday-host")) return;
    const node = document.createElement("div");
    node.id = "pp-bday-host";
    document.body.appendChild(node);
    try {
      if (window.ReactDOM.createRoot) window.ReactDOM.createRoot(node).render(R.createElement(PpBirthdayHost));
      else window.ReactDOM.render(R.createElement(PpBirthdayHost), node);
    } catch (e) { console.warn("[bday] mount failed:", e && e.message); }
  }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", mountBirthday);
  else mountBirthday();

  // ── Global birthday-IDs cache ─────────────────────────────
  // Powers the rainbow ring + 🎂 badge on every avatar in the app when
  // that person's birthday is today. Loaded once on app start, refreshed
  // every 15 min, and on focus.
  async function loadBdayIds() {
    if (!(window.api && window.api.people && window.api.people.birthdays)) return;
    try {
      const r = await window.api.people.birthdays();
      const ids = new Set();
      (r.today || []).forEach(t => t && t.id && ids.add(t.id));
      window.__fbBdayIds__ = ids;
      // Work anniversaries today — same celebration treatment, different
      // ring/badge. Populated from the same /birthdays payload so the
      // 🎉 ring + badge appears on every avatar across the app.
      const aIds = new Set();
      (r.anniversaries || []).forEach(t => t && t.id && aIds.add(t.id));
      window.__fbAnnivIds__ = aIds;
      try { window.dispatchEvent(new CustomEvent("flowboard:bday-loaded")); } catch {}
    } catch {}
  }
  function startBdayLoader() {
    setTimeout(loadBdayIds, 1500);
    setInterval(loadBdayIds, 15 * 60 * 1000);
    window.addEventListener("focus", () => { loadBdayIds(); });
  }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", startBdayLoader);
  else startBdayLoader();

  Object.assign(window, { PpProfile, PpProfileModal, PpGiftsAdmin, PpBirthdayHost, PpSidebarBirthdays });
})();
