/* Shown on sign-in when both this device and the cloud have real (non-default)
   workspace data. The user picks how to reconcile — cloud wins, local wins,
   or merge both. After this, sync runs silently. */

function ConflictModal({ local, cloud, onResolve }) {
  const localCount = local?.trees?.length || 0;
  const cloudCount = cloud?.trees?.length || 0;
  const localNodes = (local?.trees || []).reduce((n, t) => n + Object.keys(t.nodes || {}).length, 0);
  const cloudNodes = (cloud?.trees || []).reduce((n, t) => n + Object.keys(t.nodes || {}).length, 0);
  const fmt = (n, suffix) => `${n} ${suffix}${n === 1 ? "" : "s"}`;

  return (
    <div className="conflict-overlay" onMouseDown={(e) => e.stopPropagation()}>
      <div className="conflict-card" role="dialog" aria-modal="true">
        <div className="conflict-head">
          <div className="conflict-title">Sync conflict</div>
          <div className="conflict-sub">
            You have trees on this device <em>and</em> trees in your account. Pick one — or merge both.
          </div>
        </div>

        <div className="conflict-grid">
          <button className="conflict-choice" onClick={() => onResolve("cloud")}>
            <Icon name="cloud" size={16} />
            <div className="conflict-choice-title">Use cloud</div>
            <div className="conflict-choice-meta">{fmt(cloudCount, "tree")} · {fmt(cloudNodes, "node")}</div>
            <div className="conflict-choice-sub">This device's local trees will be discarded.</div>
          </button>

          <button className="conflict-choice" onClick={() => onResolve("local")}>
            <Icon name="upload" size={16} />
            <div className="conflict-choice-title">Use local</div>
            <div className="conflict-choice-meta">{fmt(localCount, "tree")} · {fmt(localNodes, "node")}</div>
            <div className="conflict-choice-sub">Account trees will be overwritten.</div>
          </button>

          <button className="conflict-choice primary" onClick={() => onResolve("merge")}>
            <Icon name="duplicate" size={16} />
            <div className="conflict-choice-title">Merge both</div>
            <div className="conflict-choice-meta">Up to {localCount + cloudCount} trees</div>
            <div className="conflict-choice-sub">Combine all trees from both. Duplicates by ID resolve to the most recently edited.</div>
          </button>
        </div>

        <div className="conflict-foot">
          Nothing is deleted until you choose. Auto-sync starts after this.
        </div>
      </div>
    </div>
  );
}

window.ConflictModal = ConflictModal;
