// Dashboard/TopBar.jsx
function TopBar(props) {
  const {
    editing,
    setEditing,
    profile,
    handleLogout,
    openCourses,
    showCertificates,
    setShowCertificates
  } = props;

  const [enrolledCount, setEnrolledCount] = React.useState(0);

  React.useEffect(() => {
    function readEnrolled() {
      try {
        const raw = localStorage.getItem("mta_enrolled_courses");
        const map = raw ? JSON.parse(raw) : {};
        setEnrolledCount(Object.keys(map || {}).length);
      } catch {
        setEnrolledCount(0);
      }
    }

    readEnrolled();
    function onStorage(e) {
      if (e.key === "mta_enrolled_courses") readEnrolled();
    }
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  return (
    <header
      className="topbar"
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        padding: "12px 18px",
        borderBottom: "1px solid #111827",
        background: "#071029"
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ fontWeight: 800, color: "#e2e8f0", fontSize: 18 }}>MTA</div>

        <button
          className="btn ghost topbar-courses-btn"
          onClick={() => {
            if (typeof openCourses === "function") openCourses();
          }}
          title="Перейти к курсам"
          style={{ position: "relative", padding: "6px 10px", borderRadius: 8 }}
        >
          Курсы
          {enrolledCount > 0 && (
            <span
              style={{
                position: "absolute",
                top: -6,
                right: -8,
                background: "#ef4444",
                color: "#fff",
                fontSize: 11,
                padding: "2px 6px",
                borderRadius: 999
              }}
            >
              {enrolledCount}
            </span>
          )}
        </button>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <button
          className="btn ghost"
          onClick={() => setShowCertificates && setShowCertificates(!showCertificates)}
        >
          Сертификаты
        </button>

        <button
          className="btn"
          onClick={() => {
            setEditing && setEditing(!editing);
          }}
        >
          {editing ? "Готово" : "Редактировать"}
        </button>

        <div style={{ width: 1, height: 28, background: "#0f1724", margin: "0 8px" }} />

        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ color: "#cbd5e1", fontSize: 13 }}>
            {profile?.name || profile?.email || "Пользователь"}
          </div>
          <button className="btn ghost" onClick={handleLogout}>Выйти</button>
        </div>
      </div>
    </header>
  );
}
