// Aria editor — Cronologia versioni: slide-over con badge provenienza + ripristino.
// Dati reali: GET /assistants/{thread}/revisions all'apertura;
// ripristino via POST /assistants/{thread}/revisions/{version}/restore.
const { Badge, Button, IconButton, Avatar, Icon, Banner } = window.AriaDesignSystem_af77ab;

function ProvenanceBadge({ source }) {
  return source === "llm"
    ? <Badge tone="info">AI</Badge>
    : <Badge tone="accent">umano</Badge>;
}

// Props:
//   open, onClose
//   thread          → assistente di cui leggere/ripristinare le revisioni (null per bozze non salvate)
//   currentVersion  → versione attuale (per evidenziare la riga corrente)
//   onRestored(res) → callback DOPO un ripristino riuscito (res = { thread }); il parent ricarica la config
function VersionHistory({ open, thread, currentVersion, onRestored, onClose }) {
  const [revisions, setRevisions] = React.useState(null); // null = caricamento; [] = nessuna
  const [error, setError] = React.useState(null);
  const [restoring, setRestoring] = React.useState(null); // version in corso di ripristino

  const load = React.useCallback(() => {
    if (!thread) { setRevisions([]); return undefined; }
    let alive = true;
    setRevisions(null);
    setError(null);
    window.AriaData.getRevisions(thread).then(
      (list) => { if (alive) setRevisions(list); },
      (err) => { if (alive) setError(err); }
    );
    return () => { alive = false; };
  }, [thread]);

  React.useEffect(() => { if (open) return load(); }, [open, load]);

  async function doRestore(rev) {
    setRestoring(rev.version);
    try {
      const res = await window.AriaData.restoreRevision(thread, rev.version);
      onClose();
      window.AriaToast && window.AriaToast({ tone: "success", title: `Ripristinata v${rev.version}`, body: `Configurazione riportata alla revisione di ${rev.changedBy}.` });
      onRestored && onRestored(res);
    } catch (err) {
      window.AriaToast && window.AriaToast({ tone: "danger", title: "Ripristino non riuscito", body: err.message || "Riprova." });
    } finally {
      setRestoring(null);
    }
  }

  if (!open) return null;
  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: "fixed", inset: 0, background: "rgba(31,42,40,0.32)", zIndex: 1200, display: "flex", justifyContent: "flex-end", animation: "aria-fade 180ms cubic-bezier(0.2,0,0,1)" }}
    >
      <aside style={{
        width: 440, maxWidth: "92vw", background: "var(--surface-card)", height: "100%",
        boxShadow: "var(--shadow-lg)", display: "flex", flexDirection: "column",
        animation: "aria-slide-in 260ms cubic-bezier(0.16,1,0.3,1)",
      }}>
        <header style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <Icon name="history" size={20} color="var(--text-muted)" />
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, flex: 1 }}>
            <span style={{ font: "var(--text-h3)", color: "var(--text-strong)" }}>Cronologia versioni</span>
            <span style={{ fontSize: 12, color: "var(--text-muted)" }}>
              {revisions == null ? "Caricamento…" : `${revisions.length} revisioni · attuale v${currentVersion}`}
            </span>
          </div>
          <IconButton label="Chiudi" onClick={onClose}><Icon name="x" size={18} /></IconButton>
        </header>

        <div style={{ overflowY: "auto", flex: 1, padding: 16 }}>
          {error ? (
            <Banner tone="danger" title="Impossibile caricare la cronologia" icon="alert-circle">
              <span>{error.message || "Errore inatteso."} </span>
              <Button variant="ghost" size="sm" iconLeft={<Icon name="refresh-cw" size={15} />} onClick={load}>Riprova</Button>
            </Banner>
          ) : revisions == null ? (
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "40px 0", color: "var(--text-muted)" }}>
              <Icon name="loader" size={18} color="var(--text-subtle)" />
              <span style={{ fontSize: 13 }}>Caricamento revisioni…</span>
            </div>
          ) : revisions.length === 0 ? (
            <div style={{ padding: "40px 16px", textAlign: "center", color: "var(--text-subtle)", fontSize: 13 }}>
              Nessuna revisione: l'assistente non è ancora stato salvato.
            </div>
          ) : (
            <ol style={{ listStyle: "none", margin: 0, padding: 0, position: "relative" }}>
              {revisions.map((r, i) => {
                const isCurrent = r.version === currentVersion;
                return (
                  <li key={r.version} style={{ position: "relative", paddingLeft: 26, paddingBottom: i === revisions.length - 1 ? 0 : 18 }}>
                    {/* timeline rail */}
                    {i !== revisions.length - 1 && (
                      <span style={{ position: "absolute", left: 8, top: 18, bottom: 0, width: 2, background: "var(--border-subtle)" }} />
                    )}
                    <span style={{
                      position: "absolute", left: 2, top: 5, width: 14, height: 14, borderRadius: "50%",
                      background: isCurrent ? "var(--primary)" : "var(--surface-card)",
                      border: `2px solid ${isCurrent ? "var(--primary)" : "var(--border-default)"}`,
                    }} />
                    <div style={{
                      border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)",
                      padding: 14, background: isCurrent ? "var(--sage-050)" : "var(--surface-card)",
                    }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                        <span style={{ font: "var(--fw-semibold) var(--fs-body)/1 var(--font-sans)", color: "var(--text-strong)" }}>v{r.version}</span>
                        <ProvenanceBadge source={r.source} />
                        {isCurrent && <Badge tone="success" dot>Attuale</Badge>}
                        <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--text-subtle)" }}>{r.changedAt}</span>
                      </div>
                      <p style={{ fontSize: 13, color: "var(--text-body)", marginBottom: 10 }}>{r.note}</p>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <Avatar name={r.changedBy} tone={r.source === "llm" ? "bot" : "sky"} size="sm" />
                        <span style={{ fontSize: 12, color: "var(--text-muted)", flex: 1 }}>{r.changedBy}</span>
                        {!isCurrent && (
                          <Button variant="ghost" size="sm" disabled={restoring != null}
                            iconLeft={<Icon name={restoring === r.version ? "loader" : "rotate-ccw"} size={15} />}
                            onClick={() => doRestore(r)}>Ripristina</Button>
                        )}
                      </div>
                    </div>
                  </li>
                );
              })}
            </ol>
          )}
        </div>
      </aside>
      <style>{`@keyframes aria-slide-in { from { transform: translateX(24px); opacity: 0; } }
        @media (prefers-reduced-motion: reduce) { aside { animation: none !important; } }`}</style>
    </div>
  );
}

Object.assign(window, { VersionHistory });
