/**
 * Trouve-KA — galerie de résultats images
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useState } from "react";
import type { SearchResult } from "@/lib/types";

function GalleryTile({ result }: { result: SearchResult }) {
  const [broken, setBroken] = useState(false);
  if (!result.image || broken) return null;

  const domain = result.domain.replace(/^www\./, "");

  return (
    <a
      href={result.url}
      target="_blank"
      rel="noopener noreferrer"
      className="group block rounded-card focus-visible:outline focus-visible:outline-2 focus-visible:outline-green"
    >
      <span className="block overflow-hidden rounded-card border-[1.5px] border-ink bg-surface shadow-[3px_3px_0_rgba(20,24,20,0.1)] transition-[transform,box-shadow] duration-150 group-hover:-translate-y-0.5 group-hover:shadow-[5px_5px_0_rgba(20,24,20,0.55)]">
        <img
          src={result.image}
          alt={result.title}
          loading="lazy"
          referrerPolicy="no-referrer"
          onError={() => setBroken(true)}
          className="aspect-[4/3] w-full bg-surface-2 object-cover"
        />
      </span>
      <span className="mt-2 block truncate text-[13px] font-medium leading-snug text-ink group-hover:underline group-hover:decoration-lime group-hover:decoration-2 group-hover:underline-offset-2">
        {result.title}
      </span>
      <span className="gk-mono block truncate text-[10.5px] font-bold uppercase tracking-[0.08em] text-green">
        {domain}
      </span>
    </a>
  );
}

/** Grille de résultats en mode galerie (onglet Images). */
export function ImageGallery({ results }: { results: SearchResult[] }) {
  return (
    <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 md:grid-cols-4">
      {results.map((result) => (
        <GalleryTile key={result.url} result={result} />
      ))}
    </div>
  );
}

/** Skeleton du mode galerie, aux mêmes dimensions que les tuiles. */
export function GallerySkeleton() {
  return (
    <div
      aria-hidden="true"
      className="grid animate-pulse grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 md:grid-cols-4"
    >
      {Array.from({ length: 12 }, (_, i) => (
        <div key={i}>
          <div className="aspect-[4/3] w-full rounded-card bg-[rgba(20,24,20,0.07)]" />
          <div className="mt-2 h-3.5 w-5/6 rounded bg-[rgba(20,24,20,0.07)]" />
          <div className="mt-1 h-3 w-1/2 rounded bg-[rgba(20,24,20,0.07)]" />
        </div>
      ))}
    </div>
  );
}
