const Topbar = ({ title, userId, setUserId, user, role, dateIso, device, setDevice, tasks, onSelectTask }) => {
  const [showRolePicker, setShowRolePicker] = React.useState(false);
  const [showNotifs, setShowNotifs] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(() => new Set());

  /* Group staff by role for the picker */
  const ROLE_GROUPS = [
    { id: "admin",   label: "Administración" },
    { id: "gerente", label: "Gerencia" },
    { id: "jefe",    label: "Jefes de área" },
    { id: "compras", label: "Compras" },
    { id: "staff",   label: "Staff" },
  ];
  const ROLE_HINTS = {
    admin: "Ve todas las áreas, aprueba, sube documentos",
    gerente: "Ve todas las áreas, mismos permisos",
    jefe: "Crea tareas, sube docs/inventario/menús de su área",
    compras: "Ve reportes, modifica compras y mantenimiento",
    staff: "Ve tareas de su área, modifica estado",
  };
  const staffByRole = ROLE_GROUPS.map(g => ({
    ...g,
    members: STAFF.filter(s => s.role === g.id),
  })).filter(g => g.members.length > 0);

  /* Build notifications from tasks */
  const notifications = React.useMemo(() => {
    if (!tasks) return [];
    const list = [];
    // Overdue tasks (vencida)
    tasks.filter(t => t.status === "vencida").forEach(t => {
      list.push({
        id: "overdue-" + t.id,
        kind: "overdue",
        icon: "AlertCircle",
        color: "var(--cdc-overdue)",
        title: t.title,
        sub: `Venció ${fmtShortDate(t.due)} · ${AREA_BY_ID[t.area]?.label || ""}`,
        taskId: t.id,
        sortKey: 1,
      });
    });
    // Due today
    tasks.filter(t => t.due === TODAY_ISO && t.status !== "terminada" && t.status !== "vencida").forEach(t => {
      list.push({
        id: "today-" + t.id,
        kind: "today",
        icon: "Clock",
        color: "var(--cdc-pending)",
        title: t.title,
        sub: `Vence hoy${t.dueTime ? ` · ${t.dueTime}` : ""} · ${AREA_BY_ID[t.area]?.label || ""}`,
        taskId: t.id,
        sortKey: 2,
      });
    });
    // Urgent
    tasks.filter(t => t.status === "urgente").forEach(t => {
      list.push({
        id: "urgent-" + t.id,
        kind: "urgent",
        icon: "Flag",
        color: "var(--cdc-urgent)",
        title: t.title,
        sub: `Urgente · ${AREA_BY_ID[t.area]?.label || ""}`,
        taskId: t.id,
        sortKey: 0,
      });
    });
    return list
      .filter(n => !dismissed.has(n.id))
      .sort((a, b) => a.sortKey - b.sortKey);
  }, [tasks, dismissed]);

  const unread = notifications.length;

  return (
    <header className="cdc-top">
      <h1 className="cdc-top__title">{title}</h1>

      <button className="cdc-pill">
        <I.Calendar size={15} />
        <span>{fmtLongDate(dateIso)}</span>
        <I.Chevron size={14} />
      </button>

      <button className="cdc-pill" style={{ gap: 10 }}>
        <I.Sun size={15} style={{ color: "#D5A23A" }} />
        <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.1, alignItems: "flex-start" }}>
          <span style={{ fontWeight: 700, fontSize: 12.5 }}>Punta Mita</span>
          <span style={{ fontSize: 11, color: "var(--cdc-ink-3)" }}>Parcialmente soleado</span>
        </span>
        <span style={{ fontWeight: 600 }}>28°C</span>
        <I.Chevron size={14} />
      </button>

      <div style={{ position: "relative" }}>
        <button
          className="cdc-top__bell"
          aria-label={`Notificaciones${unread ? ` (${unread})` : ""}`}
          onClick={() => setShowNotifs(s => !s)}
        >
          <I.Bell size={18} />
          {unread > 0 && <span className="cdc-top__bell-dot">{unread}</span>}
        </button>

        {showNotifs && (
          <>
            <div style={{ position: "fixed", inset: 0, zIndex: 40 }} onClick={() => setShowNotifs(false)} />
            <div style={{
              position: "absolute", right: 0, top: "calc(100% + 6px)",
              background: "white", border: "1px solid var(--cdc-border)", borderRadius: 12,
              boxShadow: "var(--cdc-shadow-lg)", width: 360, maxHeight: 480, zIndex: 50,
              display: "flex", flexDirection: "column",
            }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
                <div>
                  <div style={{ fontFamily: "var(--cdc-display)", fontSize: 17, fontWeight: 600 }}>Notificaciones</div>
                  <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{unread} pendiente{unread === 1 ? "" : "s"} de revisar</div>
                </div>
                {unread > 0 && (
                  <button
                    className="cdc-link"
                    onClick={() => setDismissed(new Set(notifications.map(n => n.id)))}
                    style={{ fontSize: 11.5, fontWeight: 600 }}
                  >
                    Marcar todo leído
                  </button>
                )}
              </div>

              <div style={{ flex: 1, overflowY: "auto" }}>
                {notifications.length === 0 ? (
                  <div className="cdc-empty" style={{ padding: "36px 20px" }}>
                    <I.CheckCircle size={36} style={{ color: "var(--cdc-done)" }} />
                    <div className="cdc-empty__title" style={{ fontSize: 18 }}>Todo al día</div>
                    <div style={{ fontSize: 12.5 }}>Sin tareas vencidas, urgentes ni pendientes para hoy.</div>
                  </div>
                ) : notifications.map(n => {
                  const IconCmp = I[n.icon] || I.Bell;
                  return (
                    <button
                      key={n.id}
                      onClick={() => {
                        onSelectTask && onSelectTask(n.taskId);
                        setShowNotifs(false);
                      }}
                      style={{
                        width: "100%", textAlign: "left",
                        display: "grid", gridTemplateColumns: "28px 1fr auto", gap: 10, alignItems: "flex-start",
                        padding: "12px 14px", borderBottom: "1px solid var(--cdc-border-soft)",
                        cursor: "pointer",
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = "var(--cdc-cream-50)"}
                      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                    >
                      <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 28, height: 28, borderRadius: 999, background: "var(--cdc-cream-100)", color: n.color, flexShrink: 0 }}>
                        <IconCmp size={14} />
                      </span>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13, color: "var(--cdc-ink)", lineHeight: 1.35 }}>{n.title}</div>
                        <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)", marginTop: 2 }}>{n.sub}</div>
                      </div>
                      <button
                        onClick={(e) => { e.stopPropagation(); setDismissed(prev => new Set([...prev, n.id])); }}
                        className="cdc-iconbtn"
                        title="Descartar"
                        style={{ width: 22, height: 22 }}
                      >
                        <I.X size={12} />
                      </button>
                    </button>
                  );
                })}
              </div>

              {notifications.length > 0 && (
                <div style={{ padding: "10px 14px", borderTop: "1px solid var(--cdc-border-soft)", fontSize: 11, color: "var(--cdc-ink-3)", textAlign: "center" }}>
                  Las notificaciones se actualizan automáticamente con las tareas.
                </div>
              )}
            </div>
          </>
        )}
      </div>

      {setDevice && (
        <button
          className="cdc-top__bell"
          title={device === "mobile" ? "Cambiar a escritorio" : "Ver en móvil (app del staff)"}
          onClick={() => setDevice(device === "mobile" ? "desktop" : "mobile")}
          style={{ width: 40 }}
        >
          {device === "mobile" ? <I.Building size={18} /> : <I.Smartphone size={18} />}
        </button>
      )}

      <div style={{ position: "relative" }}>
        <button className="cdc-user" onClick={() => setShowRolePicker(s => !s)}>
          <Avatar id={user.id} size="lg" />
          <div style={{ display: "flex", flexDirection: "column", textAlign: "left" }}>
            <span className="cdc-user__name">{user.name.split(" ")[0]} {user.name.split(" ")[1] || ""}</span>
            <span className="cdc-user__role">{PERMISSIONS[role].label}</span>
          </div>
          <I.Chevron size={14} style={{ color: "var(--cdc-ink-3)" }} />
        </button>

        {showRolePicker && (
          <>
            <div style={{ position: "fixed", inset: 0, zIndex: 40 }} onClick={() => setShowRolePicker(false)} />
            <div style={{ position: "absolute", right: 0, top: "calc(100% + 6px)",
              background: "white", border: "1px solid var(--cdc-border)", borderRadius: 12,
              boxShadow: "var(--cdc-shadow-lg)", padding: 6, width: 340, maxHeight: 540, overflowY: "auto", zIndex: 50,
            }}>
              <div style={{ padding: "8px 10px 6px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700 }}>
                Ver como
              </div>
              {staffByRole.map(group => (
                <React.Fragment key={group.id}>
                  <div style={{ padding: "8px 10px 4px", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--cdc-coral-deep)", fontWeight: 700, borderTop: "1px solid var(--cdc-border-soft)", marginTop: 4 }}>
                    {group.label}
                  </div>
                  {group.members.map(s => (
                    <button
                      key={s.id}
                      onClick={() => { setUserId(s.id); setShowRolePicker(false); }}
                      style={{
                        width: "100%", display: "flex", alignItems: "center", gap: 10,
                        padding: "8px 10px", borderRadius: 8, textAlign: "left",
                        background: s.id === userId ? "var(--cdc-cream-100)" : "transparent",
                      }}
                      onMouseEnter={(e) => { if (s.id !== userId) e.currentTarget.style.background = "var(--cdc-cream-50)"; }}
                      onMouseLeave={(e) => { if (s.id !== userId) e.currentTarget.style.background = "transparent"; }}
                    >
                      <Avatar id={s.id} size="lg" />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{s.name}</div>
                        <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{s.title}</div>
                        {s.extraAreas && s.extraAreas.length > 0 && (
                          <div style={{ fontSize: 10.5, color: "var(--cdc-ink-4)", marginTop: 2, lineHeight: 1.35 }}>
                            + {s.extraAreas.map(e => e.title).join(", ")}
                          </div>
                        )}
                      </div>
                      {s.id === userId && <I.Check size={16} style={{ color: "var(--cdc-coral)" }} />}
                    </button>
                  ))}
                </React.Fragment>
              ))}
              <div style={{ borderTop: "1px solid var(--cdc-border-soft)", marginTop: 4, padding: "8px 10px", fontSize: 11, color: "var(--cdc-ink-3)", lineHeight: 1.45 }}>
                Cambia el usuario activo para ver permisos y vista de esa persona.
              </div>
            </div>
          </>
        )}
      </div>
    </header>
  );
};

Object.assign(window, { Topbar });
