import { useState } from "preact/hooks";
import { useStripFocus } from "../hooks/useStripFocus";
import { addToList } from "../lib/api";
import { text } from "../lib/config";
import { Html } from "./Html";

/**
 * "You may also compare": related products under the shopper's own list
 * (`data.related`, empty for shared links or a full list). Adding goes
 * through `addToList()`; the table then refetches on `pcfw:added`.
 */
export function RelatedStrip({ data }) {
  const [busy, setBusy] = useState(0);
  const items = (data && data.related) || [];
  const shown = items.length > 0;
  const { headingRef, afterAdd } = useStripFocus(shown);

  if (!shown) {
    return null;
  }

  const add = async (id) => {
    setBusy(id);
    try {
      if (await addToList(id)) {
        afterAdd();
      }
    } finally {
      setBusy(0);
    }
  };

  return (
    <section className="pcfw-related" aria-labelledby="pcfw-related-title">
      <h3
        ref={headingRef}
        id="pcfw-related-title"
        className="pcfw-related__title"
        tabIndex={-1}
      >
        {text("relatedTitle", "You may also compare")}
      </h3>
      <ul className="pcfw-related__list">
        {items.map((item) => (
          <li key={item.id} className="pcfw-related__item">
            <img
              className="pcfw-related__image"
              src={item.image}
              alt=""
              loading="lazy"
            />
            <a className="pcfw-related__link" href={item.permalink}>
              <Html
                className="pcfw-related__name"
                html={item.name}
                id={`pcfw-related-${item.id}`}
              />
            </a>
            <Html className="pcfw-related__price" html={item.price_html} />
            <button
              type="button"
              id={`pcfw-related-add-${item.id}`}
              aria-labelledby={`pcfw-related-add-${item.id} pcfw-related-${item.id}`}
              className="pcfw-related__add"
              disabled={busy === item.id}
              aria-busy={busy === item.id}
              onClick={() => add(item.id)}
            >
              <svg
                aria-hidden="true"
                width="14"
                height="14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2.25"
                stroke-linecap="round"
              >
                <path d="M12 5v14M5 12h14" />
              </svg>
              {text("addToCompare", "Add to compare")}
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}
