/* Right-side panel: lists Firestore version snapshots for the current diagram.
   Auto-snapshots render muted; manual checkpoints render with the user's message. */
{
  const { useEffect, useMemo, useState } = React;

  function fmtRelative(then, now) {
    if (!then) return "just now";
    const s = Math.max(0, Math.round((now - then) / 1000));
    if (s < 45) return s <= 5 ? "just now" : `${s}s ago`;
    const m = Math.round(s / 60);
    if (m < 60) return `${m}m ago`;
    const h = Math.round(m / 60);
    if (h < 24) return `${h}h ago`;
    const d = Math.round(h / 24);
    if (d < 7) return `${d}d ago`;
    return new Date(then).toLocaleDateString();
  }

  function tsToMillis(t) {
    if (!t) return 0;
    if (typeof t.toMillis === "function") return t.toMillis();
    if (typeof t.seconds === "number") return t.seconds * 1000;
    if (t instanceof Date) return t.getTime();
    return 0;
  }

  function VAvatar({ photoURL, name }) {
    const initial = (name || "?").trim().charAt(0).toUpperCase() || "?";
    if (photoURL) {
      return <img className="v-avatar" src={photoURL} alt="" referrerPolicy="no-referrer" />;
    }
    return <div className="v-avatar-fallback">{initial}</div>;
  }

  function VersionsPanel({ versions, loading, currentVersionId, onPreview, onRestore, canRestore, onClose, previewVersionId }) {
    const [tick, setTick] = useState(0);
    useEffect(() => {
      const t = setInterval(() => setTick(x => x + 1), 30000);
      return () => clearInterval(t);
    }, []);
    const now = useMemo(() => Date.now(), [tick, versions]);

    return (
      <div className="panel versions-panel">
        <div className="panel-head">
          <Icon.history />
          <h2>Versions</h2>
          <span className="count">{versions.length || 0}</span>
          <button className="iconbtn" onClick={onClose} title="Hide panel" style={{ marginLeft: 8 }}>
            <Icon.close />
          </button>
        </div>
        <div className="versions-list">
          {loading && versions.length === 0 ? (
            <div className="versions-empty"><Icon.spinner /> loading…</div>
          ) : versions.length === 0 ? (
            <div className="versions-empty">No versions yet. Edits will be auto-snapshotted every few minutes.</div>
          ) : versions.map(v => {
            const created = tsToMillis(v.createdAt);
            const isCurrent = v.id === currentVersionId || v.id === previewVersionId;
            const cls = `version-row ${v.isAuto ? "auto" : ""} ${isCurrent ? "current" : ""}`;
            return (
              <div key={v.id} className={cls} onClick={() => onPreview && onPreview(v)}>
                <VAvatar photoURL={v.authorPhotoURL} name={v.authorName} />
                <div className="v-main">
                  <div className="v-message" title={v.isAuto ? "auto-snapshot" : v.message}>
                    {v.isAuto ? "auto-snapshot" : (v.message || "checkpoint")}
                  </div>
                  <div className="v-meta">
                    <span>{v.authorName}</span>
                    <span>·</span>
                    <span title={created ? new Date(created).toLocaleString() : ""}>{fmtRelative(created, now)}</span>
                  </div>
                </div>
                <div className="v-actions">
                  {canRestore && (
                    <button
                      className="v-restore"
                      onClick={(e) => { e.stopPropagation(); onRestore && onRestore(v); }}
                      title="Replace working copy with this version"
                    >
                      restore
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  window.VersionsPanel = VersionsPanel;
}
