"use client";

import { useEffect, useState, type ReactNode } from "react";

import { Button } from "@/components/ui/button";
import {
  WHATSAPP_STORE_NAME,
  buildWhatsAppApiHref,
} from "@/components/shop/whatsapp-shared";

type Props = {
  /** Short phrase included in the pre-filled WhatsApp message (section topic). */
  topic: string;
  className?: string;
  children: ReactNode;
};

export default function SectionWhatsAppCta({ topic, className, children }: Props) {
  const [href, setHref] = useState<string>(() =>
    buildWhatsAppApiHref(
      `Hi, I want to know more about ${topic} on ${WHATSAPP_STORE_NAME}. ${WHATSAPP_STORE_NAME}`,
    ),
  );

  useEffect(() => {
    const url = typeof window !== "undefined" ? window.location.href : "";
    const text = `Hi, I want to know more about ${topic} on ${WHATSAPP_STORE_NAME}.${url ? ` ${url}` : ""} ${WHATSAPP_STORE_NAME}`;
    setHref(buildWhatsAppApiHref(text));
  }, [topic]);

  return (
    <Button asChild variant="link" className={className}>
      <a
        href={href}
        target="_blank"
        rel="noopener noreferrer"
        aria-label={`Contact ${WHATSAPP_STORE_NAME} on WhatsApp: ${topic}`}
      >
        {children}
      </a>
    </Button>
  );
}
