/* Notification bell + acting-user switcher for the TopBar. Notifications are
   generated by the store on task assignment, post creation, status change and
   schedule reminders, routed per-user (Settings), and mirrored to (simulated)
   email. Shows the current user's notifications. */
(function () {
  const S = window.CroprStore;
  const D = window.CROPR_DATA;

  const rel = (iso) => {
    const s = Math.round((Date.now() - new Date(iso).getTime()) / 1000);
    if (s < 60) return "just now"; if (s < 3600) return Math.floor(s / 60) + "m ago";
    if (s < 86400) return Math.floor(s / 3600) + "h ago"; return Math.floor(s / 86400) + "d ago";
  };
  const notifIcon = (n) => {
    if (n.category === "task") return (D.ACTIONS.find((a) => a.id === n.action) || {}).icon || "list-checks";
    if (n.category === "created") return "file-plus";
    if (n.category === "status") return "git-branch";
    return "bell";
  };
  const notifColor = (n) => n.category === "reminder" ? "#B25E09" : n.category === "task" ? "var(--accent)" : "var(--fg3)";

  function memberAvatar(name, size) {
    const m = (S.getTeam() || []).find((x) => x.name === name) || {};
    const colors = { Adam: "#38BDF8", Eva: "#0EA5B7", Alex: "#12B76A", Sam: "#F79009", Mia: "#E1306C" };
    return <Avatar color={colors[name] || "#6E6E7A"} initials={(name || "?").slice(0, 2).toUpperCase()} size={size} />;
  }

  function UserSwitcher() {
    const [open, setOpen] = React.useState(false);
    const cur = S.getCurrentUser();
    const team = S.getTeam();
    const role = (m) => (S.getRoles().find((r) => r.id === m.roleId) || {}).name || "";
    // Live mode: identity is the authenticated user — no persona switching.
    const locked = S.identityLocked && S.identityLocked();
    if (locked) {
      return (
        <div title="Signed in as (your account)" style={{ display: "flex", alignItems: "center", gap: 8, height: 36, padding: "0 12px 0 6px", borderRadius: 999, border: "1px solid var(--border-strong)", background: "var(--surface)" }}>
          {memberAvatar(cur, 24)}<span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg1)" }}>{cur}</span>
        </div>
      );
    }
    return (
      <div style={{ position: "relative" }}>
        <button onClick={() => setOpen((o) => !o)} title="Acting as (switch user)" style={{ display: "flex", alignItems: "center", gap: 8, height: 36, padding: "0 10px 0 6px", borderRadius: 999, border: "1px solid var(--border-strong)", background: "var(--surface)", cursor: "pointer", fontFamily: "inherit" }}>
          {memberAvatar(cur, 24)}<span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg1)" }}>{cur}</span><Icon name="chevron-down" size={14} color="var(--fg3)" />
        </button>
        {open && (
          <React.Fragment>
            <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 88 }} />
            <div style={{ position: "absolute", top: 42, right: 0, zIndex: 89, width: 220, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, boxShadow: "var(--shadow-lg)", padding: 6 }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--fg4)", textTransform: "uppercase", letterSpacing: ".05em", padding: "6px 8px" }}>Acting as</div>
              {team.map((m) => (
                <button key={m.id} onClick={() => { S.setCurrentUser(m.name); setOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", border: 0, background: m.name === cur ? "var(--accent-weak)" : "transparent", cursor: "pointer", padding: "8px 8px", borderRadius: 8, fontFamily: "inherit", textAlign: "left" }}>
                  {memberAvatar(m.name, 26)}
                  <span style={{ minWidth: 0 }}><span style={{ display: "block", fontSize: 13, fontWeight: 600, color: "var(--fg1)" }}>{m.name}</span><span style={{ display: "block", fontSize: 11, color: "var(--fg3)" }}>{role(m)}</span></span>
                  {m.name === cur && <Icon name="check" size={15} color="var(--accent)" style={{ marginLeft: "auto" }} />}
                </button>
              ))}
            </div>
          </React.Fragment>
        )}
      </div>
    );
  }

  function NotificationBell({ onOpen, onSettings }) {
    const [open, setOpen] = React.useState(false);
    const cur = S.getCurrentUser();
    const notifs = S.getNotifications(cur);
    const unread = notifs.filter((n) => !n.read).length;
    const emailOn = S.getNotifSettings().emailEnabled;
    return (
      <div style={{ position: "relative" }}>
        <button onClick={() => setOpen((o) => !o)} title="Notifications" style={{ position: "relative", width: 38, height: 38, borderRadius: 10, border: 0, background: "var(--bg-muted)", cursor: "pointer", display: "grid", placeItems: "center" }}>
          <Icon name="bell" size={18} color="var(--fg2)" />
          {unread > 0 && <span style={{ position: "absolute", top: -4, right: -4, minWidth: 18, height: 18, borderRadius: 999, background: "var(--danger)", color: "#fff", fontSize: 10.5, fontWeight: 700, display: "grid", placeItems: "center", padding: "0 4px", border: "2px solid var(--surface)" }}>{unread > 9 ? "9+" : unread}</span>}
        </button>
        {open && (
          <React.Fragment>
            <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 88 }} />
            <div style={{ position: "absolute", top: 46, right: 0, zIndex: 89, width: 380, maxWidth: "92vw", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 14, boxShadow: "var(--shadow-xl)", overflow: "hidden" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "12px 14px", borderBottom: "1px solid var(--border)" }}>
                <span style={{ fontSize: 14, fontWeight: 700 }}>Notifications</span>
                <span style={{ fontSize: 11.5, color: "var(--fg3)" }}>· {cur}</span>
                <div style={{ flex: 1 }} />
                {unread > 0 && <button onClick={() => S.markAllNotifsRead(cur)} style={{ border: 0, background: "none", cursor: "pointer", color: "var(--accent)", fontSize: 12, fontWeight: 600 }}>Mark all read</button>}
                <button onClick={() => { setOpen(false); onSettings && onSettings(); }} title="Notification settings" style={{ border: 0, background: "none", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="settings" size={16} color="var(--fg3)" /></button>
              </div>
              <div style={{ maxHeight: 420, overflowY: "auto" }}>
                {notifs.length === 0 && <div style={{ padding: "34px 20px", textAlign: "center", color: "var(--fg3)", fontSize: 13 }}><Icon name="bell-off" size={22} color="var(--fg4)" /><div style={{ marginTop: 8 }}>You're all caught up.</div></div>}
                {notifs.slice(0, 40).map((n) => (
                  <div key={n.id} onClick={() => { S.markNotifRead(n.id); if (n.postId && onOpen) { setOpen(false); onOpen(n.postId); } }}
                    style={{ display: "flex", gap: 10, padding: "11px 14px", borderBottom: "1px solid var(--border)", cursor: n.postId ? "pointer" : "default", background: n.read ? "transparent" : "var(--accent-weak)" }}>
                    <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--bg-muted)", display: "grid", placeItems: "center", flex: "none" }}><Icon name={notifIcon(n)} size={16} color={notifColor(n)} /></span>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--fg1)", lineHeight: 1.35 }}>{n.title}</div>
                      {n.body && <div style={{ fontSize: 11.5, color: "var(--fg3)", lineHeight: 1.35, marginTop: 1 }}>{n.body}</div>}
                      <div style={{ fontSize: 10.5, color: "var(--fg4)", marginTop: 3, display: "flex", alignItems: "center", gap: 6 }}>{rel(n.at)}{n.emailed && <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}><Icon name="mail" size={11} color="var(--fg4)" />emailed</span>}</div>
                    </div>
                    {!n.read && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--accent)", flex: "none", marginTop: 5 }} />}
                  </div>
                ))}
              </div>
              <div style={{ padding: "8px 14px", fontSize: 10.5, color: "var(--fg4)", borderTop: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 6 }}>
                <Icon name={emailOn ? "mail" : "mail-x"} size={12} color="var(--fg4)" />Email delivery {emailOn ? "on" : "off"} · configure in Settings
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    );
  }

  window.NotificationBell = NotificationBell;
  window.UserSwitcher = UserSwitcher;
  window.memberAvatar = memberAvatar;
})();
