import { useEffect, useState } from "preact/hooks";
import { getConfig, text } from "../lib/config";
import { copyText, shareUrl } from "../lib/share";

let counter = 0;

/**
 * "Send this comparison" card under the compare page table: the link to
 * copy. ID links are shown right away; short links are created on Copy.
 */
export function ShareCard({ products }) {
  const { share = {}, compare_url: page } = getConfig();
  const [url, setUrl] = useState("");
  const [status, setStatus] = useState("");
  const [id] = useState(() => `pcfw-share-url-${++counter}`);
  const key = products.map((p) => p.id).join(",");

  useEffect(() => {
    setUrl("");
    if (share.mode !== "short" && key) {
      shareUrl(key.split(",").map(Number)).then(setUrl);
    }
  }, [key, share.mode]);

  if (share.enabled === false || !page || !products.length) {
    return null;
  }

  const copy = async () => {
    const link = url || (await shareUrl(key.split(",").map(Number)));
    setUrl(link);
    setStatus(
      (await copyText(link))
        ? text("linkCopied", "Link copied")
        : text("copyThis", "Copy this link:"),
    );
  };

  return (
    <section className="pcfw-share-card" aria-labelledby={`${id}-title`}>
      <div className="pcfw-share-card__text">
        <h3 id={`${id}-title`} className="pcfw-share-card__title">
          {text("shareCardTitle", "Send this comparison")}
        </h3>
        <p className="pcfw-share-card__sub">
          {text("shareCardText", "Anyone with the link sees these products.")}
        </p>
      </div>
      <div className="pcfw-share-card__form">
        {url && (
          <>
            <label htmlFor={id} className="pcfw-screen-reader-text">
              {text("shareLink", "Share link")}
            </label>
            <input
              id={id}
              className="pcfw-share-card__url"
              readOnly
              value={url}
              onFocus={(e) => e.currentTarget.select()}
            />
          </>
        )}
        <button type="button" className="pcfw-share-card__copy" onClick={copy}>
          {text("copyLink", "Copy link")}
        </button>
        <span className="pcfw-share-card__status" role="status">
          {status}
        </span>
      </div>
    </section>
  );
}
