"use client";

import { useState } from "react";
import type { MediaResult } from "@/lib/types";

export function Results({
  media,
  onReset,
}: {
  media: MediaResult;
  onReset: () => void;
}) {
  const [imageFailed, setImageFailed] = useState(false);
  const showImage = Boolean(media.thumbnail) && !imageFailed;

  return (
    <article className="results" aria-live="polite">
      <div className="thumb-frame">
        {showImage ? (
          <img
            src={media.thumbnail}
            alt={media.title ? `Preview of ${media.title}` : "Preview of the retrieved TikTok media"}
            width={270}
            height={480}
            onError={() => setImageFailed(true)}
          />
        ) : (
          <div className="thumb-fallback">
            <svg viewBox="0 0 32 32" aria-hidden="true">
              <path d="M12 9v14l12-7-12-7z" fill="currentColor" />
            </svg>
            <span>No preview image</span>
          </div>
        )}
      </div>
      <div className="results-body">
        <h2>Ready to download</h2>
        {media.title ? <p className="media-title">{media.title}</p> : null}
        {media.author ? <p className="media-author">{media.author}</p> : null}
        <ul className="download-list">
          {media.downloads.map((item) => (
            <li key={`${item.label}-${item.url}`}>
              <a className="download-link" href={item.url}>
                <span>{item.label}</span>
                <span className="download-meta">
                  {item.quality ? <span>{item.quality}</span> : null}
                  {item.format !== "file" && item.format !== "image" ? <span>{item.format.toUpperCase()}</span> : null}
                </span>
              </a>
            </li>
          ))}
        </ul>
        <p className="fine-print">These links expire after a short time. If a file does not start, process the TikTok link again.</p>
        <button type="button" className="text-button" onClick={onReset}>
          Download another video
        </button>
      </div>
    </article>
  );
}
