import "keycloak-headless/provider";
import { useKeycloakAuth } from "keycloak-headless/solid";
import { Show, createMemo } from "solid-js";

import { realmRolesAttr } from "./realm-roles-attr.js";

export function App() {
  let host: HTMLDivElement | undefined;
  const auth = useKeycloakAuth(() => host ?? null);

  const keycloak = createMemo(() => auth().keycloak);
  const authenticated = createMemo(() => auth().authenticated);
  const error = createMemo(() => auth().error);

  return (
    <kc-provider
      url="__KEYCLOAK_URL__"
      realm="__KEYCLOAK_REALM__"
      client-id="__KEYCLOAK_CLIENT_ID__"
    >
      <div ref={host} style={{ "font-family": "system-ui", padding: "1rem" }}>
        <h1>kc-provider + Solid</h1>

        <Show when={!keycloak() && !error()}>
          <p>Initializing Keycloak…</p>
        </Show>

        <Show when={error()}>
          <p style={{ color: "crimson" }}>
            Init error (expected if Keycloak is not running):{" "}
            {String((error() as Error)?.message ?? error())}
          </p>
        </Show>

        <Show when={keycloak()}>
          <p>Authenticated: {String(authenticated())}</p>

          <kc-render-authenticated>
            <p style={{ background: "#e8f5e9", padding: "0.5rem" }}>
              Members-only: you are signed in (via{" "}
              <code>kc-render-authenticated</code>).
            </p>
            <p>
              <kc-account-link>
                <button type="button">Account console</button>
              </kc-account-link>{" "}
              — via <code>kc-account-link</code>{" "}
              <kc-logout-button>
                <button type="button">Logout</button>
              </kc-logout-button>{" "}
              — via <code>kc-logout-button</code>
            </p>
            <kc-render-roles
              roles={realmRolesAttr("admin")}
              role-kind="realm"
              match="any"
            >
              <p style={{ background: "#e3f2fd", padding: "0.5rem" }}>
                You have the configured realm role (via{" "}
                <code>kc-render-roles</code>).
              </p>
            </kc-render-roles>
          </kc-render-authenticated>

          <kc-render-guest>
            <p style={{ background: "#fff3e0", padding: "0.5rem" }}>
              <kc-login-button>
                <button type="button">Get started (guest)</button>
              </kc-login-button>{" "}
              — login via <code>kc-login-button</code> inside{" "}
              <code>kc-render-guest</code>
            </p>
          </kc-render-guest>
        </Show>
      </div>
    </kc-provider>
  );
}
