import Markdown from "../../islands/Markdown.jsx";
import "../../styles/cards.css";

/**
 * @typedef {{ klucz: string, label: string, value: (string|number) }} PhoneParam
 * @typedef {{
 *   nazwa: string,
 *   widoczny?: boolean,
 *   popularny?: boolean,
 *   cena?: { wartosc: number, opis?: string },
 *   parametry?: PhoneParam[]
 * }} PhoneCard
 */

/**
 * @param {{ title?: string, description?: string, cards?: PhoneCard[] }} props
 */
export default function PhoneDbOffersCards({
  title = "",
  description = "",
  cards = [],
}) {
  const visibleCards = Array.isArray(cards) ? cards : [];

  return (
    <section class="f-offers">
      {title && <h2 class="f-section-header">{title}</h2>}
      <div>
        <Markdown text={description} />
      </div>
      {visibleCards.length === 0 ? (
        <p class="opacity-80">Brak dostępnych pakietów.</p>
      ) : (
        <div class={`f-offers-grid f-count-${visibleCards.length || 1}`}>
          {visibleCards.map((card) => (
            <PhoneOfferCard key={card.nazwa} card={card} />
          ))}
        </div>
      )}
    </section>
  );
}

function PhoneOfferCard({ card }) {
  const price = card?.cena?.wartosc ?? "";
  const priceDesc = card?.cena?.opis ?? "zł/mies.";

  const params = Array.isArray(card?.parametry) ? card.parametry : [];

  return (
    <div class={`f-card ${card.popularny ? "f-card-popular" : ""}`}>
      {card.popularny && <div class="f-card-badge">Najczęściej wybierany</div>}

      <div class="f-card-header">
        <div class="f-card-name">{card.nazwa}</div>
        <div class="f-card-price">
          {price.toFixed(2)} {priceDesc}
        </div>
      </div>

      <ul class="f-card-features">
        {params.map((p) => (
          <li class="f-card-row" key={p.klucz || p.label}>
            <span class="f-card-label">{p.label}</span>
            <span class="f-card-value">{p.value}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
