"use client";

import { useState } from "react";
import styles from "./ScreenshotGallery.module.css";

interface ScreenshotGalleryProps {
  screenshotsJson: string;
  appName: string;
}

export default function ScreenshotGallery({ screenshotsJson, appName }: ScreenshotGalleryProps) {
  const [activeIdx, setActiveIdx] = useState(0);

  // Parse screenshots
  const screenshots: string[] = (() => {
    try {
      return JSON.parse(screenshotsJson);
    } catch {
      return [];
    }
  })();

  if (screenshots.length === 0) {
    return (
      <div className={`${styles.galleryPlaceholder} glass-panel`}>
        <span className={styles.placeholderIcon}>🖼️</span>
        <p>No screenshots available for this application.</p>
      </div>
    );
  }

  return (
    <div className={styles.galleryWrapper}>
      {/* Main Large Display */}
      <div className={`${styles.mainDisplay} glass-panel`}>
        <img
          src={screenshots[activeIdx]}
          alt={`${appName} Screenshot ${activeIdx + 1}`}
          className={styles.mainImage}
          loading="eager"
        />
      </div>

      {/* Thumbnails */}
      {screenshots.length > 1 && (
        <div className={styles.thumbnailList}>
          {screenshots.map((url, idx) => (
            <button
              key={idx}
              onClick={() => setActiveIdx(idx)}
              className={`${styles.thumbBtn} ${activeIdx === idx ? styles.activeThumb : ""} glass-panel`}
              aria-label={`View Screenshot ${idx + 1}`}
            >
              <img src={url} alt={`${appName} Thumb ${idx + 1}`} className={styles.thumbImage} />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
