// onboard-step-pair.jsx — Wizard Step 5 (Get the desktop client).
//
// Replaces the original pairing-code design. Now this step is purely
// informational: link to download the desktop client, tell user the
// rest happens IN the desktop app (which opens a browser to
// /authorize when it first launches — the OAuth-style flow that
// authorize.jsx handles).
//
// User can also skip — the dashboard shows the same "download
// desktop" prompt persistently.

(function (window) {
  'use strict';

  const { useAuth, db } = window.exoteamAuth || {};
  if (!useAuth) {
    console.error('onboard-step-pair.jsx: window.exoteamAuth missing');
    return;
  }

  // Detect OS for the primary download link.
  function detectOS() {
    const ua = (typeof navigator !== 'undefined' ? navigator.userAgent : '') || '';
    const platform = (typeof navigator !== 'undefined' ? navigator.platform : '') || '';
    if (/Mac|iPhone|iPad|iPod/.test(platform) || /Mac OS X/.test(ua)) return 'mac';
    if (/Win/.test(platform) || /Windows/.test(ua)) return 'windows';
    if (/Linux/.test(platform)) return 'linux';
    return 'other';
  }

  // Download URLs — placeholder; replace when the desktop client ships.
  // For now points at the GitHub releases page which will exist once
  // F008 ships the Tauri build.
  const DOWNLOAD_URLS = {
    mac: 'https://github.com/exoteam-ai/exoteam-desktop/releases/latest/download/Exoteam.dmg',
    windows: 'https://github.com/exoteam-ai/exoteam-desktop/releases/latest/download/Exoteam-Setup.exe',
    linux: 'https://github.com/exoteam-ai/exoteam-desktop/releases/latest/download/Exoteam.AppImage',
    other: 'https://github.com/exoteam-ai/exoteam-desktop/releases/latest',
  };

  function StepPair({ navigate, onBack }) {
    const { user } = useAuth();
    const [os, setOs] = React.useState('mac');
    const [advancing, setAdvancing] = React.useState(false);

    React.useEffect(() => {
      setOs(detectOS());
    }, []);

    async function advance(skipped) {
      if (!user) return;
      setAdvancing(true);
      try {
        const memSnap = await db
          .collection('memberships')
          .where('user_id', '==', user.uid)
          .limit(1)
          .get();
        if (!memSnap.empty) {
          const workspaceId = memSnap.docs[0].data().workspace_id;
          if (workspaceId) {
            await db.collection('workspaces').doc(workspaceId).set(
              {
                onboarding: {
                  current_step: 'done',
                  completed_steps: firebase.firestore.FieldValue.arrayUnion({
                    step: 'pair',
                    skipped: !!skipped,
                    at: firebase.firestore.Timestamp.now(),
                  }),
                  last_advanced_at: firebase.firestore.FieldValue.serverTimestamp(),
                },
              },
              { merge: true }
            );
          }
        }
        navigate('done');
      } catch (err) {
        console.error('StepPair: advance failed', err);
        setAdvancing(false);
      }
    }

    const downloadUrl = DOWNLOAD_URLS[os] || DOWNLOAD_URLS.other;
    const osLabel = os === 'mac' ? 'macOS' : os === 'windows' ? 'Windows' : os === 'linux' ? 'Linux' : 'your OS';

    return (
      <div className="exo-step">
        <h1 className="exo-step-title">Get the desktop client</h1>
        <p className="exo-step-body">
          Exoteam's day-to-day surface is a desktop app. Your morning
          report, outreach drafts, scout candidates — all live there.
          The web dashboard is your read-only mirror + settings.
        </p>

        <a
          href={downloadUrl}
          className="exo-auth-submit"
          style={{
            display: 'block',
            textAlign: 'center',
            textDecoration: 'none',
            marginTop: 8,
          }}
        >
          Download for {osLabel} →
        </a>

        <p
          className="exo-auth-hint"
          style={{ textAlign: 'center', marginTop: 4 }}
        >
          {os === 'mac' && (
            <a
              href={DOWNLOAD_URLS.windows}
              style={{ color: 'var(--exo-blue)' }}
            >
              Windows
            </a>
          )}
          {os === 'mac' && ' · '}
          {os !== 'linux' && (
            <a
              href={DOWNLOAD_URLS.linux}
              style={{ color: 'var(--exo-blue)' }}
            >
              Linux
            </a>
          )}
          {os !== 'linux' && os !== 'mac' && ' · '}
          {os !== 'mac' && (
            <a
              href={DOWNLOAD_URLS.mac}
              style={{ color: 'var(--exo-blue)' }}
            >
              macOS
            </a>
          )}
        </p>

        <hr
          style={{
            border: 'none',
            borderTop: '1px solid rgba(10,10,26,0.06)',
            margin: '24px 0 8px',
          }}
        />

        <div style={{ fontSize: 13, lineHeight: 1.55, color: '#4a4a52' }}>
          <p style={{ margin: '8px 0', fontWeight: 500, color: 'var(--exo-ink)' }}>
            What happens when you install it:
          </p>
          <ol
            style={{
              paddingLeft: 20,
              margin: '4px 0 8px',
              lineHeight: 1.7,
            }}
          >
            <li>
              On first launch, click <strong>Sign in</strong> — the desktop
              opens this site in your browser
            </li>
            <li>
              You'll see an <strong>Authorize this device</strong> page —
              click Allow
            </li>
            <li>
              The desktop walks you through connecting your Google
              Workspace (one-time, ~10 minutes — privacy note below)
            </li>
            <li>
              Tomorrow at 07:00 your morning report arrives
            </li>
          </ol>
        </div>

        {/* Folded in from the dropped "Connect Workspace" explainer
            step — surfaces why we ask for a 10-min one-time setup
            instead of one-click Sign in with Google. */}
        <div
          style={{
            background: 'rgba(91,141,239,0.07)',
            border: '1px solid rgba(91,141,239,0.15)',
            borderRadius: 10,
            padding: '12px 14px',
            fontSize: 12.5,
            lineHeight: 1.55,
            color: '#4a4a52',
            margin: '12px 0 8px',
          }}
        >
          <strong>Why not just one-click Sign in with Google?</strong> To
          ship that for Gmail-modify across thousands of users we'd need
          Google's CASA Security Assessment ($15K-$75K/year, annually
          recurring). We'd rather pass that cost on as "10 minutes of
          one-time setup" than as a subscription markup. Tokens stay on
          your machine, encrypted — we never see them.
        </div>

        {onBack && (
          <div style={{ marginTop: 16, marginBottom: -4 }}>
            <button
              type="button"
              onClick={onBack}
              disabled={advancing}
              className="exo-step-back"
              aria-label="Go to previous step"
            >
              ← Back
            </button>
          </div>
        )}
        <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
          <button
            type="button"
            onClick={() => advance(true)}
            disabled={advancing}
            style={{
              flex: 1,
              padding: '11px 16px',
              fontSize: 15,
              fontWeight: 500,
              border: '1px solid rgba(10,10,26,0.14)',
              background: '#fff',
              color: 'var(--exo-ink)',
              borderRadius: 10,
              cursor: 'pointer',
              fontFamily: 'inherit',
            }}
          >
            I'll download it later
          </button>
          <button
            type="button"
            className="exo-auth-submit"
            style={{ flex: 1, margin: 0 }}
            onClick={() => advance(false)}
            disabled={advancing}
          >
            {advancing ? 'Saving…' : "I've downloaded it →"}
          </button>
        </div>
      </div>
    );
  }

  window.StepPair = StepPair;
})(window);
