"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { CircleNotch, DownloadSimple, Eye, FilmStrip, House, Medal, PlayCircle, SignOut, Storefront } from "@phosphor-icons/react";

import type { TemaDosMembros } from "./tema";

/*
 * O topo da área de membros: a marca, Início, Meus cursos, Downloads,
 * Certificados e Loja, e quem está dentro (iniciais e Sair). No celular os
 * atalhos descem para uma barra de abas fixa embaixo, como num aplicativo.
 * `sobreFoto`: o topo fica transparente por cima da foto grande da página.
 */
export default function CabecalhoDosMembros({
  slug,
  nomeDaArea,
  pessoa,
  previa = false,
  ativo = "inicio",
  sobreFoto = false,
}: {
  slug: string;
  nomeDaArea: string;
  /* Mantidos para as telas que ainda passam (as cores vêm das variáveis da área). */
  cor?: string;
  tema?: TemaDosMembros;
  pessoa: { nome: string } | null;
  previa?: boolean;
  ativo?: "inicio" | "curso" | "nenhum";
  sobreFoto?: boolean;
}) {
  const router = useRouter();
  const [saindo, setSaindo] = useState(false);
  /* Por cima da foto o topo é transparente; ao rolar, vira barra de vidro. */
  const [rolou, setRolou] = useState(false);
  useEffect(() => {
    if (!sobreFoto) return;
    const conferir = () => setRolou(window.scrollY > 48);
    conferir();
    window.addEventListener("scroll", conferir, { passive: true });
    return () => window.removeEventListener("scroll", conferir);
  }, [sobreFoto]);
  const iniciais =
    (pessoa?.nome || "")
      .trim()
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((p) => p[0]?.toUpperCase())
      .join("") || "?";

  async function sair() {
    if (saindo) return;
    setSaindo(true);
    try {
      await fetch("/api/client-portal/logout", { method: "POST", headers: { "content-type": "application/json" } });
    } finally {
      router.push(`/${slug}/membros`);
      router.refresh();
    }
  }

  const atalhos = [
    { href: `/${slug}/membros`, rotulo: "Início", Icone: House, ativo: ativo === "inicio" },
    { href: `/${slug}/membros#cursos`, rotulo: "Meus conteúdos", curto: "Conteúdos", Icone: PlayCircle, ativo: ativo === "curso" },
    { href: `/${slug}/membros#downloads`, rotulo: "Downloads", Icone: DownloadSimple, ativo: false },
    { href: `/${slug}/membros#certificados`, rotulo: "Certificados", Icone: Medal, ativo: false },
    { href: `/${slug}`, rotulo: "Loja", Icone: Storefront, ativo: false },
  ];

  return (
    <>
      {previa ? (
        <div className="mb-previa">
          <Eye size={15} weight="bold" />
          Prévia da equipe: é assim que o cliente vê. Nada aqui grava progresso nem comentário.
        </div>
      ) : null}
      <header className={`mb-topo ${sobreFoto && !previa ? (rolou ? "mb-fixo" : "mb-fixo mb-sobre-foto") : ""}`}>
        <Link href={`/${slug}/membros`} className="mb-marca">
          <span className="mb-selo">
            <FilmStrip size={17} weight="fill" />
          </span>
          <span>{nomeDaArea}</span>
        </Link>
        <nav className="mb-menu">
          {atalhos.map((atalho) => (
            <Link key={atalho.rotulo} href={atalho.href} className={atalho.ativo ? "mb-ativo" : undefined}>
              {atalho.rotulo}
            </Link>
          ))}
        </nav>
        <div className="mb-direita">
          {pessoa ? (
            <>
              <span className="mb-avatar" title={pessoa.nome}>
                {iniciais}
              </span>
              <button type="button" onClick={() => void sair()} disabled={saindo} className="mb-sair" aria-label="Sair">
                {saindo ? <CircleNotch size={16} className="animate-spin" /> : <SignOut size={17} weight="bold" />}
                <span>Sair</span>
              </button>
            </>
          ) : !previa ? (
            <Link href={`/${slug}/membros`} className="mb-sair">
              Entrar
            </Link>
          ) : null}
        </div>
      </header>
      <nav className="mb-abas" aria-label="Atalhos da área">
        {atalhos.map(({ Icone, ...atalho }) => (
          <Link key={atalho.rotulo} href={atalho.href} className={atalho.ativo ? "mb-ativo" : undefined}>
            <Icone size={23} weight={atalho.ativo ? "fill" : "regular"} />
            {"curto" in atalho && atalho.curto ? atalho.curto : atalho.rotulo}
          </Link>
        ))}
      </nav>
    </>
  );
}
