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

function buildLabels(switches, selected) {
  const out = {};
  for (const sw of switches || []) {
    const currentId = selected?.[sw.id];
    const opt = sw?.opcje?.find((op) => String(op.id) === String(currentId));
    if (opt) out[sw.id] = opt.nazwa;
  }
  return out;
}

export default function OffersSwitches({ switches = [] }) {
  const initialSelected = useMemo(() => {
    const init = {};
    for (const sw of switches) {
      if (!sw?.id) continue;
      if (sw.domyslny != null) init[sw.id] = sw.domyslny;
      else if (sw.opcje?.length) init[sw.id] = sw.opcje[0].id;
    }
    return init;
  }, [switches]);

  const [selected, setSelected] = useState(initialSelected);

  useEffect(() => {
    setSelected(initialSelected);
  }, [initialSelected]);

  useEffect(() => {
    const labels = buildLabels(switches, selected);

    window.fuzSwitchState = { selected, labels };

    window.dispatchEvent(
      new CustomEvent("fuz:switch-change", {
        detail: { id: null, value: null, selected, labels },
      }),
    );
  }, [switches, selected]);

  const handleClick = (id, value) => {
    setSelected((prev) => {
      const next = { ...prev, [id]: value };
      const labels = buildLabels(switches, next);

      window.fuzSwitchState = { selected: next, labels };

      window.dispatchEvent(
        new CustomEvent("fuz:switch-change", {
          detail: { id, value, selected: next, labels },
        }),
      );

      return next;
    });
  };

  if (!Array.isArray(switches) || !switches.length) return null;

  return (
    <div class="f-switches-wrapper">
      {switches.map((sw) => (
        <div class="f-switch-group" key={sw.id}>
          {/* (opcjonalnie) etykieta */}
          {/* <div class="f-switch-label">{sw.etykieta}</div> */}
          {sw.opcje?.map((op) => (
            <button
              key={`${sw.id}:${op.id}`}
              type="button"
              class={`f-switch ${
                String(selected?.[sw.id]) === String(op.id) ? "active" : ""
              }`}
              onClick={() => handleClick(sw.id, op.id)}
              title={sw.title}
            >
              {op.nazwa}
            </button>
          ))}
        </div>
      ))}
    </div>
  );
}
