"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

import LanguageSwitcher from "@/app/components/LanguageSwitcher";
import NotificationBell from "@/app/components/notifications/NotificationBell";
import { getAstrologerDashboard } from "@/app/lib/astrologer";
import { getAstrologerAuthToken } from "@/app/lib/astrologer-token";

function greeting(): string {
  const hour = new Date().getHours();

  if (hour < 12) return "Good morning";
  if (hour < 17) return "Good afternoon";

  return "Good evening";
}

/*
 * The one fixed header shared by every astrologer dashboard page (mounted
 * once in app/astrologer/layout.tsx): greeting + name on the left, language,
 * notification bell and profile photo on the right. Pages only render their
 * own breadcrumb + title below it.
 */
export default function AstrologerTopbar() {
  const [token, setToken] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [image, setImage] = useState("");
  const [hello, setHello] = useState("Hello");

  useEffect(() => {
    const t = getAstrologerAuthToken();

    setToken(t);
    setHello(greeting());

    if (!t) return;

    getAstrologerDashboard(t)
      .then((response) => {
        const data = response?.data ?? response;

        setName(String(data?.name ?? ""));
        setImage(String(data?.profile_image ?? ""));
      })
      .catch(() => {});
  }, []);

  const initial = (name || "A").trim().charAt(0).toUpperCase();

  return (
    <header className="astro-topbar">
      <div className="astro-topbar-id">
        <div className="astro-topbar-greeting">{hello},</div>
        <div className="astro-topbar-name" translate="no">
          {name || "Astrologer"}
        </div>
      </div>

      <div className="astro-topbar-actions">
        <LanguageSwitcher />

        <NotificationBell
          audience="astrologer"
          token={token}
          notificationsHref="/astrologer/notifications"
          dark
        />

        <Link href="/astrologer/profile" className="astro-topbar-profile" aria-label="Open profile" title="Profile">
          {image ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={image} alt="" className="astro-topbar-avatar" />
          ) : (
            <div className="astro-topbar-avatar astro-topbar-avatar-fallback">{initial}</div>
          )}
        </Link>
      </div>
    </header>
  );
}
