// ============ TaskQuest — Header & Notifications ============
const { useState, useEffect, useRef } = React;
const { ROLES: R2, PROJECTS: P2, CONSULTANTS: C2 } = window.TQ;

function Dropdown({ trigger, children, width, align = "left" }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useClickOutside(ref, () => setOpen(false), open);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      {trigger(open, () => setOpen(o => !o))}
      {open && (
        <div className="pop" style={{ [align]: 0, top: "calc(100% + 6px)", minWidth: width }}
          onClick={() => setOpen(false)}>
          {children}
        </div>
      )}
    </div>
  );
}

function Header({ role, setRole, project, setProject, theme, toggleTheme, authUser, onLogout, canSwitchRole = true, notifications, onOpenNotif, notifOpen, notifPanel }) {
  const r = R2[role];
  const isDM = r.type === "dm";
  // PMs/consultants are scoped to the projects they're assigned to; DMs span all.
  const myProjs = window.TQ.projectsOf(r).map(k => P2[k]).filter(Boolean);
  const projOptions = isDM
    ? [{ key: "all", name: "All Projects", color: "#8b7cf6" }, ...Object.values(P2)]
    : (myProjs.length ? myProjs : Object.values(P2));
  const curProj = project === "all" ? { name: "All Projects", color: "#8b7cf6" } : (P2[project] || { name: "—", color: "#878b94" });
  const acct = R2[authUser] || r;
  const acctUsername = (R2[authUser] && R2[authUser].username) || "";

  return (
    <header className="app-header">
      <div className="brand">
        <div className="brand-mark"><Ic.Layers size={15} sw={2.2} /></div>
        <div className="brand-name">Task<b>Quest</b></div>
      </div>
      <div className="header-divider" />

      {/* Project selector — managers only (consultants see their own board) */}
      {(r.type === "pm" || r.type === "dm") && (
      <Dropdown width={220} trigger={(open, t) => (
        <button className="hbtn bordered" onClick={t}>
          <span className="pdot" style={{ width: 8, height: 8, borderRadius: "50%", background: curProj.color }} />
          {curProj.name}
          <Ic.ChevDown size={14} className="chev" />
        </button>
      )}>
        <div className="pop-label">Projects</div>
        {projOptions.map(p => (
          <button key={p.key} className={`pop-item ${project === p.key ? "active" : ""}`} onClick={() => setProject(p.key)}>
            <span style={{ width: 9, height: 9, borderRadius: "50%", background: p.color }} />
            {p.name}
            {project === p.key && <span className="check"><Ic.Check size={15} /></span>}
          </button>
        ))}
      </Dropdown>
      )}

      <div className="spacer" />

      {/* Role switcher — prototype only (offline preview / admin impersonation) */}
      {canSwitchRole && (
        <Dropdown width={250} align="right" trigger={(open, t) => (
          <button className="hbtn bordered" onClick={t} title="Switch role (prototype)">
            <Ic.Users size={14} style={{ color: "var(--faint)" }} />
            View as
            <Ic.ChevDown size={14} className="chev" />
          </button>
        )}>
          <div className="pop-label">View as · prototype</div>
          {Object.values(R2).slice().sort((a, b) => {
            const ord = { dm: 0, pm: 1, consultant: 2, admin: 3 };
            return (ord[a.type] - ord[b.type]) || a.name.localeCompare(b.name);
          }).map(p => (
            <button key={p.key} className={`pop-item ${role === p.key ? "active" : ""}`} onClick={() => setRole(p.key)}>
              <Avatar who={p.key} size="sm" />
              <span style={{ fontWeight: 600, flex: 1, whiteSpace: "nowrap" }}>{p.short}</span>
              <span className="role-meta">{p.type === "consultant" ? "Consultant" : p.label}</span>
            </button>
          ))}
        </Dropdown>
      )}

      {/* Signed-in identity (locked to the authenticated user) */}
      <span className="hbtn bordered identity" style={{ cursor: "default" }} title={r.name}>
        <Avatar who={authUser} size="sm" />
        <span className="identity-text">
          <span className="identity-name">{r.short}</span>
          <span className="identity-role">{r.type === "consultant" ? "Consultant" : r.label}</span>
        </span>
      </span>

      <div className="header-divider" />

      {/* Theme toggle */}
      <button className="icon-btn" onClick={toggleTheme} title="Toggle theme">
        {theme === "dark" ? <Ic.Sun size={17} /> : <Ic.Moon size={17} />}
      </button>

      {/* Notifications */}
      <div style={{ position: "relative" }}>
        <button className="icon-btn" onClick={onOpenNotif} title="Notifications">
          <Ic.Bell size={17} />
          {notifications.filter(n => !n.read).length > 0 && (
            <span className="notif-dot">{notifications.filter(n => !n.read).length}</span>
          )}
        </button>
        {notifOpen && notifPanel}
      </div>

      <Dropdown width={230} align="right" trigger={(open, tog) => (
        <button className="acct-trigger" onClick={tog} title={acct.name}>
          <Avatar who={authUser} size="lg" />
        </button>
      )}>
        <div className="acct-card">
          <Avatar who={authUser} size="lg" />
          <div>
            <div className="acct-name">{acct.name}</div>
            <div className="acct-user">@{acctUsername}</div>
          </div>
        </div>
        <div className="pop-sep" />
        <button className="pop-item" onClick={onLogout}>
          <Ic.Logout size={16} style={{ color: "var(--muted)" }} />Log out
        </button>
      </Dropdown>
    </header>
  );
}

function NotificationsPanel({ notifications, onClose, onMarkAll, onClickNotif }) {
  const ref = useRef(null);
  useClickOutside(ref, onClose, true);
  const iconFor = {
    date_request: { ic: Ic.Calendar, c: "#f2c94c" },
    date_approved: { ic: Ic.CheckCircle, c: "#4cb782" },
    approved: { ic: Ic.CheckCircle, c: "#4cb782" },
    done: { ic: Ic.Flag, c: "#8b7cf6" },
    comment: { ic: Ic.Msg, c: "#4ea7fc" },
    bonus: { ic: Ic.Gift, c: "#e0902b" },
    rejected: { ic: Ic.X, c: "#eb5757" },
  };
  return (
    <div ref={ref} className="pop notif-pop" style={{ right: 0, top: "calc(100% + 8px)" }}>
      <div className="notif-head">
        <span className="notif-head-title">Notifications</span>
        {notifications.some(n => !n.read) && <button className="notif-mark" onClick={onMarkAll}>Mark all read</button>}
      </div>
      <div className="notif-list">
        {notifications.length === 0 && <div className="notif-empty">You're all caught up.</div>}
        {notifications.map(n => {
          const meta = iconFor[n.type] || { ic: Ic.Bell, c: "var(--muted)" };
          return (
            <div key={n.id} className={`notif ${n.read ? "" : "unread"}`} onClick={() => onClickNotif(n)}>
              <div className="notif-ic" style={{ background: meta.c + "22", color: meta.c }}>
                {React.createElement(meta.ic, { size: 15 })}
              </div>
              <div className="notif-c">
                <div className="notif-text" dangerouslySetInnerHTML={{ __html: n.text }} />
                <div className="notif-time">{n.time}{n.project ? " · " + (P2[n.project] ? P2[n.project].name : "") : ""}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.Header = Header;
window.NotificationsPanel = NotificationsPanel;
window.Dropdown = Dropdown;
