"use client";


import { DETAIL_ORGANIZER, DETAIL_AVATAR } from "../opportunityDetailLayout";
import Link from "next/link";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { IoIosShareAlt } from "react-icons/io";
import { getDefaultProfileImage, handleShare } from "@/lib/helpers";
import type { OpportunityCreator, VolunteerOpportunityDetail } from "./types";
import { organizerProfilePath } from "./volunteerEventView";
import RemoteImage from "@/components/ui/RemoteImage";
import { contactWhatsAppHref } from "@/lib/whatsapp";
import { externalHref } from "@/features/events/eventLifecycle";

const SOCIAL_LINKS = [
  { key: "facebook_link", icon: "/assets/profile/facebook.svg" },
  { key: "twitter_link", icon: "/assets/profile/twitter.svg" },
  { key: "whatsapp_link", icon: "/assets/profile/whatsapp.svg" },
  { key: "instagram_link", icon: "/assets/profile/instagram.svg" },
  { key: "linkedin_link", icon: "/assets/profile/linkdin.svg" },
] as const satisfies ReadonlyArray<{ key: keyof OpportunityCreator; icon: string }>;

interface OrganizerCardProps {
  data: VolunteerOpportunityDetail;
  isCreator: boolean;
  children?: ReactNode;
}

/**
 * A WhatsApp value as a link. Organizations may now store a plain number
 * (backend `55e6e46`, `whatsapp_link` is `string|max:15`), which as a raw
 * `href` would be a broken relative link; a URL passes through.
 */
function whatsAppHref(value: string | null | undefined): string | null {
  // A link pasted without its scheme (`chat.whatsapp.com/…`) gains `https://`
  // instead of being dropped (same rule as the development detail).
  return contactWhatsAppHref(value) || null;
}

/** Avatar, name, social links (WhatsApp prefers the opportunity's own) and Share. */
export default function OrganizerCard({ data, isCreator, children }: OrganizerCardProps) {
  const { t } = useTranslation();
  const creator = data.created_by;
  const profilePath = organizerProfilePath(creator);

  /*
   * One WhatsApp icon, no green button (client, 2026-10-15). When the
   * opportunity has its own WhatsApp (`link`, the form's «رابط واتساب») the
   * icon opens that instead of the organization's profile number — a volunteer
   * asking about this opportunity should reach whoever runs it.
   */
  const socialLinks = SOCIAL_LINKS.flatMap(({ key, icon }) => {
    const raw = key === "whatsapp_link" ? data.link || creator?.[key] : creator?.[key];
    const href = key === "whatsapp_link" ? whatsAppHref(raw) : externalHref(raw);
    return href ? [{ key, icon, href }] : [];
  });

  return (
    <div className={`opportunity-detail-organizer ${DETAIL_ORGANIZER}`}>
      <Link href={profilePath}>
        <RemoteImage
          src={
            creator?.profile_pic ||
            getDefaultProfileImage(
              creator?.gender_display?.value_en ?? undefined,
              "/assets/profile/male_profile.svg",
              "/assets/profile/female_profile.svg",
              "/assets/profile/org_profile.svg"
            )
          }
          alt={creator?.full_name ?? ""}
          width={112}
          height={112}
          className={DETAIL_AVATAR}
        />
      </Link>

      <div className="relative flex w-full flex-col items-center pt-4">
        <Link href={profilePath} className="block w-full max-w-[220px] min-w-0">
          <div className="w-full text-center">
            <h3 className="text-base font-bold leading-relaxed text-primary-5 [overflow-wrap:anywhere]">
              {creator?.full_name}
            </h3>
          </div>
        </Link>

        <div className="w-full text-center">
          {socialLinks.length > 0 && (
            <div className="mt-3 flex flex-wrap items-center justify-center gap-3">
              {socialLinks.map(({ key, icon, href }) => (
                <a className="shrink-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary-5" key={key} target="_blank" rel="noopener noreferrer" href={href} aria-label={t(`COMMON.SOCIAL_${key.replace("_link", "").toUpperCase()}`)}>
                  <RemoteImage
                    src={icon}
                    alt={""}
                    width={31}
                    height={31}
                    className={"w-6 h-6"}
                  />
                </a>
              ))}
            </div>
          )}
        </div>

        {/* A private opportunity is reachable only by its link, so the
            creator gets a way to hand it out. */}
        {isCreator && !data.is_public && (
          <button
            type="button"
            onClick={() => handleShare(data.registration_link || "", t)}
            className="mt-5 flex items-center text-primary-200 font-medium"
          >
            <span className="mr-1 flex gap-2 text-primary-5 items-center text-sm md:text-base font-bold">
              <IoIosShareAlt className="w-6 h-6" />
              {t("COMMON.SHARE_OPPORTUNITY")}
            </span>
          </button>
        )}
        {children}
      </div>
    </div>
  );
}
