// onboard-step-done.jsx — Wizard final step (success).
//
// R03 / T0007: reads the user's first workspace + its products +
// connections + devices to give the final summary, then routes into
// `/w/<wid>/dashboard`.

(function (window) {
  'use strict';

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

  function StepDone({ navigate }) {
    const { user, userDoc } = useAuth();
    const [workspace, setWorkspace] = React.useState(null);
    const [productCount, setProductCount] = React.useState(0);
    const [connectionCount, setConnectionCount] = React.useState(0);
    const [pairedDeviceCount, setPairedDeviceCount] = React.useState(0);

    React.useEffect(() => {
      if (!user) return;
      (async () => {
        const memSnap = await db
          .collection('memberships')
          .where('user_id', '==', user.uid)
          .limit(1)
          .get();
        if (memSnap.empty) return;
        const workspaceId = memSnap.docs[0].data().workspace_id;
        const wsSnap = await db.collection('workspaces').doc(workspaceId).get();
        if (wsSnap.exists) setWorkspace({ id: workspaceId, ...wsSnap.data() });
        const [products, connections, devices] = await Promise.all([
          db.collection('workspaces').doc(workspaceId).collection('products').get(),
          db.collection('workspaces').doc(workspaceId).collection('workspace_connections').get(),
          db.collection('workspaces').doc(workspaceId).collection('devices').get(),
        ]);
        setProductCount(products.size);
        setConnectionCount(connections.size);
        setPairedDeviceCount(devices.size);
      })().catch((err) => console.error('StepDone: load failed', err));
    }, [user]);

    if (!workspace) return <p className="exo-auth-body">Loading…</p>;

    const name = (userDoc && userDoc.display_name) || 'there';

    return (
      <div className="exo-step">
        <h1 className="exo-step-title">You're all set, {name}.</h1>
        <p className="exo-step-body">
          Your first scout will run overnight. Tomorrow's morning report
          arrives at 07:00 your local time. From here, the desktop client
          is the daily surface — but the web dashboard mirrors everything.
        </p>

        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            gap: 12,
            margin: '12px 0',
          }}
        >
          <Stat label="Products" value={productCount} />
          <Stat label="Google Workspaces" value={connectionCount} />
          <Stat label="Paired devices" value={pairedDeviceCount} />
        </div>

        {/* R10T04 — team toggle. Suggests inviting cofounders straight
            into Settings → Members. Keeps the solo founder's funnel
            untouched (single-click "Open the dashboard"); team
            founders see a parallel "Invite cofounders" CTA. */}
        <div style={{
          margin: '16px 0 12px',
          padding: '14px 16px',
          background: 'rgba(91,141,239,0.06)',
          border: '1px solid rgba(91,141,239,0.15)',
          borderRadius: 10,
        }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--exo-ink)', marginBottom: 4 }}>
            Onboarding the team?
          </div>
          <p style={{ fontSize: 12.5, color: '#4a4a52', margin: '0 0 10px', lineHeight: 1.5 }}>
            Add cofounders or teammates now and assign who owns each module
            (outreach, grants, proposals…). Each member can paste their own
            voice samples so drafts sound like <em>them</em>, not you.
          </p>
          <button
            type="button"
            className="exo-link"
            style={{ fontSize: 13 }}
            onClick={() => navigateTo(workspacePath(workspace.id, 'settings/members'))}
          >
            Invite cofounders →
          </button>
        </div>

        <a
          href={workspacePath(workspace.id, 'dashboard')}
          className="exo-auth-submit"
          style={{ textAlign: 'center', textDecoration: 'none', display: 'block' }}
          onClick={(e) => {
            e.preventDefault();
            navigateTo(workspacePath(workspace.id, 'dashboard'));
          }}
        >
          Open the dashboard →
        </a>

        <div className="exo-step-skip">
          <button
            type="button"
            className="exo-link"
            onClick={() => navigateTo(workspacePath(workspace.id, 'settings'))}
          >
            Configure more in Settings
          </button>
        </div>
      </div>
    );
  }

  function Stat({ label, value }) {
    return (
      <div
        style={{
          padding: '14px 12px',
          background: 'var(--exo-bone)',
          borderRadius: 10,
          textAlign: 'center',
        }}
      >
        <div style={{ fontSize: 28, fontWeight: 600, color: 'var(--exo-ink)' }}>
          {value}
        </div>
        <div style={{ fontSize: 12, color: '#6e6e73', marginTop: 4 }}>{label}</div>
      </div>
    );
  }

  window.StepDone = StepDone;
})(window);
