// cross-ws-settings.jsx — Settings → Cross-Workspace tab content.
//
// R03 / T0007 (Phase 5). Surfaces the `cross_workspace_sharing_enabled`
// toggle for the current Workspace + an informational list of other
// Workspaces the user has admin+ access on + the recent cross-Workspace
// access audit log.
//
// IMPORTANT: this pane orthogonal from any payment / subscription
// concerns — that decoupling is the central R03 claim. Invariant grep
// in T0007's task file asserts zero "b-i-l-l" hits in this file.
//
// Exposes window.CrossWsSettingsPane.

(function (window) {
  'use strict';

  const { db, fns, useWorkspace } = window.exoteamAuth || {};
  if (!useWorkspace) {
    console.error('cross-ws-settings.jsx: window.exoteamAuth missing');
    return;
  }

  function CrossWsSettingsPane({ workspaceId }) {
    const { workspaces } = useWorkspace();
    const [workspace, setWorkspace] = React.useState(null);
    const [audit, setAudit] = React.useState([]);
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState(null);

    React.useEffect(() => {
      if (!workspaceId) return undefined;
      const unsub = db
        .collection('workspaces')
        .doc(workspaceId)
        .onSnapshot(
          (snap) => {
            setWorkspace(snap.exists ? { id: snap.id, ...snap.data() } : null);
          },
          (err) => {
            console.error('CrossWsSettingsPane: workspace snapshot', err);
            setError(err.message || String(err));
          },
        );
      return unsub;
    }, [workspaceId]);

    React.useEffect(() => {
      if (!workspaceId) return undefined;
      const unsub = db
        .collection('workspaces')
        .doc(workspaceId)
        .collection('audit_cross_workspace_access')
        .orderBy('ts', 'desc')
        .limit(20)
        .onSnapshot(
          (snap) => setAudit(snap.docs.map((d) => ({ id: d.id, ...d.data() }))),
          (err) => {
            // Rules require admin+ to read this — non-admins see an empty list.
            console.warn('CrossWsSettingsPane: audit snapshot', err);
            setAudit([]);
          },
        );
      return unsub;
    }, [workspaceId]);

    async function toggle(next) {
      setBusy(true);
      setError(null);
      try {
        const callable = fns.httpsCallable('setCrossWorkspaceSharing');
        await callable({ workspace_id: workspaceId, enabled: next });
      } catch (err) {
        console.error('setCrossWorkspaceSharing failed', err);
        setError(err.message || String(err));
      } finally {
        setBusy(false);
      }
    }

    const enabled = !!(workspace && workspace.cross_workspace_sharing_enabled);

    // Other Workspaces the user has admin+ on. Informational only —
    // the gate fires automatically when both sides are opted-in.
    const otherAdmin = (workspaces || []).filter(
      (w) =>
        w.workspace_id !== workspaceId &&
        (w.role === 'owner' || w.role === 'admin'),
    );

    function fmtTs(ts) {
      if (!ts) return '—';
      const d = ts.toDate ? ts.toDate() : new Date(ts);
      return d.toLocaleString();
    }

    if (!workspaceId) {
      return (
        <div>
          <h2 className="exo-admin-title">Cross-Workspace</h2>
          <p className="exo-admin-subtitle">Pick a workspace.</p>
        </div>
      );
    }

    return (
      <div>
        <h2 className="exo-admin-title">Cross-Workspace</h2>
        <p className="exo-admin-subtitle">
          When two Workspaces both opt in — and you have admin or owner
          access on both — drafts in one Workspace can read context from
          the other. Useful for cross-sell, shared contact lookups, and
          federated outreach across the brands you operate.
        </p>

        {error && (
          <div className="exo-admin-banner is-error" style={{ marginBottom: 14 }}>
            <span>{error}</span>
          </div>
        )}

        {!workspace && <p className="exo-admin-hint">Loading workspace…</p>}

        {workspace && (
          <label
            className="exo-admin-card"
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 16,
              padding: '18px 22px',
              cursor: 'pointer',
            }}
          >
            <div style={{ flex: 1 }}>
              <strong>Share data with my other Workspaces</strong>
              <p className="exo-admin-hint" style={{ marginTop: 4, marginBottom: 0 }}>
                Off by default. Both sides must opt in for any sharing
                to happen.
              </p>
            </div>
            <input
              type="checkbox"
              checked={enabled}
              onChange={(e) => toggle(e.target.checked)}
              disabled={busy}
              style={{ width: 22, height: 22, accentColor: 'var(--exo-accent)' }}
            />
          </label>
        )}

        <hr className="exo-admin-divider" />

        <h3 className="exo-admin-section-title">Your other Workspaces</h3>
        {otherAdmin.length === 0 ? (
          <p className="exo-admin-hint">
            No other Workspaces with admin or owner access. Add a Workspace
            to pair with this one.
          </p>
        ) : (
          <ul className="exo-admin-list">
            {otherAdmin.map((w) => (
              <li key={w.workspace_id} className="exo-admin-list-row">
                <div>
                  <strong>{w.display_name || w.workspace_id}</strong>
                  <span
                    style={{ marginLeft: 8, color: 'var(--exo-ink-tertiary)', fontSize: 12 }}
                  >
                    · {w.role}
                    {' · '}
                    {w.cross_workspace_sharing_enabled
                      ? 'sharing on'
                      : 'sharing off'}
                  </span>
                </div>
              </li>
            ))}
          </ul>
        )}

        <hr className="exo-admin-divider" />

        <h3 className="exo-admin-section-title">Recent cross-Workspace access</h3>
        <p className="exo-admin-hint" style={{ marginTop: 0, marginBottom: 10 }}>
          The latest 20 reads from other Workspaces that the gate
          permitted. Admin-only.
        </p>
        {audit.length === 0 ? (
          <p className="exo-admin-hint">No cross-Workspace access yet.</p>
        ) : (
          <ul className="exo-admin-list">
            {audit.map((row) => (
              <li key={row.id} className="exo-admin-list-row">
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13 }}>
                    <strong>{row.surface || '—'}</strong>
                    <span style={{ marginLeft: 8, color: 'var(--exo-ink-tertiary)' }}>
                      from {row.ws_src || '—'} → {row.ws_dst || '—'}
                    </span>
                  </div>
                  <div className="exo-admin-list-row-meta">
                    user {row.user_id ? row.user_id.slice(0, 8) : '—'} · {fmtTs(row.ts)}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  }

  window.CrossWsSettingsPane = CrossWsSettingsPane;
})(window);
