// add-workspace.jsx — "+ Add Workspace" full-page wizard for an
// existing signed-in user.
//
// R03 / T0007 (Phase 5), Q8 resolved 2026-05-27.
//
// Reuses the same step components as `onboard.jsx`, with two steps
// removed:
//
//   - "Sign up" (user already signed in)
//   - "Get the desktop" (devices are user-scoped — one paired desktop
//     serves every Workspace the user belongs to)
//
// Step sequence (5 steps):
//   1. Pick modules
//   2. Your work     (brand / company definition)
//   3. Ideal customer (ICP)
//   4. Connect Google Workspace (OAuth dance OR pick existing connection)
//   5. Done
//
// All step components are passed a `mode: 'additional'` flag so they
// can write to the new pending workspace doc instead of the existing
// first one. Each step component reads `window.exoteamPendingWorkspaceId`
// to identify which workspace to persist into.
//
// The modules-step calls the `createWorkspace` callable to mint the
// new workspace doc + the caller's `owner` membership atomically.
// `billing_parent_id` is set during that call if the user opts into
// linking the new Workspace's bill to an existing one they own/admin.
//
// Exposes window.AddWorkspace.

(function (window) {
  'use strict';

  const { useAuth, AuthGate, signOut, db, fns, navigateTo, workspacePath } =
    window.exoteamAuth || {};
  if (!useAuth) {
    console.error('add-workspace.jsx: window.exoteamAuth missing');
    return;
  }

  const STEPS = [
    { id: 'modules', path: '/onboard/add-workspace/modules', label: 'Pick modules' },
    { id: 'work', path: '/onboard/add-workspace/work', label: 'Your work' },
    { id: 'icp', path: '/onboard/add-workspace/icp', label: 'Ideal customer' },
    { id: 'workspace', path: '/onboard/add-workspace/workspace', label: 'Connect Workspace' },
    { id: 'done', path: '/onboard/add-workspace/done', label: 'Done' },
  ];

  function currentStepId() {
    const path = window.location.pathname || STEPS[0].path;
    const match = STEPS.find((s) => path === s.path);
    return match ? match.id : 'modules';
  }

  function stepNavigate(stepId) {
    const step = STEPS.find((s) => s.id === stepId);
    if (!step) return;
    if (window.location.pathname !== step.path) {
      window.history.pushState({ step: step.id }, '', step.path);
      window.dispatchEvent(new PopStateEvent('popstate'));
    }
  }

  function AddWorkspace() {
    const [stepId, setStepId] = React.useState(currentStepId);
    React.useEffect(() => {
      const onPop = () => setStepId(currentStepId());
      window.addEventListener('popstate', onPop);
      // Normalise bare /onboard/add-workspace to the first step.
      if (window.location.pathname === '/onboard/add-workspace') {
        window.history.replaceState({}, '', STEPS[0].path);
        setStepId('modules');
      }
      return () => window.removeEventListener('popstate', onPop);
    }, []);

    return (
      <AuthGate>
        <Chrome stepId={stepId}>
          <StepBody stepId={stepId} navigate={stepNavigate} />
        </Chrome>
      </AuthGate>
    );
  }

  function Chrome({ stepId, children }) {
    const { userDoc } = useAuth();
    const stepIndex = STEPS.findIndex((s) => s.id === stepId);
    return (
      <div className="exo-onboard">
        <header className="exo-onboard-bar">
          <img src="/lockup.svg" alt="exoteam" className="exo-onboard-logo" />
          <div
            className="exo-onboard-progress"
            role="progressbar"
            aria-valuemin="0"
            aria-valuemax={STEPS.length - 1}
            aria-valuenow={stepIndex}
          >
            {STEPS.map((s, i) => (
              <span
                key={s.id}
                className={
                  'exo-onboard-step ' +
                  (i < stepIndex ? 'exo-onboard-step--done ' : '') +
                  (i === stepIndex ? 'exo-onboard-step--current ' : '')
                }
                aria-current={i === stepIndex ? 'step' : undefined}
              >
                {s.label}
              </span>
            ))}
          </div>
          <div className="exo-onboard-bar-right">
            {userDoc && userDoc.display_name && (
              <span className="exo-onboard-bar-user">Hi, {userDoc.display_name}</span>
            )}
            <button type="button" className="exo-link" onClick={() => signOut()}>
              Sign out
            </button>
          </div>
        </header>
        <main className="exo-onboard-main">{children}</main>
      </div>
    );
  }

  // Resolve the previous step for an in-flight add-workspace step.
  // Returns null on the entry step ('modules') and terminal ('done').
  function prevStepFor(stepId) {
    const idx = STEPS.findIndex((s) => s.id === stepId);
    if (idx <= 0) return null;
    if (stepId === 'done') return null;
    return STEPS[idx - 1];
  }

  function StepBody({ stepId, navigate }) {
    // mode='additional' signals step components to operate on the
    // pending new workspace rather than the user's first workspace.
    // The pending workspace id is materialised by the first step that
    // succeeds at creating it (modules step, via enableModule). Until
    // then, steps fall back to a stub copy + a "this needs a server
    // callable" notice.
    const prev = prevStepFor(stepId);
    const onBack = prev ? () => navigate(prev.id) : null;
    const ctx = { mode: 'additional', navigate, onBack };
    switch (stepId) {
      case 'modules':
        return <ModulesStep ctx={ctx} />;
      case 'work':
        return window.StepWork
          ? <window.StepWork navigate={navigate} mode="additional" onBack={onBack} />
          : <Placeholder label="Your work" navigate={navigate} next="icp" />;
      case 'icp':
        return window.StepIcp
          ? <window.StepIcp navigate={navigate} mode="additional" onBack={onBack} />
          : <Placeholder label="Ideal customer" navigate={navigate} next="workspace" />;
      case 'workspace':
        return window.StepWorkspace
          ? <window.StepWorkspace navigate={navigate} mode="additional" onBack={onBack} />
          : <Placeholder label="Connect Workspace" navigate={navigate} next="done" />;
      case 'done':
        return <DoneStep />;
      default:
        return <Placeholder label={stepId} navigate={navigate} next="done" />;
    }
  }

  // The modules step here ALSO carries the "billing-parent linkage"
  // opt-in (Q8 spec). We render the existing StepModules + an above-
  // the-grid card asking whether to inherit billing from another
  // Workspace the user owns/admins. If selected, the modules section
  // is hidden (modules inherit from parent).
  function ModulesStep({ ctx }) {
    const [createError, setCreateError] = React.useState(null);
    const [linkToParent, setLinkToParent] = React.useState(false);
    const [parentChoice, setParentChoice] = React.useState('');
    const { workspaces } =
      (window.exoteamAuth && window.exoteamAuth.useWorkspace
        ? window.exoteamAuth.useWorkspace()
        : { workspaces: [] }) || {};
    const eligibleParents = (workspaces || []).filter(
      (w) => (w.role === 'owner' || w.role === 'admin') && !w.billing_parent_id,
    );

    async function proceed() {
      setCreateError(null);
      // Guard: if the user picked "link to parent" but didn't select one.
      if (linkToParent && !parentChoice) {
        setCreateError('Pick a parent Workspace or uncheck "Bill this Workspace via another".');
        return;
      }
      try {
        const callable = window.exoteamAuth.fns.httpsCallable('createWorkspace');
        const { data } = await callable({
          // display_name + send_as_email get filled in by the "Your work"
          // step (which writes to workspaces/{wid} via the same flow as
          // the new-user wizard). We mint with placeholder display_name
          // now so the workspace doc exists and the wizard can route
          // subsequent step writes against it.
          display_name: null,
          billing_parent_id: linkToParent ? parentChoice : null,
        });
        if (!data || !data.workspace_id) {
          throw new Error('createWorkspace returned no workspace_id');
        }
        // Persist the newly-minted workspace_id into ctx so subsequent
        // wizard steps target this Workspace. After "Done" the user is
        // redirected to /w/<wid>/dashboard by the wizard's navigation.
        if (ctx && typeof ctx.setNewWorkspaceId === 'function') {
          ctx.setNewWorkspaceId(data.workspace_id);
        }
        // Advance to the next step.
        if (ctx && typeof ctx.navigate === 'function') {
          ctx.navigate('work');
        } else {
          // Fallback if ctx is missing (defensive — UI shouldn't reach this).
          window.history.pushState({}, '', '/onboard/add-workspace/work');
          window.dispatchEvent(new PopStateEvent('popstate'));
        }
      } catch (err) {
        console.error('createWorkspace failed', err);
        setCreateError(err.message || String(err));
      }
    }

    return (
      <div className="exo-step">
        <h1 className="exo-step-title">Add a new Workspace</h1>
        <p className="exo-step-body">
          A Workspace is a brand or company you operate. It has its own
          ICP, products, voice, and (optionally) its own bill. You can
          switch between Workspaces from the header.
        </p>

        {eligibleParents.length > 0 && (
          <div style={billingCardStyle}>
            <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={linkToParent}
                onChange={(e) => setLinkToParent(e.target.checked)}
                style={{ width: 18, height: 18, marginTop: 2, accentColor: '#5b8def' }}
              />
              <div style={{ flex: 1 }}>
                <strong>Bill this Workspace via another Workspace</strong>
                <p className="exo-auth-hint" style={{ marginTop: 4 }}>
                  Modules subscribed on the parent become accessible here —
                  no separate subscription. You can switch back any time.
                </p>
                {linkToParent && (
                  <select
                    className="exo-auth-input"
                    value={parentChoice}
                    onChange={(e) => setParentChoice(e.target.value)}
                    style={{ marginTop: 8, maxWidth: 360 }}
                  >
                    <option value="">— pick a Workspace —</option>
                    {eligibleParents.map((w) => (
                      <option key={w.workspace_id} value={w.workspace_id}>
                        {w.display_name || w.workspace_id}
                      </option>
                    ))}
                  </select>
                )}
              </div>
            </label>
          </div>
        )}

        {!linkToParent && (
          <p className="exo-step-body" style={{ marginTop: 24 }}>
            Otherwise, pick the modules you want on this Workspace. Each
            starts a fresh 14-day trial — no card needed.
          </p>
        )}

        {createError && (
          <p
            style={{
              background: '#fdecea',
              color: '#b3261e',
              padding: '12px 14px',
              borderRadius: 10,
              marginTop: 16,
              fontSize: 13.5,
              lineHeight: 1.55,
            }}
          >
            {createError}
          </p>
        )}

        <div style={{ marginTop: 24, display: 'flex', gap: 12 }}>
          <button
            type="button"
            className="exo-auth-submit"
            onClick={proceed}
            disabled={linkToParent && !parentChoice}
            style={{ maxWidth: 240 }}
          >
            Continue →
          </button>
          <button
            type="button"
            className="exo-link"
            onClick={() => navigateTo('/')}
          >
            Cancel
          </button>
        </div>
      </div>
    );
  }

  function Placeholder({ label, navigate, next }) {
    return (
      <div className="exo-step exo-step--narrow">
        <h1 className="exo-step-title">{label}</h1>
        <p className="exo-step-body">
          This step is wired to the same component the new-user
          onboarding uses. Once the new Workspace has been minted (gated
          on the missing `createWorkspace` callable — see modules step),
          this step's writes target the new Workspace.
        </p>
        <button
          type="button"
          className="exo-auth-submit"
          onClick={() => navigate(next)}
          style={{ maxWidth: 220 }}
        >
          Continue →
        </button>
      </div>
    );
  }

  function DoneStep() {
    const { workspaces } = window.exoteamAuth.useWorkspace();
    const latest = workspaces[workspaces.length - 1];
    return (
      <div className="exo-step exo-step--narrow">
        <h1 className="exo-step-title">Workspace added</h1>
        <p className="exo-step-body">
          Your new Workspace is ready. Switch into it from the header at
          any time.
        </p>
        {latest && (
          <button
            type="button"
            className="exo-auth-submit"
            onClick={() => navigateTo(workspacePath(latest.workspace_id, 'dashboard'))}
            style={{ maxWidth: 280 }}
          >
            Open {latest.display_name || 'new Workspace'} →
          </button>
        )}
      </div>
    );
  }

  const billingCardStyle = {
    border: '1px solid rgba(0,0,0,0.08)',
    borderRadius: 14,
    padding: 16,
    background: '#fff',
    marginTop: 16,
  };

  window.AddWorkspace = AddWorkspace;
})(window);
