/**
 * DownloadProjectButton.tsx — S363-Blueprint: Final Artifact
 *
 * "Instant Download ZIP" — l'ultima frase deve sempre consegnare un artefatto.
 * Mostra un bottone compatto che scarica il VFS come ZIP.
 * Appare in fondo al messaggio finale quando ci sono file nel VFS.
 */
import { useState, memo } from "react";
import { makeTimedSignal } from "@/lib/agentLoop/networkConstants";

interface Props {
  conversationId: string;
  fileCount?: number;
}

export const DownloadProjectButton = memo(function DownloadProjectButton({ conversationId, fileCount }: Props) {
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);

  const handleDownload = async () => {
    setLoading(true);
    try {
      const backendUrl = (window as Window & { __AGENTE_BACKEND_URL?: string }).__AGENTE_BACKEND_URL ||
        import.meta.env.VITE_BACKEND_URL ||
        "https://agente-ai.pages.dev";
      const url = `${backendUrl}/api/project/export?conversation_id=${encodeURIComponent(conversationId)}`;
      // S485-fix: AbortSignal.timeout evita hang infinito se il backend non risponde
      const res = await fetch(url, { signal: makeTimedSignal(30_000) });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const blob = await res.blob();
      const _zipFilename = `project_${conversationId.slice(0, 8)}.zip`;
      const _zipUrl = URL.createObjectURL(blob);
      // S725-iOS-FIX: a.click() dopo fetch bloccato su Safari iOS — delega a DownloadQueue
      window.dispatchEvent(new CustomEvent("agent:download-ready", { detail: { url: _zipUrl, filename: _zipFilename } }));
      setDone(true);
      setTimeout(() => setDone(false), 3000);
    } catch (e) {
      console.error("Download failed:", e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={handleDownload}
      disabled={loading}
      title={`Scarica progetto (${fileCount ?? "?"} file) come ZIP`}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "5px 12px",
        borderRadius: 3,  /* Replit square */
        border: done
          ? "1px solid rgba(74,222,128,0.40)"
          : "1px solid rgba(96,165,250,0.28)",
        background: done
          ? "rgba(74,222,128,0.08)"
          : "rgba(96,165,250,0.06)",
        color: done ? "rgba(74,222,128,0.90)" : "rgba(96,165,250,0.85)",
        cursor: loading ? "wait" : "pointer",
        fontSize: "0.68rem",
        fontFamily: "var(--font-mono, ui-monospace, monospace)",
        fontWeight: 600,
        letterSpacing: "0.03em",
        transition: "all 0.15s",
        opacity: loading ? 0.65 : 1,
        marginTop: 6,
      }}
    >
      {loading ? (
        <>
          <svg width={10} height={10} viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"
            style={{ animation: "spin 1s linear infinite" }}>
            <path d="M21 12a9 9 0 1 1-6.219-8.56" />
          </svg>
          Preparazione…
        </>
      ) : done ? (
        <>
          <svg width={10} height={10} viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
            <polyline points="20 6 9 17 4 12" />
          </svg>
          Scaricato!
        </>
      ) : (
        <>
          <svg width={10} height={10} viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
          {fileCount ? `Download ZIP (${fileCount} file)` : "Download ZIP"}
        </>
      )}
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </button>
  );
});
export default DownloadProjectButton;
