import { useEffect, useMemo, useState } from "preact/hooks";

function cleanPkgName(v) {
  const s = String(v || "").trim();
  if (!s) return null;
  if (s.length > 64) return null;
  return s;
}

function getNearestSectionEl(el) {
  return el?.closest?.("[data-addon-section]") ?? null;
}

export default function AddonChannelsGrid(props) {
  const packageName = cleanPkgName(props?.packageName);
  const fallbackImage = String(props?.fallbackImage || "").trim();
  const title = String(props?.title || "").trim();
  const aboveFold = props?.aboveFold === true;

  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const [items, setItems] = useState([]);

  const rootRef = useMemo(() => ({ current: null }), []);

  const channelsWithLogo = useMemo(() => {
    return (items || []).filter((x) => String(x?.logo_url || "").trim());
  }, [items]);

  async function load() {
    if (!packageName) return;
    setLoading(true);
    setErr("");
    try {
      const url = `/api/jambox/jambox-channels-package?package=${encodeURIComponent(
        packageName,
      )}`;
      const res = await fetch(url);
      const json = await res.json().catch(() => null);
      if (!res.ok || !json?.ok) throw new Error(json?.error || "FETCH_ERROR");
      setItems(Array.isArray(json.data) ? json.data : []);
    } catch (e) {
      setErr(String(e?.message || e));
      setItems([]);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [packageName]);

  useEffect(() => {
    const el = rootRef.current;
    const section = getNearestSectionEl(el);
    if (!section) return;

    const hasIcons = channelsWithLogo.length > 0;
    const hasFallback = !!fallbackImage;
    const hasMedia = hasIcons || hasFallback;

    section.setAttribute("data-has-media", hasMedia ? "1" : "0");
  }, [channelsWithLogo.length, fallbackImage]);

  const hasIcons = channelsWithLogo.length > 0;
  const visible = hasIcons ? channelsWithLogo.slice(0, 60) : [];

  return (
    <div ref={(el) => (rootRef.current = el)}>
      {hasIcons ? (
        <div class="f-channels-grid" aria-label={title || packageName || "Kanały"}>
          {visible.map((ch, idx) => {
            const logo = String(ch?.logo_url || "").trim();
            const name = String(ch?.name || "").trim();

            return (
              <div class="f-channel-item" title={name}>
                {logo ? (
                  <img
                    class="f-channel-logo"
                    src={logo}
                    alt=""
                    loading={aboveFold && idx < 12 ? "eager" : "lazy"}
                    decoding="async"
                  />
                ) : (
                  <div class="f-channel-logo-placeholder" />
                )}
                <div class="f-channel-label">{name}</div>
              </div>
            );
          })}
        </div>
      ) : fallbackImage ? (
        <img
          class="f-addon-fallback-image"
          src={fallbackImage}
          alt={title || packageName || ""}
          loading={aboveFold ? "eager" : "lazy"}
          decoding="async"
        />
      ) : (
        <div class="sr-only">
          {loading ? "Ładowanie kanałów" : err ? `Błąd: ${err}` : "Brak kanałów"}
        </div>
      )}
    </div>
  );
}
