// right-column.jsx - RightColumn component
// Loaded after sortof-shared.jsx; defines globals that sortof-app.jsx references.

// Shows when a user has sorted many mods that don't belong to the active build,
// suggesting they switch builds and re-sort. Only counts remove-only mismatches
// (no swap available); those can't be fixed any other way.
function SwitchBuildBanner({ warnings, pzBuild, onSwitchBuildAndSort }) {
  const otherBuild = pzBuild === 'B41' ? 'B42' : 'B41';
  const removeOnly = (warnings || []).filter(w =>
    w.tag === 'build-mismatch' &&
    Array.isArray(w.actions) &&
    !w.actions.some(a => a.type === 'swap-wsid')
  );
  const totalMods = (D.SORTED_ORDER || []).length;
  if (removeOnly.length < 5 || totalMods === 0 || removeOnly.length / totalMods < 0.2) return null;
  return (
    <div className="switch-build-banner" role="alert">
      <span className="switch-build-msg">
        {removeOnly.length} mods are {pzBuild}-incompatible with no {pzBuild} equivalent:
        are you on the wrong build?
      </span>
      <button
        type="button"
        className="switch-build-btn"
        onClick={() => onSwitchBuildAndSort && onSwitchBuildAndSort(otherBuild)}
      >switch to {otherBuild} &amp; re-sort</button>
    </div>
  );
}

function RightColumn({ state, counts, progress, emptyVariant, successVariant, modTableDefault, pzBuild, setPzBuild, branchSelections, onToggleBranch, expandedWsids, onToggleExpansion, inputWsids, onAddWsid, onPickBranch, onSwapWsid, onRemoveWsid, onAutoFixAddDeps, onAutoFixSwaps, onAutoFixRemoves, onRetry, onSwitchBuildAndSort, inputWsidList, unknownWsids, failedWsids, diffOpen, setDiffOpen, activeJobId, isShortlinkView, onDismissShortlink }) {
  const isTerminalDone = state === 'success' || state === 'done';
  const isInflightPartial = state === 'partial' || state === 'queued' || state === 'draining';
  const showWarnings = isTerminalDone || isInflightPartial;
  const showOutputs = isTerminalDone || isInflightPartial;

  const _allWarnings = [...(D.WARNINGS || []), ...unknownRemovalWarnings(unknownWsids), ...failedIndexWarnings(failedWsids)];

  return (
    <>
      {showWarnings && (
        <>
          <SwitchBuildBanner warnings={_allWarnings} pzBuild={pzBuild} onSwitchBuildAndSort={onSwitchBuildAndSort} />
          <AutoFixBar
            items={_allWarnings}
            inputWsids={inputWsids}
            onAddDeps={onAutoFixAddDeps}
            onFixMismatches={onAutoFixSwaps}
            onRemoveIncorrect={onAutoFixRemoves}
          />
          <Warnings
            items={_allWarnings}
            defaultOpen={isTerminalDone}
            inputWsids={inputWsids}
            onAddWsid={onAddWsid}
            onPickBranch={onPickBranch}
            onSwapWsid={onSwapWsid}
            onRemoveWsid={onRemoveWsid}
            onToggleBranch={onToggleBranch}
          />
        </>
      )}

      {state === 'cold' && (
        <div className="cold-banner">
          <span className="err-tag"><span aria-hidden="true">❄</span> cold</span>
          <div className="err-msg">
            indexing <span className="cold-count">{counts.queued} {counts.queued === 1 ? 'mod' : 'mods'}</span> we haven't seen before. try again in ~30s. or don't, we're not your boss.
          </div>
        </div>
      )}

      {state === 'error' && (() => {
        const warns = (D.WARNINGS || []);
        const retryWarn = [...warns].reverse().find(w => w.tag === 'retry');
        const reason = retryWarn ? retryWarn.msg : 'something failed - check warnings above';
        const hasCached = (D.MOD_DB || []).length > 0;
        return (
          <div className="err-banner">
            <span className="err-tag"><span aria-hidden="true">⚠</span> err</span>
            <div className="err-msg">
              {reason}{hasCached ? ' · cached results below still valid' : ''}
              <div className="err-actions">
                <button type="button" className="copy-btn" onClick={() => onRetry && onRetry()}>retry</button>
              </div>
            </div>
          </div>
        );
      })()}

      {isShortlinkView && <ShareBanner onDismiss={onDismissShortlink} />}

      {state === 'idle' && <EmptyRight variant={emptyVariant} />}
      {(state === 'loading' || state === 'expanding') && (
        <div className="right-empty">
          <span className="big">{state === 'expanding' ? 'expanding your collection…' : 'parsing your collection…'}</span>
          <span className="parsing-msg">resolving dependencies. applying rules. probably fine.</span>
        </div>
      )}

      {showOutputs && (
        <>
          {isInflightPartial && (
            <div className="inflight-notice">
              <span className="dot-led inflight-dot"></span>
              showing cached subset · {counts.queued + (counts.parsing || 0)} mods still in flight
            </div>
          )}
          <div className="diff-toggle-row">
            <button
              type="button"
              className={'diff-toggle' + (diffOpen ? ' open' : '')}
              onClick={() => setDiffOpen(o => !o)}
              title="diff your input against the sorted output"
            >
              {diffOpen ? '▾ diff' : '▸ diff'}
            </button>
          </div>
          {diffOpen && (
            <DiffPanel
              inputWsids={inputWsidList}
              outputWsids={(D.WORKSHOP_ITEMS_LINE || '').replace(/;+$/, '').split(';').filter(Boolean)}
              onClose={() => setDiffOpen(false)}
            />
          )}
          <BuildToggle value={pzBuild} onChange={setPzBuild} />
          <div className="stagger-group stagger-enter">
            {successVariant === 'stacked'  && <div className="stagger-item"><SuccessStacked  data={{ count: D.SORTED_ORDER.length }} pzBuild={pzBuild} /></div>}
            {successVariant === 'compact'  && <div className="stagger-item"><SuccessCompact  data={{ count: D.SORTED_ORDER.length }} pzBuild={pzBuild} /></div>}
            {successVariant === 'numbered' && <div className="stagger-item"><SuccessNumbered data={{ count: D.SORTED_ORDER.length }} pzBuild={pzBuild} /></div>}
          </div>
        </>
      )}

      {(isTerminalDone && !isShortlinkView) && (
        <div className="share-btn-wrap">
          <ShareBtn jobId={activeJobId} />
        </div>
      )}

      {(isTerminalDone || isInflightPartial) && (
        <ModTable
          defaultOpen={modTableDefault}
          branchSelections={branchSelections}
          onToggleBranch={onToggleBranch}
          expandedWsids={expandedWsids}
          onToggleExpansion={onToggleExpansion}
        />
      )}
    </>
  );
}

Object.assign(window, { RightColumn });
