"use client";

import { DETAIL_TITLE } from "../opportunityDetailLayout";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import type { VolunteerOpportunityDetail } from "./types";
import { opportunityTitle, type VolunteerEventView } from "./volunteerEventView";

interface OpportunityHeaderProps {
  data: VolunteerOpportunityDetail;
  view: VolunteerEventView;
  onRegisterClick: () => void;
}

/**
 * Title and the viewer's Register / Unregister.
 *
 * The creator's controls are *not* here — `CreatorActionBar` renders them as a
 * vertical rail beside the whole details column, one level up in
 * `VolunteerEvent`. Everyone else keeps a labelled button, because for them
 * this is the page's main call to action — the one control a volunteer must not
 * have to hover to identify. It is desktop-only here; `ViewerActionButton`
 * renders the phone copy further down the page.
 */
export default function OpportunityHeader({
  data,
  view,
  onRegisterClick,
}: OpportunityHeaderProps) {
  const { t } = useTranslation();

  return (
    <div className="flex justify-between items-start gap-4">
      <h2 className={DETAIL_TITLE}>
        {opportunityTitle(data)}
      </h2>

      <div className="flex flex-col items-end gap-3">
        <ViewerActionButton
          view={view}
          onClick={onRegisterClick}
          className="whitespace-nowrap block xss:hidden disabled:opacity-50 disabled:cursor-not-allowed"
        />

        {/* The creator reads the closed state off the accented padlock; a
            viewer has no padlock, so they keep the labelled pill. */}
        {view.showRegistrationClosedBadge && (
          <span className="whitespace-nowrap rounded-[20px] bg-[#F1F1F5] px-4 py-2 text-sm font-bold text-secondary-102">
            {t("COMMON.REGISTRATION_CLOSED")}
          </span>
        )}
      </div>
    </div>
  );
}

/**
 * The labelled Register / Unregister button. Renders for viewers only — the
 * creator's equivalent is the glyph in `CreatorActionBar`, so showing this too
 * would put the same action on the page twice.
 */
export function ViewerActionButton({
  view,
  onClick,
  className,
}: {
  view: Pick<
    VolunteerEventView,
    "showActionButton" | "isCreator" | "isViewerActionDisabled" | "actionLabelKey"
  >;
  onClick: () => void;
  className: string;
}) {
  const { t } = useTranslation();
  if (!view.showActionButton || view.isCreator) return null;

  return (
    <div className="flex flex-col items-center gap-2"><Button
      variant="primary"
      size="medium"
      className={`!h-11 !px-5 !text-sm ${className}`}
      disabled={view.isViewerActionDisabled}
      onClick={onClick}
    >
      {t(view.actionLabelKey)}
    </Button>
    {view.actionLabelKey === "COMMON.REGISTERED" && <p className="max-w-xs text-center text-xs leading-relaxed text-secondary-102">{t("COMMON.REGISTRATION_CANCELLATION_CUTOFF")}</p>}
    </div>
  );
}
