"use client";

import { usePathname } from "next/navigation";
import { useMemo } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { faPhone } from "@fortawesome/free-solid-svg-icons";
import { faWhatsapp } from "@fortawesome/free-brands-svg-icons";
import { useHome } from "@/context/helpers/Home/HomeContext";
import ContactWidget from "./ContactWidget";

/**
 * Phone (mobile only) and WhatsApp floating buttons on home page.
 * Same logic, position and data as markattynextcode CommonLayout section.
 */
export default function ContactWidgets() {
  const pathname = usePathname();
  const { t } = useTranslation("header");
  const { whatsappNumber } = useHome();

  const isHomePage = pathname === "/" || pathname === "/home";

  const whatsappUrl = useMemo(() => {
    // Use WhatsApp number if set
    const raw = whatsappNumber;
    const number = raw?.trim().replace(/\s/g, "");
    const normalized = number?.startsWith("+") ? number : `+${number}`;
    return `https://api.whatsapp.com/send?phone=${normalized}&text=${encodeURIComponent("I'm interested in ...")}`;
  }, [whatsappNumber]);

  if (!isHomePage) return null;
  if (!whatsappNumber) return null;

  const content = (
    <>
      <ContactWidget
        className="whatsapp"
        label={t("contactWidget.whatsappUs")}
        url={whatsappUrl}
        icon={faWhatsapp}
        requireScroll={false}
      />
    </>
  );

  // Portal to document.body so no layout overflow/stacking can hide the buttons
  if (typeof document !== "undefined" && document.body) {
    return createPortal(content, document.body);
  }
  return content;
}
