import { useState } from "preact/hooks";
import FuzMarkdown from "./Markdown.jsx";

import OffersSwitches from "./Offers/OffersSwitches.jsx";
import OffersTable from "./Offers/OffersTable.jsx";
import OffersExtraServices from "./Offers/OffersExtraServices.jsx";
import "../styles/offers/offers-main.css";

export default function InternetOffersIsland({ data }) {
  const switches = data.przelaczniki ?? [];
  const features = data.funkcje ?? [];
  const plans = data.plany ?? [];
  const extraServices = data.uslugi_dodatkowe ?? [];

  const initialSelected = {};
  switches.forEach((sw) => {
    initialSelected[sw.id] = sw.domyslny;
  });

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

  const toggleService = (id) =>
    setOpenServiceId((prev) => (prev === id ? null : id));

  const handleSwitchClick = (switchId, optionId) =>
    setSelected((prev) => ({ ...prev, [switchId]: optionId }));

  return (
    <section class="fuz-offers-section">
      <div class="fuz-offers-container">
        {data.opis_gorny && (
          <div class="fuz-offers-description">
            <FuzMarkdown text={data.opis_gorny} />
          </div>
        )}

        <OffersSwitches
          switches={switches}
          selected={selected}
          onSwitch={handleSwitchClick}
        />

        <OffersTable
          switches={switches}
          selected={selected}
          plans={plans}
          features={features}
        />

        <OffersExtraServices
          extraServices={extraServices}
          openId={openServiceId}
          toggle={toggleService}
        />

        {data.opis_dolny && (
          <div class="fuz-offers-description">
            <FuzMarkdown text={data.opis_dolny} />
          </div>
        )}
      </div>
    </section>
  );
}
