// Sign in with CodeB - React (react-oidc-context).
// European Digital Identity Wallet users can also sign in via the wallet
// button; see verifier-integration-cookbook.html for the widget recipe.
// [oidc-signin-cookbook 2026-07-23]
// npm install react-oidc-context oidc-client-ts

import React from "react";
import { AuthProvider, useAuth } from "react-oidc-context";

const oidcConfig = {
  authority:          "https://<CODEB_TENANT_HOST>",
  client_id:          "<YOUR_CLIENT_ID>",
  redirect_uri:       "<APP_CALLBACK>",
  response_type:      "code",
  scope:              "openid profile email",
  post_logout_redirect_uri: window.location.origin,
  // PKCE (S256) is on by default in oidc-client-ts.
  // Discovery -> https://<host>/.well-known/openid-configuration
};

function Profile(){
  const auth = useAuth();
  if (auth.isLoading) return <p>Loading...</p>;
  if (auth.error)     return <p>Error: {auth.error.message}</p>;
  if (!auth.isAuthenticated){
    return <button onClick={() => auth.signinRedirect()}>Sign in with CodeB</button>;
  }
  const u = auth.user.profile;
  return (
    <div>
      <p>Signed in as {u.preferred_username} (role={u.role || "user"})</p>
      <button onClick={() => auth.signoutRedirect()}>Sign out</button>
    </div>
  );
}

export default function App(){
  return (
    <AuthProvider {...oidcConfig}>
      <Profile />
    </AuthProvider>
  );
}
