"use client";

import React, { ReactNode } from "react";
import styles from "./Cta.module.css";

type CtaVariant = "solid" | "outline" | "toggle" | "white";
type CtaIcon = "arrow" | "close";

type CtaBaseProps = {
  label: ReactNode;
  variant?: CtaVariant;
  icon?: CtaIcon;
  className?: string;
  onClick?: (event: any) => void;
};

type CtaSpanProps = CtaBaseProps &
  Omit<React.HTMLAttributes<HTMLSpanElement>, "onClick"> & {
    as?: "span";
  };

type CtaButtonProps = CtaBaseProps &
  Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onClick"> & {
    as: "button";
  };

type CtaProps = CtaSpanProps | CtaButtonProps;

const icons: Record<CtaIcon, ReactNode> = {
  arrow: (
    <path d="M647-440H160v-80h487L423-744l57-56 320 320-320 320-57-56 224-224Z" />
  ),
  close: (
    <path d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z" />
  ),
};

const Cta = ({
  label,
  variant = "solid",
  icon = "arrow",
  className = "",
  as = "span",
  ...rest
}: CtaProps) => {
  const classes = [styles.cta, styles[variant], className].join(" ").trim();

  const content = (
    <>
      <span className={styles.label}>{label}</span>
      <svg
        className={`${styles.icon} ${
          icon === "arrow" ? styles.animated : ""
        }`.trim()}
        xmlns="http://www.w3.org/2000/svg"
        height="24"
        viewBox="0 -960 960 960"
        width="24"
      >
        {icons[icon]}
      </svg>
    </>
  );

  if (as === "button") {
    const buttonProps = rest as React.ButtonHTMLAttributes<HTMLButtonElement>;

    return (
      <button
        type={buttonProps.type || "button"}
        className={classes}
        {...buttonProps}
      >
        {content}
      </button>
    );
  }

  return (
    <span
      className={classes}
      {...(rest as React.HTMLAttributes<HTMLSpanElement>)}
    >
      {content}
    </span>
  );
};

export default Cta;
