function LoginView({ onBack, initialStatus, onCreateClinic, onUseExistingClinic, onAcceptClientInvite, onContinueDashboard }) {
  const [authMethod, setAuthMethod] = useState(initialStatus ? "OTP" : null);
  const [status, setStatus] = useState(initialStatus || "idle");
  const [showStateDialog, setShowStateDialog] = useState(false);
  const [returnStatus, setReturnStatus] = useState(["request-pending", "request-approved"].includes(initialStatus) ? "no-org" : "access");
  const [requestHasExistingClinic, setRequestHasExistingClinic] = useState(false);
  const [requestClinicName, setRequestClinicName] = useState("South Austin Functional Medicine");
  const [requestOwnerName, setRequestOwnerName] = useState("Linn Harper");
  const [requestPhone, setRequestPhone] = useState("+1 (512) 555-0198");
  const [requestCredential, setRequestCredential] = useState("FNTP_Certificate_2024.pdf");

  function loginSuccess(label) {
    setAuthMethod(label);
    setStatus("state-select");
    setRequestHasExistingClinic(false);
    setShowStateDialog(true);
  }

  const authOptions = [
    {
      label: "Continue with OTP",
      helper: "Email one-time code through Better Auth",
      icon: <I.mail size={18}/>,
      action: () => loginSuccess("OTP"),
      primary: true,
    },
    {
      label: "Continue with Google",
      helper: "Google OAuth through Better Auth",
      icon: <I.globe size={18}/>,
      action: () => loginSuccess("Google OAuth"),
    },
  ];
  const hasAuthenticated = Boolean(authMethod);
  const requestValid = requestClinicName.trim() && requestOwnerName.trim() && requestCredential.trim();
  const stateResolved = hasAuthenticated && !["idle", "state-select"].includes(status);
  const isRequestFlow = ["requesting-clinic", "request-pending", "request-approved"].includes(status);
  const prototypeStates = [
    {
      id: "access",
      label: "Active clinic found",
      helper: "DB has at least one active clinic membership.",
      icon: <I.bldg size={16}/>,
    },
    {
      id: "clinic-team-invite",
      label: "Clinic team invite",
      helper: "DB has a pending clinic staff invite or selectable membership.",
      icon: <I.users size={16}/>,
    },
    {
      id: "client-invite",
      label: "Client onboarding",
      helper: "DB has a pending client invitation for this email.",
      icon: <I.user size={16}/>,
    },
    {
      id: "no-org",
      label: "No access facts",
      helper: "DB has no active membership, clinic invite, client onboarding invite, or approved request.",
      icon: <I.warn size={16}/>,
    },
    {
      id: "membership-blocked",
      label: "Suspended membership",
      helper: "DB has a clinic membership, but its status blocks access.",
      icon: <I.shield size={16}/>,
    },
    {
      id: "request-pending",
      label: "Clinic request pending",
      helper: "DB has a submitted clinic request awaiting Platform Admin review.",
      icon: <I.clock size={16}/>,
    },
    {
      id: "request-approved",
      label: "Clinic request approved",
      helper: "DB has an approved clinic request ready for org creation.",
      icon: <I.checkCircle size={16}/>,
    },
  ];
  const activeState = prototypeStates.find(item => item.id === status);
  const flowSteps = [
    ["Signed in", hasAuthenticated],
    ["Access Router", stateResolved || showStateDialog],
    ["Access state resolved", stateResolved],
    ["Next action shown", stateResolved],
  ];
  const beginClinicRequest = () => {
    setReturnStatus(stateResolved && !isRequestFlow ? status : "no-org");
    setRequestHasExistingClinic(status === "access");
    setStatus("requesting-clinic");
  };
  const selectPrototypeState = (nextStatus) => {
    setStatus(nextStatus);
    setRequestHasExistingClinic(false);
    setReturnStatus(["request-pending", "request-approved"].includes(nextStatus) ? "no-org" : nextStatus);
    setShowStateDialog(false);
  };
  const resetToSignIn = () => {
    setAuthMethod(null);
    setStatus("idle");
    setShowStateDialog(false);
    setRequestHasExistingClinic(false);
  };

  return (
    <div className="auth-stage">
      <button className="btn sm ghost auth-stage-back" onClick={onBack}>
        <I.arrowL size={12}/> Selection
      </button>

      <div className="auth-card login-card" data-screen-label="Login View">
        <section className="auth-hero">
          <div className="auth-brand-lockup">
            <span className="auth-brand-mark"></span>
            <span>VYKON · HTMA</span>
          </div>
          <div>
            <div className="auth-title">Login to Vykon HTMA</div>
            <div className="auth-subtitle">Sign in, then use one access router for clinic staff, clients, and new clinic account requests.</div>
          </div>

          <div className="auth-flow-list">
            {flowSteps.map(([label, complete], index) => (
              <div key={label} className={"auth-flow-step" + (complete ? " complete" : "")}>
                <span>{complete ? <I.check size={12}/> : index + 1}</span>
                <div>{label}</div>
              </div>
            ))}
          </div>
        </section>

        <section className="auth-panel">
          <div className="auth-panel-head">
            <h2>{hasAuthenticated ? "Access Router" : "Sign in"}</h2>
            <p>{hasAuthenticated ? "The selected prototype state represents what Vykon resolves from memberships, client onboarding invites, clinic team invites, and clinic requests after Better Auth sign-in." : "Use OTP or Google OAuth. Vykon routes every authenticated user through the same access step."}</p>
          </div>

          {!hasAuthenticated && (
            <>
              <div className="auth-option-stack">
                {authOptions.map((option) => (
                  <button
                    key={option.label}
                    type="button"
                    className={"auth-option" + (option.primary ? " primary" : "")}
                    onClick={option.action}
                  >
                    <span className="auth-option-icon">{option.icon}</span>
                    <span>
                      <span className="auth-option-title">{option.label}</span>
                      <span className="auth-option-helper">{option.helper}</span>
                    </span>
                    <I.arrowR size={15}/>
                  </button>
                ))}
              </div>

              <div className="auth-divider">
                <span></span>
                <em>state is selected after sign-in</em>
                <span></span>
              </div>
            </>
          )}

          {hasAuthenticated && status === "state-select" && (
            <div className="alert info auth-status">
              <I.checkCircle size={16}/>
              <div>
                <strong>Authenticated through {authMethod}</strong>
                <div>Use the prototype dialog to select the DB-backed access state. The real platform resolves this automatically.</div>
              </div>
            </div>
          )}

          {hasAuthenticated && ["access", "clinic-team-invite", "client-invite"].includes(status) && (
            <div className="alert info auth-status">
              <I.checkCircle size={16}/>
              <div>
                <strong>{activeState?.label || "Access resolved"}</strong>
                <div>{activeState?.helper || "Access is resolved after auth."}</div>
                <button type="button" className="btn sm ghost auth-state-change" onClick={() => setShowStateDialog(true)}>
                  Change prototype state
                </button>
              </div>
            </div>
          )}

          {hasAuthenticated && status === "access" && (
            <>
              <div className="clinic-access-summary">
                <div>
                  <span>Signed-in user</span>
                  <strong>Linn Harper</strong>
                  <small>Authenticated through {authMethod}</small>
                </div>
                <div>
                  <span>Active access</span>
                  <strong>1 clinic</strong>
                  <small>Functional Practice Clinic · Practitioner</small>
                </div>
              </div>
              <div className="login-route-actions">
                <button type="button" className="flow-open-action-card primary" onClick={onContinueDashboard}>
                  <span className="flow-option-icon"><I.bldg size={16}/></span>
                  <span>
                    <span className="flow-option-title">Go to Functional Practice Clinic</span>
                    <span className="flow-option-desc">Enter the active clinic workspace with current role-scoped access.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
                <button type="button" className="flow-open-action-card" onClick={onUseExistingClinic}>
                  <span className="flow-option-icon"><I.users size={16}/></span>
                  <span>
                    <span className="flow-option-title">Use another clinic access</span>
                    <span className="flow-option-desc">Accept/select another active clinic, then complete profile setup if needed.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
                <button type="button" className="flow-open-action-card" onClick={beginClinicRequest}>
                  <span className="flow-option-icon"><I.plus size={16}/></span>
                  <span>
                    <span className="flow-option-title">Request a new clinic account</span>
                    <span className="flow-option-desc">Send a clinic creation request to Platform Admin. No organization is created until approval.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
              </div>
            </>
          )}

          {hasAuthenticated && status === "clinic-team-invite" && (
            <>
              <div className="clinic-access-summary">
                <div>
                  <span>Signed-in user</span>
                  <strong>Linn Harper</strong>
                  <small>Authenticated through {authMethod}</small>
                </div>
                <div>
                  <span>Pending access</span>
                  <strong>Functional Practice Clinic</strong>
                  <small>Practitioner invite awaiting acceptance</small>
                </div>
              </div>
              <div className="login-route-actions">
                <button type="button" className="flow-open-action-card primary" onClick={onUseExistingClinic}>
                  <span className="flow-option-icon"><I.users size={16}/></span>
                  <span>
                    <span className="flow-option-title">Accept clinic access</span>
                    <span className="flow-option-desc">Select the invited clinic, complete profile setup, and enter with role-scoped access.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
                <button type="button" className="flow-open-action-card" onClick={beginClinicRequest}>
                  <span className="flow-option-icon"><I.plus size={16}/></span>
                  <span>
                    <span className="flow-option-title">Request a new clinic account</span>
                    <span className="flow-option-desc">Submit a separate clinic account request for Platform Admin review.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
              </div>
            </>
          )}

          {hasAuthenticated && status === "client-invite" && (
            <>
              <div className="clinic-access-summary">
                <div>
                  <span>Signed-in user</span>
                  <strong>Amelia Hart</strong>
                  <small>Authenticated through {authMethod}</small>
                </div>
                <div>
                  <span>Client onboarding</span>
                  <strong>Functional Practice Clinic</strong>
                  <small>Assigned practitioner: Linn Harper</small>
                </div>
              </div>
              <div className="login-route-actions">
                <button type="button" className="flow-open-action-card primary" onClick={onAcceptClientInvite}>
                  <span className="flow-option-icon"><I.user size={16}/></span>
                  <span>
                    <span className="flow-option-title">Start client onboarding</span>
                    <span className="flow-option-desc">Complete profile, shipping, payment, and intake details before entering the client portal.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
              </div>
            </>
          )}

          {hasAuthenticated && status === "requesting-clinic" && (
            <div className="clinic-request-panel">
              <div className="alert info">
                <I.bldg size={16}/>
                <div>
                  <strong>Request another clinic account</strong>
                  <div>{requestHasExistingClinic ? "This user can stay in Functional Practice Clinic while requesting a separate clinic organization." : "This request asks Platform Admin to approve a new clinic organization before setup can begin."}</div>
                </div>
              </div>
              <div className="clinic-request-grid">
                <div className="field">
                  <div className="field-label">Requested clinic name</div>
                  <input className="input" value={requestClinicName} onChange={e => setRequestClinicName(e.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Requested owner</div>
                  <input className="input" value={requestOwnerName} onChange={e => setRequestOwnerName(e.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Phone</div>
                  <input className="input" value={requestPhone} onChange={e => setRequestPhone(e.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Credential / accreditation</div>
                  <input className="input" value={requestCredential} onChange={e => setRequestCredential(e.target.value)}/>
                </div>
              </div>
              <div className="vera-rule-strip">
                <span><I.shield size={13}/> Platform Admin approval required</span>
                <span><I.bldg size={13}/> New clinic is a separate organization</span>
                <span><I.clock size={13}/> Request can be pending, approved, denied, or expired</span>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStatus(returnStatus)}>Back</button>
                <button className="btn primary lg" disabled={!requestValid} onClick={() => setStatus("request-pending")}>
                  Submit request <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {hasAuthenticated && status === "request-pending" && (
            <div className="clinic-request-panel">
              <div className="alert warn">
                <I.clock size={16}/>
                <div>
                  <strong>New clinic request pending</strong>
                  <div>{requestClinicName} is waiting for Platform Admin review.{requestHasExistingClinic ? " The existing clinic remains available." : " No new clinic organization is created until approval."}</div>
                </div>
              </div>
              <div className="clinic-request-status">
                <div><span>Request</span><strong>{requestClinicName}</strong></div>
                <div><span>Owner</span><strong>{requestOwnerName}</strong></div>
                <div><span>Status</span><strong>Pending review</strong></div>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStatus(returnStatus)}>Go back</button>
                {requestHasExistingClinic && <button className="btn lg" onClick={onContinueDashboard}>Go to existing clinic</button>}
                {!requestHasExistingClinic && <button className="btn lg" onClick={() => setShowStateDialog(true)}>Change state</button>}
                <button className="btn primary lg" onClick={() => setStatus("request-approved")}>
                  Simulate approval <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {hasAuthenticated && status === "request-approved" && (
            <div className="clinic-request-panel">
              <div className="alert info">
                <I.checkCircle size={16}/>
                <div>
                  <strong>Clinic request approved</strong>
                  <div>Vykon can now create the Better Auth organization and run first-owner onboarding for {requestClinicName}.</div>
                </div>
              </div>
              <button className="btn primary lg" onClick={onCreateClinic}>
                Create approved clinic account <I.arrowR size={14}/>
              </button>
              <button type="button" className="btn ghost lg" onClick={() => setShowStateDialog(true)}>
                Change prototype state
              </button>
            </div>
          )}

          {status === "no-org" && (
            <>
              <div className="alert warn auth-status">
                <I.warn size={16}/>
                <div>
                  <strong>No access facts found</strong>
                  <div>This account is authenticated, but no active clinic membership, clinic team invite, client onboarding invite, or approved clinic request was found.</div>
                  <button type="button" className="btn sm ghost auth-state-change" onClick={() => setShowStateDialog(true)}>
                    Change prototype state
                  </button>
                </div>
              </div>
              <div className="clinic-access-summary">
                <div>
                  <span>Signed-in user</span>
                  <strong>Linn Harper</strong>
                  <small>Authenticated through {authMethod}</small>
                </div>
                <div>
                  <span>Resolved access</span>
                  <strong>No workspace or client profile</strong>
                  <small>The user can request a clinic account or provide a valid clinic team or client onboarding invite.</small>
                </div>
              </div>
              <div className="login-route-actions">
                <button type="button" className="flow-open-action-card primary" onClick={beginClinicRequest}>
                  <span className="flow-option-icon"><I.plus size={16}/></span>
                  <span>
                    <span className="flow-option-title">Request new clinic account</span>
                    <span className="flow-option-desc">Submit a clinic request for Platform Admin approval.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
                <button type="button" className="flow-open-action-card" onClick={() => setStatus("clinic-team-invite")}>
                  <span className="flow-option-icon"><I.users size={16}/></span>
                  <span>
                    <span className="flow-option-title">I have a clinic team invite</span>
                    <span className="flow-option-desc">Simulate a valid practitioner/admin/assistant invite for this authenticated email.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
                <button type="button" className="flow-open-action-card" onClick={() => setStatus("client-invite")}>
                  <span className="flow-option-icon"><I.user size={16}/></span>
                  <span>
                    <span className="flow-option-title">Continue client onboarding</span>
                    <span className="flow-option-desc">Simulate a pending client invitation and continue to client profile completion.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
              </div>
            </>
          )}

          {status === "membership-blocked" && (
            <>
              <div className="alert danger auth-status">
                <I.shield size={16}/>
                <div>
                  <strong>Suspended membership</strong>
                  <div>The clinic membership exists, but its status blocks workspace entry. A clinic owner/admin needs to reactivate access.</div>
                  <button type="button" className="btn sm ghost auth-state-change" onClick={() => setShowStateDialog(true)}>
                    Change prototype state
                  </button>
                </div>
              </div>
              <div className="clinic-access-summary">
                <div>
                  <span>Blocked clinic</span>
                  <strong>Functional Practice Clinic</strong>
                  <small>Practitioner membership</small>
                </div>
                <div>
                  <span>Status</span>
                  <strong>Suspended</strong>
                  <small>No dashboard entry action is available for this clinic.</small>
                </div>
              </div>
              <div className="login-route-actions">
                <button type="button" className="flow-open-action-card" onClick={beginClinicRequest}>
                  <span className="flow-option-icon"><I.plus size={16}/></span>
                  <span>
                    <span className="flow-option-title">Request new clinic account</span>
                    <span className="flow-option-desc">Submit a separate clinic request if this user needs to create another clinic.</span>
                  </span>
                  <I.arrowR size={14}/>
                </button>
              </div>
            </>
          )}

          <div className="auth-legal">By continuing, the user accepts the Terms of Service and Privacy Policy.</div>
        </section>
      </div>

      {showStateDialog && hasAuthenticated && (
        <div className="modal-backdrop auth-state-backdrop">
          <div className="modal auth-state-modal" onClick={event => event.stopPropagation()}>
            <div className="auth-state-head">
              <span className="auth-state-kicker">Prototype state selector</span>
              <h3>Select access state</h3>
              <p>The real platform gets this from Better Auth, clinic memberships, clinic team invitations, client invitations, and clinic request records. In the mockup, choose the state to preview the matching screen actions.</p>
            </div>
            <div className="access-state-grid">
              {prototypeStates.map(item => (
                <button
                  key={item.id}
                  type="button"
                  className={"access-state-card" + (status === item.id ? " selected" : "")}
                  onClick={() => selectPrototypeState(item.id)}
                >
                  <span className="flow-option-icon">{item.icon}</span>
                  <span>
                    <strong>{item.label}</strong>
                    <small>{item.helper}</small>
                  </span>
                </button>
              ))}
            </div>
            <div className="auth-actions split">
              <button className="btn ghost lg" onClick={resetToSignIn}>Back to sign in</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function OnboardingView({ initialStep = "path", onBack, onComplete }) {
  const [step, setStep] = useState(initialStep);
  const [clinicName, setClinicName] = useState("Functional Practice Clinic");
  const [ownerName, setOwnerName] = useState("Linn Harper");
  const [clinicRegion, setClinicRegion] = useState("Austin, TX");
  const [website, setWebsite] = useState("functionalpractice.co");
  const [selectedPlan, setSelectedPlan] = useState("advanced");
  const [inviteEmail, setInviteEmail] = useState("maya@functionalpractice.co");
  const [inviteRole, setInviteRole] = useState("Admin");
  const [selectedExistingOrg, setSelectedExistingOrg] = useState("functional-practice");
  const [existingAvatarAdded, setExistingAvatarAdded] = useState(false);
  const [existingProfileName, setExistingProfileName] = useState("Linn Harper");
  const [primaryPractitioner, setPrimaryPractitioner] = useState({
    firstName: "Linn",
    lastName: "Harper",
    billingAddress: "1800 Congress Ave, Austin, TX 78701",
    phone: "+1 (512) 555-0198",
    email: "linn@functionalpractice.co",
    certificate: "FNTP_Certificate_2024.pdf",
    paymentInfo: "Visa ending 4242",
  });
  const [clinicAdmin, setClinicAdmin] = useState({
    firstName: "Maya",
    lastName: "Chen",
    address: "1800 Congress Ave, Austin, TX 78701",
    phone: "+1 (512) 555-0142",
    email: "maya@functionalpractice.co",
  });

  const hasPathChoice = initialStep === "path";
  const setupSteps = [
    { id: "clinic", label: "Clinic" },
    { id: "practitioner", label: "Primary Practitioner" },
    { id: "admin", label: "Admin" },
    { id: "plan", label: "Plan" },
    { id: "checkout", label: "Checkout" },
    { id: "activation", label: "Activate" },
    { id: "team", label: "Team" },
    { id: "ready", label: "Ready" },
  ];
  const existingSteps = [
    { id: "existing", label: "Clinic" },
    { id: "existing-photo", label: "Photo" },
    { id: "existing-profile", label: "Profile" },
    { id: "existing-ready", label: "Ready" },
  ];
  const steps = initialStep === "existing" ? existingSteps : hasPathChoice ? [{ id: "path", label: "Path" }, ...setupSteps] : setupSteps;
  const stepIndex = step === "existing" ? 1 : Math.max(0, steps.findIndex(item => item.id === step));
  const setupOffset = hasPathChoice ? 1 : 0;
  const plans = [
    { id: "basic", name: "Basic", price: "$149/mo", seats: "3 seats", credits: 10, helper: "Solo or small clinic starting HTMA workflows", features: ["Core dashboard", "Client records", "Protocol credits"] },
    { id: "advanced", name: "Advanced", price: "$299/mo", seats: "10 seats", credits: 30, helper: "Clinic teams with assistants and admin support", features: ["Team roles", "Priority VERA", "Expanded audit trail"] },
    { id: "premium", name: "Premium", price: "$599/mo", seats: "25 seats", credits: 90, helper: "High-volume or multi-practitioner clinics", features: ["Higher capacity", "Advanced support", "Enterprise controls"] },
  ];
  const selectedPlanOption = plans.find(plan => plan.id === selectedPlan) || plans[1];
  const existingOrgs = [
    { id: "functional-practice", name: "Functional Practice Clinic", role: "Practitioner", plan: "Advanced", credits: 12, members: 8, status: "Active" },
    { id: "northstar", name: "Northstar Wellness", role: "Admin", plan: "Basic", credits: 4, members: 3, status: "Active" },
  ];
  const activeExistingOrg = existingOrgs.find(org => org.id === selectedExistingOrg) || existingOrgs[0];
  const isExistingBranch = step === "path" || step.startsWith("existing");
  const readiness = isExistingBranch ? [
    { label: "Signed in", detail: "OTP or Google OAuth complete", complete: true },
    { label: "Access path", detail: step === "path" ? "Choose existing clinic or new clinic" : "Existing clinic selected", complete: step !== "path" },
    { label: "Invitation accepted", detail: `${activeExistingOrg.role} membership`, complete: stepIndex >= 1 },
    { label: "Active clinic", detail: activeExistingOrg.name, complete: stepIndex >= 1 },
    { label: "Profile picture", detail: existingAvatarAdded ? "Photo selected" : "Optional upload", complete: stepIndex >= 2 },
    { label: "Profile details", detail: existingProfileName || "Name required", complete: stepIndex >= 3 },
  ] : [
    { label: "Signed in", detail: "OTP or Google OAuth complete", complete: true },
    { label: "Clinic profile", detail: clinicName || "Pending clinic details", complete: stepIndex >= setupOffset + 1 },
    { label: "Better Auth organization", detail: "Created for new clinic owner", complete: stepIndex >= setupOffset + 1 },
    { label: "Primary practitioner", detail: primaryPractitioner.certificate ? "Credential captured" : "Certificate required", complete: stepIndex >= setupOffset + 2 },
    { label: "Clinic admin", detail: clinicAdmin.email || "Optional admin details", complete: stepIndex >= setupOffset + 3 },
    { label: "Plan selected", detail: selectedPlanOption.name, complete: stepIndex >= setupOffset + 4 },
    { label: "Stripe checkout", detail: "Payment method confirmed", complete: stepIndex >= setupOffset + 5 },
    { label: "Billing sync", detail: "Better Auth billing active", complete: stepIndex >= setupOffset + 5 },
  ];
  const activationRows = [
    { label: "Better Auth organization", detail: "org_functional_practice", icon: <I.bldg size={15}/> },
    { label: "Clinic Owner membership", detail: `${ownerName || "Owner"} assigned as Owner`, icon: <I.shield size={15}/> },
    { label: "Primary Practitioner", detail: `${primaryPractitioner.firstName} ${primaryPractitioner.lastName} · credential pending verification`, icon: <I.file size={15}/> },
    { label: "Clinic Admin", detail: `${clinicAdmin.firstName} ${clinicAdmin.lastName} ready for invite`, icon: <I.users size={15}/> },
    { label: "Stripe subscription", detail: `${selectedPlanOption.name} marked active`, icon: <I.receipt size={15}/> },
    { label: "subscription_entitlements", detail: "Plan features, seats, and limits synced", icon: <I.checkCircle size={15}/> },
    { label: "Monthly credits granted", detail: `${selectedPlanOption.credits} included credits available`, icon: <I.bolt size={15}/> },
  ];
  const inviteRows = [
    { email: clinicAdmin.email, role: "Clinic Admin", status: "Pending invitation", detail: "Can manage team, clients, assignments, communications, and orders" },
    { email: "jordan@functionalpractice.co", role: "Practitioner", status: "Pending verification", detail: "Certificate required before clinical approval" },
    { email: "riley@functionalpractice.co", role: "Practitioner Assistant", status: "Draft", detail: "Assigned to practitioner with view/edit/communication/order permissions" },
  ];
  const headerTitle = step === "path" ? "Choose access path" : step.startsWith("existing") ? "Existing clinic access" : "Activate clinic account";
  const headerCopy = step === "path"
    ? "Continue with an existing clinic invitation or start a new clinic owner setup."
    : step.startsWith("existing")
      ? "Select a clinic organization, then complete the production-style profile picture and profile details steps."
      : "Create the clinic organization, choose a subscription, sync entitlements, then invite the first team members.";

  return (
    <div className="auth-stage">
      <button className="btn sm ghost auth-stage-back" onClick={onBack}>
        <I.arrowL size={12}/> Selection
      </button>

      <div className="auth-card onboarding-card" data-screen-label="Onboarding View">
        <section className="auth-panel onboarding-main">
          <div className="auth-brand-lockup compact">
            <span className="auth-brand-mark"></span>
            <span>VYKON · HTMA</span>
          </div>

          <div className="auth-panel-head centered">
            <h2>{headerTitle}</h2>
            <p>{headerCopy}</p>
          </div>

          <div className="onboarding-steps" aria-label="Onboarding progress">
            {steps.map((item, index) => (
              <React.Fragment key={item.id}>
                <span className="onboarding-step-node">
                  <span className={"onboarding-dot" + (index <= stepIndex ? " active" : "")}>
                  {index < stepIndex ? <I.check size={12}/> : index + 1}
                  </span>
                  <small>{item.label}</small>
                </span>
                {index < steps.length - 1 && <span className={"onboarding-line" + (index < stepIndex ? " active" : "")}></span>}
              </React.Fragment>
            ))}
          </div>

          {step === "path" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="setup-centered-copy">
                <h3>How should this user continue?</h3>
                <p>Existing members should select or accept a clinic invite. New clinic owners reach setup after a clinic account request is approved.</p>
              </div>
              <div className="access-path-grid">
                <button type="button" className="access-path-card primary" onClick={() => setStep("clinic")}>
                  <span className="access-path-icon"><I.bldg size={22}/></span>
                  <strong>Create approved clinic account</strong>
                  <small>Continue after Platform Admin approval, complete clinic profile, select Basic / Advanced / Premium, checkout, sync credits, and invite the team.</small>
                  <em>Approved Clinic Owner setup</em>
                </button>
                <button type="button" className="access-path-card" onClick={() => setStep("existing")}>
                  <span className="access-path-icon"><I.users size={22}/></span>
                  <strong>Use existing clinic access</strong>
                  <small>Select an active clinic, then complete profile picture and profile details.</small>
                  <em>Existing invite or membership</em>
                </button>
              </div>
            </div>
          )}

          {step === "existing" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="onboarding-ready-icon"><I.bldg size={28}/></div>
              <div className="setup-centered-copy">
                <h3>Select active clinic</h3>
                <p>The user accepts the organization invite, chooses the active clinic context, and receives permissions from their clinic role.</p>
              </div>
              <div className="org-option-stack">
                {existingOrgs.map(org => (
                  <button
                    key={org.id}
                    type="button"
                    className={"org-select-card" + (selectedExistingOrg === org.id ? " selected" : "")}
                    onClick={() => setSelectedExistingOrg(org.id)}
                  >
                    <span>
                      <strong>{org.name}</strong>
                      <small>{org.role} · {org.plan} · {org.credits} credits · {org.members} members</small>
                    </span>
                    <span className="badge green"><span className="dot"></span> {org.status}</span>
                  </button>
                ))}
              </div>
              <div className="setup-summary-grid">
                <div><span>Membership</span><strong>{activeExistingOrg.role}</strong></div>
                <div><span>Subscription</span><strong>{activeExistingOrg.plan} active</strong></div>
                <div><span>Credits</span><strong>{activeExistingOrg.credits} available</strong></div>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => hasPathChoice ? setStep("path") : onBack()}>Back</button>
                <button className="btn primary lg" onClick={() => setStep("existing-photo")}>
                  Continue <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "existing-photo" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="setup-centered-copy">
                <div className="onboarding-ready-icon"><I.upload size={28}/></div>
                <h3>Add a profile picture</h3>
                <p>Upload a photo for the practitioner profile, or skip this for now. This mirrors the production onboarding profile step.</p>
              </div>
              <button type="button" className="onboarding-avatar" onClick={() => setExistingAvatarAdded(true)}>
                {existingAvatarAdded ? <Avatar initial="L" color="oklch(0.62 0.14 240)" size={82}/> : <I.upload size={28}/>}
              </button>
              <div className="auth-actions">
                <button className="btn primary lg" onClick={() => setStep("existing-profile")} disabled={false}>
                  Continue <I.arrowR size={14}/>
                </button>
                <button className="btn ghost lg" onClick={() => setStep("existing-profile")}>Skip for now</button>
              </div>
            </div>
          )}

          {step === "existing-profile" && (
            <div className="onboarding-step-panel setup-wide form">
              <div className="setup-centered-copy">
                <h3>Complete your profile</h3>
                <p>Set up the account details practitioners and clinic admins will see.</p>
              </div>
              <div className="clinic-form-grid">
                <div className="field">
                  <div className="field-label">Name</div>
                  <input
                    className="input"
                    value={existingProfileName}
                    maxLength={40}
                    onChange={(event) => setExistingProfileName(event.target.value.slice(0, 40))}
                  />
                  <div className="auth-char-count">{existingProfileName.trim().length}/40</div>
                </div>
                <div className="field">
                  <div className="field-label">Email</div>
                  <input className="input" value="linn@functionalpractice.co" readOnly/>
                </div>
                <div className="field">
                  <div className="field-label">Role</div>
                  <input className="input" value={activeExistingOrg.role} readOnly/>
                </div>
                <div className="field">
                  <div className="field-label">Active clinic</div>
                  <input className="input" value={activeExistingOrg.name} readOnly/>
                </div>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("existing-photo")}>Back</button>
                <button className="btn primary lg" disabled={!existingProfileName.trim()} onClick={() => setStep("existing-ready")}>
                  Finish <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "existing-ready" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="onboarding-ready-icon"><I.checkCircle size={30}/></div>
              <div className="setup-centered-copy">
                <h3>Workspace ready</h3>
                <p>{activeExistingOrg.name} is active. {existingProfileName || "This user"} can enter with {activeExistingOrg.role} access.</p>
              </div>
              <div className="setup-summary-grid">
                <div><span>Active clinic</span><strong>{activeExistingOrg.name}</strong></div>
                <div><span>Role</span><strong>{activeExistingOrg.role}</strong></div>
                <div><span>Credits</span><strong>{activeExistingOrg.credits} available</strong></div>
              </div>
              <button className="btn primary lg" onClick={onComplete}>
                Enter dashboard <I.arrowR size={14}/>
              </button>
            </div>
          )}

          {step === "clinic" && (
            <div className="onboarding-step-panel setup-wide form">
              <div className="onboarding-ready-icon"><I.bldg size={28}/></div>
              <div className="setup-centered-copy">
                <h3>Clinic profile</h3>
                <p>This creates the Better Auth organization, the Vykon clinic profile, and the first Clinic Owner membership after approved platform placement.</p>
              </div>
              <div className="clinic-form-grid">
                <div className="field">
                  <div className="field-label">Clinic name</div>
                  <input className="input" value={clinicName} onChange={(event) => setClinicName(event.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Owner name</div>
                  <input className="input" value={ownerName} onChange={(event) => setOwnerName(event.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Website</div>
                  <input className="input" value={website} onChange={(event) => setWebsite(event.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Region</div>
                  <input className="input" value={clinicRegion} onChange={(event) => setClinicRegion(event.target.value)}/>
                </div>
              </div>
              <div className="setup-summary-grid">
                <div><span>Initial role</span><strong>Clinic Owner</strong></div>
                <div><span>Auth method</span><strong>Better Auth organization</strong></div>
                <div><span>Access state</span><strong>Approved platform placement</strong></div>
              </div>
              {hasPathChoice ? (
                <div className="auth-actions split">
                  <button className="btn ghost lg" onClick={() => setStep("path")}>Back</button>
                  <button className="btn primary lg" disabled={!clinicName.trim() || !ownerName.trim()} onClick={() => setStep("practitioner")}>
                    Create clinic account <I.arrowR size={14}/>
                  </button>
                </div>
              ) : (
                <button className="btn primary lg" disabled={!clinicName.trim() || !ownerName.trim()} onClick={() => setStep("practitioner")}>
                  Create clinic account <I.arrowR size={14}/>
                </button>
              )}
            </div>
          )}

          {step === "practitioner" && (
            <div className="onboarding-step-panel setup-wide form">
              <div className="setup-centered-copy">
                <h3>Add Primary Practitioner</h3>
                <p>The primary practitioner carries clinical responsibility for the initial clinic setup. Credential and payment details are collected before plan activation.</p>
              </div>
              <div className="clinic-form-grid clinic-form-grid-3">
                <div className="field">
                  <div className="field-label">First name</div>
                  <input className="input" value={primaryPractitioner.firstName} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, firstName: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Last name</div>
                  <input className="input" value={primaryPractitioner.lastName} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, lastName: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Phone</div>
                  <input className="input" value={primaryPractitioner.phone} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, phone: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Email</div>
                  <input className="input" value={primaryPractitioner.email} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, email: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Accreditation certificate</div>
                  <input className="input" value={primaryPractitioner.certificate} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, certificate: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Payment information</div>
                  <input className="input" value={primaryPractitioner.paymentInfo} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, paymentInfo: e.target.value }))}/>
                </div>
                <div className="field" style={{gridColumn: "1 / -1"}}>
                  <div className="field-label">Billing address</div>
                  <input className="input" value={primaryPractitioner.billingAddress} onChange={e => setPrimaryPractitioner(prev => ({ ...prev, billingAddress: e.target.value }))}/>
                </div>
              </div>
              <div className="vera-rule-strip">
                <span><I.shield size={13}/> Owner inherits Admin permissions</span>
                <span><I.checkCircle size={13}/> Verified Owner inherits Practitioner permissions</span>
                <span><I.file size={13}/> Practitioner starts Pending Verification</span>
                <span><I.bldg size={13}/> Practitioner is connected to this clinic account</span>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("clinic")}>Back</button>
                <button className="btn primary lg" disabled={!primaryPractitioner.firstName.trim() || !primaryPractitioner.email.trim() || !primaryPractitioner.certificate.trim()} onClick={() => setStep("admin")}>
                  Continue <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "admin" && (
            <div className="onboarding-step-panel setup-wide form">
              <div className="setup-centered-copy">
                <h3>Add Clinic Administrator</h3>
                <p>The admin role is optional, must be invited by the Clinic Owner, and supports operations without clinical approval authority.</p>
              </div>
              <div className="clinic-form-grid clinic-form-grid-3">
                <div className="field">
                  <div className="field-label">First name</div>
                  <input className="input" value={clinicAdmin.firstName} onChange={e => setClinicAdmin(prev => ({ ...prev, firstName: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Last name</div>
                  <input className="input" value={clinicAdmin.lastName} onChange={e => setClinicAdmin(prev => ({ ...prev, lastName: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Phone</div>
                  <input className="input" value={clinicAdmin.phone} onChange={e => setClinicAdmin(prev => ({ ...prev, phone: e.target.value }))}/>
                </div>
                <div className="field">
                  <div className="field-label">Email</div>
                  <input className="input" value={clinicAdmin.email} onChange={e => setClinicAdmin(prev => ({ ...prev, email: e.target.value }))}/>
                </div>
                <div className="field" style={{gridColumn: "span 2"}}>
                  <div className="field-label">Address</div>
                  <input className="input" value={clinicAdmin.address} onChange={e => setClinicAdmin(prev => ({ ...prev, address: e.target.value }))}/>
                </div>
              </div>
              <div className="vera-rule-grid">
                <div><strong>Can do</strong><span>Manage practitioners, assistants, clients, assignments, communications, orders, and reporting.</span></div>
                <div><strong>Cannot do</strong><span>Be owner, transfer ownership, manage clinic profile/settings, or create/edit/approve clinical content.</span></div>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("practitioner")}>Back</button>
                <button className="btn primary lg" disabled={!clinicAdmin.email.trim()} onClick={() => setStep("plan")}>
                  Continue to plan <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "plan" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="setup-centered-copy">
                <h3>Select plan</h3>
                <p>Basic, Advanced, and Premium determine seats, included monthly credits, and gated product capabilities.</p>
              </div>
              <div className="plan-grid">
                {plans.map(plan => (
                  <button
                    key={plan.id}
                    type="button"
                    className={"plan-card" + (selectedPlan === plan.id ? " selected" : "")}
                    onClick={() => setSelectedPlan(plan.id)}
                  >
                    <span className="plan-card-head">
                      <strong>{plan.name}</strong>
                      <em>{plan.price}</em>
                    </span>
                    <span className="plan-helper">{plan.helper}</span>
                    <span className="plan-metrics">
                      <span>{plan.seats}</span>
                      <span>{plan.credits} credits/mo</span>
                    </span>
                    <span className="plan-features">
                      {plan.features.map(feature => <span key={feature}><I.check size={11}/> {feature}</span>)}
                    </span>
                  </button>
                ))}
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("admin")}>Back</button>
                <button className="btn primary lg" onClick={() => setStep("checkout")}>
                  Continue to checkout <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "checkout" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="setup-centered-copy">
                <h3>Stripe checkout</h3>
                <p>This mock payment step represents Stripe checkout and the Better Auth billing sync that follows a successful payment.</p>
              </div>
              <div className="checkout-grid">
                <div className="checkout-panel">
                  <div className="checkout-panel-title">Selected plan</div>
                  <div className="checkout-plan-name">{selectedPlanOption.name}</div>
                  <div className="checkout-plan-price">{selectedPlanOption.price}</div>
                  <div className="checkout-line"><span>Seats</span><strong>{selectedPlanOption.seats}</strong></div>
                  <div className="checkout-line"><span>Included credits</span><strong>{selectedPlanOption.credits}/month</strong></div>
                  <div className="checkout-line"><span>Clinic</span><strong>{clinicName}</strong></div>
                </div>
                <div className="checkout-panel">
                  <div className="checkout-panel-title">Payment method</div>
                  <div className="payment-card-preview">
                    <I.receipt size={18}/>
                    <div>
                      <strong>Visa ending 4242</strong>
                      <span>Billing owner: {ownerName || "Clinic Owner"}</span>
                    </div>
                  </div>
                  <div className="alert info">
                    <I.externalLink size={15}/>
                    <div>In production this opens Stripe checkout, then returns to Vykon when payment succeeds.</div>
                  </div>
                </div>
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("plan")}>Back</button>
                <button className="btn primary lg" onClick={() => setStep("activation")}>
                  Complete checkout <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "activation" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="onboarding-ready-icon"><I.checkCircle size={30}/></div>
              <div className="setup-centered-copy">
                <h3>Subscription active</h3>
                <p>Stripe, Better Auth billing, Vykon entitlements, and monthly credits are now synced for the clinic.</p>
              </div>
              <div className="activation-list">
                {activationRows.map(row => (
                  <div key={row.label} className="activation-row">
                    <span>{row.icon}</span>
                    <div>
                      <strong>{row.label}</strong>
                      <small>{row.detail}</small>
                    </div>
                    <I.checkCircle size={16}/>
                  </div>
                ))}
              </div>
              <button className="btn primary lg" onClick={() => setStep("team")}>
                Invite team <I.arrowR size={14}/>
              </button>
            </div>
          )}

          {step === "team" && (
            <div className="onboarding-step-panel setup-wide form">
              <div className="setup-centered-copy">
                <h3>Invite clinic team</h3>
                <p>Owner can invite Admins, Practitioners, and Practitioner Assistants. Accepted users sign in, select the active clinic, and receive role-scoped access.</p>
              </div>
              <div className="team-invite-composer">
                <div className="field">
                  <div className="field-label">Email</div>
                  <input className="input" value={inviteEmail} onChange={(event) => setInviteEmail(event.target.value)}/>
                </div>
                <div className="field">
                  <div className="field-label">Role</div>
                  <select className="select" value={inviteRole} onChange={(event) => setInviteRole(event.target.value)}>
                    <option>Admin</option>
                    <option>Practitioner</option>
                    <option>Practitioner Assistant</option>
                  </select>
                </div>
                <button className="btn primary"><I.mail size={13}/> Send invite</button>
              </div>
              <div className="team-invite-list">
                {[{ email: inviteEmail, role: inviteRole, status: "Ready to send" }, ...inviteRows].map((row, index) => (
                  <div key={row.email + index} className="team-invite-row">
                    <span><I.mail size={14}/></span>
                    <div>
                      <strong>{row.email}</strong>
                      <small>{row.role}{row.detail ? ` · ${row.detail}` : ""}</small>
                    </div>
                    <em>{row.status}</em>
                  </div>
                ))}
              </div>
              <div className="auth-actions split">
                <button className="btn ghost lg" onClick={() => setStep("activation")}>Back</button>
                <button className="btn primary lg" onClick={() => setStep("ready")}>
                  Finish setup <I.arrowR size={14}/>
                </button>
              </div>
            </div>
          )}

          {step === "ready" && (
            <div className="onboarding-step-panel setup-wide">
              <div className="onboarding-ready-icon"><I.checkCircle size={30}/></div>
              <div className="setup-centered-copy">
                <h3>Workspace ready</h3>
                <p>{clinicName} is active on {selectedPlanOption.name}. Team invitations are pending and the owner can enter the dashboard.</p>
              </div>
              <div className="setup-summary-grid wide">
                <div><span>Active clinic</span><strong>{clinicName}</strong></div>
                <div><span>Plan</span><strong>{selectedPlanOption.name}</strong></div>
                <div><span>Credits</span><strong>{selectedPlanOption.credits} monthly</strong></div>
                <div><span>Seats</span><strong>{selectedPlanOption.seats}</strong></div>
              </div>
              <button className="btn primary lg" onClick={onComplete}>
                Enter dashboard <I.arrowR size={14}/>
              </button>
            </div>
          )}
        </section>

        <aside className="auth-side-panel">
          <div className="auth-side-title">Activation status</div>
          <div className="auth-readiness-list">
            {readiness.map(item => (
              <div key={item.label} className={"auth-readiness-row" + (item.complete ? " complete" : "")}>
                <span>{item.complete ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div>
                  <strong>{item.label}</strong>
                  <small>{item.detail}</small>
                </div>
              </div>
            ))}
          </div>

          <div className="auth-side-title">{isExistingBranch ? "Existing clinic gates" : "Clinic entitlements"}</div>
          {isExistingBranch ? (
            <div className="auth-readiness-list">
              <div className={"auth-readiness-row" + (stepIndex >= 1 ? " complete" : "")}>
                <span>{stepIndex >= 1 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>Subscription current</strong><small>{activeExistingOrg.plan} plan is active</small></div>
              </div>
              <div className={"auth-readiness-row" + (stepIndex >= 1 ? " complete" : "")}>
                <span>{stepIndex >= 1 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>Credits available</strong><small>{activeExistingOrg.credits} shared organization credits</small></div>
              </div>
              <div className={"auth-readiness-row" + (stepIndex >= 3 ? " complete" : "")}>
                <span>{stepIndex >= 3 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>Role scoped</strong><small>{activeExistingOrg.role} access for active clinic</small></div>
              </div>
            </div>
          ) : (
            <div className="auth-readiness-list">
              <div className={"auth-readiness-row" + (stepIndex >= setupOffset + 5 ? " complete" : "")}>
                <span>{stepIndex >= setupOffset + 5 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>subscription_entitlements</strong><small>{selectedPlanOption.name} seats, features, and limits</small></div>
              </div>
              <div className={"auth-readiness-row" + (stepIndex >= setupOffset + 5 ? " complete" : "")}>
                <span>{stepIndex >= setupOffset + 5 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>Monthly credits</strong><small>{selectedPlanOption.credits} included credits</small></div>
              </div>
              <div className={"auth-readiness-row" + (stepIndex >= setupOffset + 6 ? " complete" : "")}>
                <span>{stepIndex >= setupOffset + 6 ? <I.check size={12}/> : <I.clock size={12}/>}</span>
                <div><strong>Team invitations</strong><small>Admins, Practitioners, and Assistants</small></div>
              </div>
            </div>
          )}
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { LoginView, OnboardingView });
