"use client";

import { useEffect, useState } from "react";
import { ChevronDown, Trophy } from "lucide-react";
import { normalizeMediaUrl } from "@/lib/media-url";

export type WinnerEntry = { prize: string; code: string };

type Props = {
  title: string;
  imageUrl?: string;
  prizes: WinnerEntry[];
  sectionId?: string;
  badge?: string;
  /** Cerrada al cargar para no distraer del sorteo activo */
  defaultExpanded?: boolean;
};

export default function DrawResultsAccordion({
  title,
  imageUrl,
  prizes,
  sectionId = "resultados",
  badge = "SORTEO",
  defaultExpanded = false,
}: Props) {
  const [expanded, setExpanded] = useState(defaultExpanded);


  // Si llegan desde el footer (#resultados / #resultados-2), abrir sola
  useEffect(() => {
    const openFromHash = () => {
      if (window.location.hash === `#${sectionId}`) {
        setExpanded(true);
        window.setTimeout(() => {
          document.getElementById(sectionId)?.scrollIntoView({ behavior: "smooth", block: "start" });
        }, 150);
      }
    };
    openFromHash();
    window.addEventListener("hashchange", openFromHash);
    return () => window.removeEventListener("hashchange", openFromHash);
  }, [sectionId]);

  const validPrizes = prizes.filter((p) => p.code?.trim());
  if (validPrizes.length === 0) return null;

  const imgSrc = normalizeMediaUrl(imageUrl);

  return (
    <section id={sectionId} className="mx-auto max-w-6xl scroll-mt-24 px-4 py-8 md:py-10">
      <div
        className={`overflow-hidden rounded-xl border transition-colors ${
          expanded
            ? "border-brand-purple/30 bg-white shadow-lg"
            : "border-slate-200 bg-white hover:border-brand-purple/40"
        }`}
      >
        {/* Cabecera — siempre visible, plegable */}
        <button
          type="button"
          onClick={() => setExpanded((v) => !v)}
          aria-expanded={expanded}
          aria-controls={`${sectionId}-panel`}
          className="flex w-full items-center justify-between gap-4 px-5 py-4 text-left transition hover:bg-brand-soft md:px-6 md:py-5"
        >
          <div className="flex min-w-0 flex-1 items-center gap-3 md:gap-4">
            <Trophy
              className={`h-5 w-5 shrink-0 md:h-6 md:w-6 ${expanded ? "text-brand-purple" : "text-brand-muted"}`}
            />
            <div className="min-w-0">
              <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-brand-purple md:text-xs">
                {badge}
              </p>
              <p
                className="truncate font-serif text-base font-bold text-brand-ink md:text-lg"
              >
                {title}
              </p>
            </div>
            <span className="hidden shrink-0 rounded-full border border-slate-200 bg-brand-soft px-3 py-1 text-xs text-brand-muted sm:inline">
              {validPrizes.length} ganador{validPrizes.length !== 1 ? "es" : ""}
            </span>
          </div>
          <span className="flex shrink-0 items-center gap-2 text-xs text-brand-muted">
            <span className="hidden sm:inline">{expanded ? "Ocultar" : "Ver ganadores"}</span>
            <ChevronDown
              className={`h-5 w-5 text-brand-purple transition-transform duration-300 ${expanded ? "rotate-180" : ""}`}
            />
          </span>
        </button>

        {/* Contenido — toda la sección se expande/contrae */}
        <div
          id={`${sectionId}-panel`}
          className="overflow-hidden transition-[max-height,opacity] duration-500 ease-in-out"
          style={{
            maxHeight: expanded ? "2400px" : "0px",
            opacity: expanded ? 1 : 0,
          }}
          aria-hidden={!expanded}
        >
          <div className="border-t border-slate-200">
            <div className={`grid grid-cols-1 ${imgSrc ? "lg:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]" : ""}`}>
              {imgSrc && (
                <div className="relative hidden min-h-[220px] overflow-hidden lg:block lg:min-h-[320px]">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={imgSrc}
                    alt=""
                    className="absolute inset-0 h-full w-full object-cover object-center"
                  />
                </div>
              )}

              <div className="max-h-[min(60vh,420px)] overflow-y-auto">
                <ul className="divide-y divide-slate-100">
                  {validPrizes.map((row, idx) => (
                    <li
                      key={`${row.code}-${idx}`}
                      className="flex flex-col gap-1 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-4 md:px-6"
                    >
                      <span className="font-medium text-brand-ink">{row.prize}</span>
                      <span className="font-mono text-sm font-bold tracking-wider text-brand-purple sm:text-base">
                        {row.code}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            <div className="border-t border-slate-200 px-5 py-4 md:px-6">
              <a
                href="/buscador"
                className="inline-flex items-center justify-center rounded-full bg-brand-gradient px-7 py-2.5 text-sm font-bold text-white transition hover:opacity-90"
              >
                Verificar mi boleto
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
