// Mapea códigos WMO (Open-Meteo) a descripción breve en español.
const _weatherDesc = (code) => {
  if (code === 0) return "Despejado";
  if (code === 1) return "Mayormente despejado";
  if (code === 2) return "Parcialmente nublado";
  if (code === 3) return "Nublado";
  if (code === 45 || code === 48) return "Niebla";
  if (code >= 51 && code <= 57) return "Llovizna";
  if (code >= 61 && code <= 67) return "Lluvia";
  if (code >= 71 && code <= 77) return "Nieve";
  if (code >= 80 && code <= 82) return "Chubascos";
  if (code >= 95) return "Tormenta";
  return "—";
};

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

  // Clima actual de Punta Mita (API gratuita de Open-Meteo, sin API key).
  React.useEffect(() => {
    fetch("https://api.open-meteo.com/v1/forecast?latitude=20.78&longitude=-105.52&current=temperature_2m,weather_code&timezone=auto")
      .then(r => r.json())
      .then(d => {
        if (d && d.current) {
          setWeather({
            temp: Math.round(d.current.temperature_2m),
            desc: _weatherDesc(d.current.weather_code),
          });
        }
      })
      .catch(() => { /* sin red — dejamos el placeholder */ });
  }, []);

  /* 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)" }}>{weather ? weather.desc : "Cargando…"}</span>
        </span>
        <span style={{ fontWeight: 600 }}>{weather ? `${weather.temp}°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: 260, zIndex: 50,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 10px 12px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
                <Avatar id={user.id} size="lg" />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13.5 }}>{user.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{user.title} · {PERMISSIONS[role].label}</div>
                </div>
              </div>
              <button
                onClick={() => { setShowRolePicker(false); setShowPwModal(true); }}
                style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "10px 10px", borderRadius: 8, textAlign: "left", marginTop: 4 }}
                onMouseEnter={(e) => e.currentTarget.style.background = "var(--cdc-cream-50)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
              >
                <span style={{ fontSize: 13.5, color: "var(--cdc-ink)" }}>Cambiar contraseña</span>
              </button>
              <button
                onClick={() => { setShowRolePicker(false); onLogout && onLogout(); }}
                style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "10px 10px", borderRadius: 8, textAlign: "left", color: "var(--cdc-urgent)" }}
                onMouseEnter={(e) => e.currentTarget.style.background = "var(--cdc-cream-50)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
              >
                <span style={{ fontSize: 13.5 }}>Cerrar sesión</span>
              </button>
            </div>
          </>
        )}
      </div>

      {showPwModal && <ChangePasswordModal onClose={() => setShowPwModal(false)} />}
    </header>
  );
};

Object.assign(window, { Topbar });
