// warn-row.jsx - WarnRow component
// Loaded after sortof-shared.jsx; defines globals that sortof-app.jsx references.
const { useState } = React;

function WarnAction({ a, inputWsids, onAddWsid, onSwapWsid, onRemoveWsid }) {
  if (a.type === 'add-wsid') {
    const staged = actionStaged(a, inputWsids);
    return (
      <button
        key={a.wsid}
        type="button"
        className={'warn-action' + (staged ? ' staged' : '')}
        onClick={() => onAddWsid && onAddWsid(a.wsid, a.modId)}
        title={staged ? `click to undo (will remove ${a.wsid})` : `add ${a.wsid} to your input - click sort when ready`}
      >{staged ? `✓ ${a.label}` : a.label}</button>
    );
  }
  if (a.type === 'swap-wsid') {
    const staged = actionStaged(a, inputWsids);
    return (
      <button
        key={a.from}
        type="button"
        className={'warn-action swap' + (staged ? ' staged' : '')}
        onClick={() => onSwapWsid && onSwapWsid(a.from, a.to)}
        title={staged ? `click to undo (will swap back to ${a.from})` : `replace ${a.from} with ${a.to} - click sort when ready`}
      >{staged ? '✓' : '↔'} {a.label}</button>
    );
  }
  if (a.type === 'remove-wsid') {
    const staged = actionStaged(a, inputWsids);
    return (
      <button
        key={a.wsid}
        type="button"
        className={'warn-action remove' + (staged ? ' staged' : '')}
        onClick={() => onRemoveWsid && onRemoveWsid(a.wsid)}
        title={staged ? `click to undo (will re-add ${a.wsid})` : `remove ${a.wsid} from your input - click sort when ready`}
      >{staged ? '✓' : '✕'} {a.label}</button>
    );
  }
  if (a.type === 'search-workshop') {
    return (
      <a
        key={a.url}
        href={a.url}
        target="_blank"
        rel="noopener noreferrer"
        className="warn-action search"
        title={`search Steam Workshop for ${a.modId}`}
      >↗ {a.label}</a>
    );
  }
  return null;
}

function WarnBranchPicker({ w, inputWsids, isAdditive, onPickBranch, onToggleBranch }) {
  const [branchOpen, setBranchOpen] = useState(isAdditive);
  const liveSet = new Set(D.SORTED_ORDER || []);
  const controlled = new Set();
  for (const ww of (D.WARNINGS || [])) {
    if (String(ww.wsid) === String(w.wsid) && Array.isArray(ww.alternatives)) {
      for (const a of ww.alternatives) controlled.add(a);
    }
  }
  const alwaysOn = (w.wsid)
    ? (D.MOD_DB || [])
        .filter(m => String(m.wsid) === String(w.wsid)
                  && !controlled.has(m.modId)
                  && liveSet.has(m.modId))
        .map(m => m.modId)
    : [];
  return (
    <>
      <button
        type="button"
        className="warn-action expand"
        onClick={() => setBranchOpen(b => !b)}
        title={isAdditive ? 'tick modules to include' : 'pick a different branch'}
      >{branchOpen
          ? (isAdditive ? '▾ optional modules' : '▾ branches')
          : (isAdditive ? '▸ optional modules' : '▸ branches')}</button>
      {branchOpen && (
        <div
          className="warn-branches"
          role="group"
          aria-label={isAdditive ? 'optional add-on modules' : 'branch options'}
        >
          {alwaysOn.map(modId => (
            <span
              key={'on-' + modId}
              className="warn-branch-btn picked warn-btn-picked"
              title="always loaded (required by this item)"
            >★ {modId}</span>
          ))}
          {w.alternatives.map(modId => {
            const activeSet = new Set(D.SORTED_ORDER || []);
            const isActive = isAdditive ? activeSet.has(modId) : modId === w.picked;
            const isPrimary = modId === w.picked;
            return (
              <button
                key={modId}
                type="button"
                aria-pressed={isActive}
                className={'warn-branch-btn' + (isActive ? ' picked' : '')}
                onClick={() => {
                  if (isAdditive) {
                    if (isPrimary) return;
                    onToggleBranch && onToggleBranch(
                      w.wsid, modId,
                      w.alternatives.map(id => ({ modId: id })),
                    );
                  } else {
                    if (isActive && !w.optional) return;
                    onPickBranch && onPickBranch(w.wsid, modId, w.alternatives, w.optional);
                  }
                }}
                title={
                  isPrimary && isAdditive ? 'main (always loaded)' :
                  isActive ? (
                    isAdditive ? 'addon enabled - click to remove'
                    : (w.optional ? 'selected - click to remove' : 'currently selected (main)')
                  ) :
                  isAdditive ? `enable ${modId}` : `switch to ${modId}`
                }
              >
                {isActive ? '★ ' : ''}{modId}
              </button>
            );
          })}
        </div>
      )}
    </>
  );
}

function WarnRow({ w, inputWsids, onAddWsid, onPickBranch, onSwapWsid, onRemoveWsid, onToggleBranch }) {
  const isAdditive = w.tag === 'unmatched-addons';
  const hasPicker = Array.isArray(w.alternatives);
  const rowStaged = (Array.isArray(w.actions) ? w.actions : []).some(a => actionStaged(a, inputWsids));
  return (
    <li className={rowStaged ? 'staged' : undefined}>
      <span className={'w-tag ' + warnAccent(w)}>
        <span aria-hidden="true" className="w-tag-glyph">{warnAccent(w) === 'red' ? '!' : warnAccent(w) === 'info' ? '›' : '⚠'}</span>
        {w.tag}
      </span>
      <div className="w-content">
        <WarnMsg msg={w.msg} wsid={w.wsid} />
        {Array.isArray(w.actions) && w.actions.map((a, j) => (
          <WarnAction key={j} a={a} inputWsids={inputWsids} onAddWsid={onAddWsid} onSwapWsid={onSwapWsid} onRemoveWsid={onRemoveWsid} />
        ))}
        {hasPicker && (
          <WarnBranchPicker w={w} inputWsids={inputWsids} isAdditive={isAdditive} onPickBranch={onPickBranch} onToggleBranch={onToggleBranch} />
        )}
      </div>
    </li>
  );
}

Object.assign(window, { WarnRow });
