"use client";

import { useState } from "react";

import MediaImage from "./MediaImage";

/**
 * Floor plans, one group per section, one plan visible at a time.
 *
 * A column of plans is not a page anyone reads; the design shows one and a tab
 * strip to reach the others. A group with a single tab renders without a strip.
 *
 * The grouping and the four-per-section split are decided in the backend — they
 * are facts about the content, and doing them here would mean two places
 * deciding what a "group" is.
 */
export default function FloorPlans({ groups }: { groups: any[] }) {
  if (!groups || groups.length === 0) {
    return null;
  }

  return (
    <>
      {groups.map((group, index) => (
        <FloorPlanGroup group={group} key={index} index={index} />
      ))}
    </>
  );
}

function FloorPlanGroup({ group, index }: { group: any; index: number }) {
  const [active, setActive] = useState(0);
  const tabs: any[] = group.tabs ?? [];

  return (
    <section className="project-floor-section">
      <div className="container">
        <h2 className="section-title">{group.title}</h2>

        <div className="floor-plans" data-tabs>
          {tabs.length > 1 ? (
            <div className="floor-plans__tabs" role="tablist">
              {tabs.map((tab, i) => (
                <button
                  key={i}
                  type="button"
                  role="tab"
                  className="floor-plans__tab"
                  aria-selected={active === i}
                  aria-controls={`plan-${index}-${i}`}
                  onClick={() => setActive(i)}
                >
                  {tab.title}
                </button>
              ))}
            </div>
          ) : null}

          {tabs.map((tab, i) => (
            <div
              className="floor-plans__panel"
              role="tabpanel"
              id={`plan-${index}-${i}`}
              key={i}
              hidden={active !== i}
            >
              {(tab.images ?? []).map((image: any, j: number) => (
                <MediaImage key={j} image={image} alt={tab.title} />
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
