var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import * as appstate from '../../appstate.js';
import { viewHostCss } from '../shared/css.js';
import { DeesElement, css, cssManager, customElement, html, state, } from '@design.estate/dees-element';
let OpsViewUsers = (() => {
    let _classDecorators = [customElement('ops-view-users')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _usersState_decorators;
    let _usersState_initializers = [];
    let _usersState_extraInitializers = [];
    let _loginState_decorators;
    let _loginState_initializers = [];
    let _loginState_extraInitializers = [];
    var OpsViewUsers = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _usersState_decorators = [state()];
            _loginState_decorators = [state()];
            __esDecorate(this, null, _usersState_decorators, { kind: "accessor", name: "usersState", static: false, private: false, access: { has: obj => "usersState" in obj, get: obj => obj.usersState, set: (obj, value) => { obj.usersState = value; } }, metadata: _metadata }, _usersState_initializers, _usersState_extraInitializers);
            __esDecorate(this, null, _loginState_decorators, { kind: "accessor", name: "loginState", static: false, private: false, access: { has: obj => "loginState" in obj, get: obj => obj.loginState, set: (obj, value) => { obj.loginState = value; } }, metadata: _metadata }, _loginState_initializers, _loginState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewUsers = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #usersState_accessor_storage = __runInitializers(this, _usersState_initializers, {
            users: [],
            isLoading: false,
            error: null,
            lastUpdated: 0,
        });
        get usersState() { return this.#usersState_accessor_storage; }
        set usersState(value) { this.#usersState_accessor_storage = value; }
        #loginState_accessor_storage = (__runInitializers(this, _usersState_extraInitializers), __runInitializers(this, _loginState_initializers, {
            identity: null,
            isLoggedIn: false,
        }));
        get loginState() { return this.#loginState_accessor_storage; }
        set loginState(value) { this.#loginState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _loginState_extraInitializers);
            const usersSub = appstate.usersStatePart
                .select((s) => s)
                .subscribe((usersState) => {
                this.usersState = usersState;
            });
            this.rxSubscriptions.push(usersSub);
            const loginSub = appstate.loginStatePart
                .select((s) => s)
                .subscribe((loginState) => {
                this.loginState = loginState;
                // Re-fetch users when user logs in (fixes race condition where
                // the view is created before authentication completes)
                if (loginState.isLoggedIn) {
                    appstate.usersStatePart.dispatchAction(appstate.fetchUsersAction, null);
                }
            });
            this.rxSubscriptions.push(loginSub);
        }
        static styles = [
            cssManager.defaultStyles,
            viewHostCss,
            css `
      .usersContainer {
        display: flex;
        flex-direction: column;
        gap: 24px;
      }

      .roleBadge {
        display: inline-flex;
        align-items: center;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        letter-spacing: 0.02em;
        text-transform: uppercase;
      }

      .roleBadge.admin {
        background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
        color: ${cssManager.bdTheme('#92400e', '#fbbf24')};
      }

      .roleBadge.user {
        background: ${cssManager.bdTheme('#e0f2fe', '#0c4a6e')};
        color: ${cssManager.bdTheme('#075985', '#7dd3fc')};
      }

      .sessionBadge {
        display: inline-flex;
        align-items: center;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        letter-spacing: 0.02em;
        text-transform: uppercase;
        background: ${cssManager.bdTheme('#dcfce7', '#14532d')};
        color: ${cssManager.bdTheme('#166534', '#4ade80')};
      }

      .userIdCell {
        font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
        font-size: 11px;
        color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
      }
    `,
        ];
        render() {
            const { users } = this.usersState;
            const currentUserId = this.loginState.identity?.userId;
            return html `
      <dees-heading level="3">Users</dees-heading>

      <div class="usersContainer">
        <dees-table
          .heading1=${'Users'}
          .heading2=${'OpsServer user accounts'}
          .data=${users}
          .dataName=${'user'}
          .searchable=${true}
          .showColumnFilters=${true}
          .displayFunction=${(user) => ({
                ID: html `<span class="userIdCell">${user.id}</span>`,
                Email: user.email || user.username,
                Name: user.name || '',
                Role: this.renderRoleBadge(user.role),
                Status: user.status || 'active',
                Auth: (user.authSources || []).join(', ') || 'bootstrap',
                Session: user.id === currentUserId
                    ? html `<span class="sessionBadge">current</span>`
                    : '',
            })}
          .dataActions=${[
                {
                    name: 'Create User',
                    iconName: 'lucide:userPlus',
                    type: ['header'],
                    actionFunc: async () => await this.showCreateUserDialog(),
                },
                {
                    name: 'Delete',
                    iconName: 'lucide:trash2',
                    type: ['inRow', 'contextmenu'],
                    actionFunc: async (actionData) => {
                        await this.showDeleteUserDialog(actionData.item);
                    },
                },
            ]}
        ></dees-table>
      </div>
    `;
        }
        renderRoleBadge(role) {
            const cls = role === 'admin' ? 'admin' : 'user';
            return html `<span class="roleBadge ${cls}">${role}</span>`;
        }
        async showCreateUserDialog() {
            const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
            await DeesModal.createAndShow({
                heading: 'Create User',
                content: html `
        <dees-form>
          <dees-input-text .key=${'email'} .label=${'Email'} .required=${true}></dees-input-text>
          <dees-input-text .key=${'name'} .label=${'Display name'}></dees-input-text>
          <dees-input-dropdown
            .key=${'role'}
            .label=${'Role'}
            .options=${[
                    { option: 'User', key: 'user' },
                    { option: 'Admin', key: 'admin' },
                ]}
            .selectedOption=${{ option: 'User', key: 'user' }}
            .required=${true}
          ></dees-input-dropdown>
          <dees-input-text .key=${'password'} .label=${'Password'} .required=${true} .isPasswordBool=${true}></dees-input-text>
          <dees-input-text .key=${'passwordConfirm'} .label=${'Confirm password'} .required=${true} .isPasswordBool=${true}></dees-input-text>
          <dees-input-checkbox
            .key=${'enableIdpGlobalAuth'}
            .label=${'Allow idp.global login for this email'}
            .description=${'Uses https://idp.global by default; the local dcrouter account and role remain authoritative.'}
          ></dees-input-checkbox>
        </dees-form>
      `,
                menuOptions: [
                    {
                        name: 'Cancel',
                        iconName: 'lucide:x',
                        action: async (modalArg) => await modalArg.destroy(),
                    },
                    {
                        name: 'Create',
                        iconName: 'lucide:userPlus',
                        action: async (modalArg) => {
                            const form = modalArg.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            const email = String(data.email || '').trim();
                            const name = String(data.name || '').trim();
                            const password = String(data.password || '');
                            const passwordConfirm = String(data.passwordConfirm || '');
                            const roleValue = String(data.role?.key ?? data.role ?? 'user');
                            if (!email || !password) {
                                form.setStatus?.('error', 'Email and password are required.');
                                return;
                            }
                            if (password !== passwordConfirm) {
                                form.setStatus?.('error', 'Passwords do not match.');
                                return;
                            }
                            form.setStatus?.('pending', 'Creating user...');
                            await appstate.usersStatePart.dispatchAction(appstate.createUserAction, {
                                email,
                                name,
                                role: roleValue === 'admin' ? 'admin' : 'user',
                                password,
                                enableIdpGlobalAuth: Boolean(data.enableIdpGlobalAuth),
                            });
                            const state = appstate.usersStatePart.getState();
                            if (state?.error) {
                                form.setStatus?.('error', state.error);
                                return;
                            }
                            DeesToast.show({ message: `User created for ${email}`, type: 'success', duration: 3000 });
                            await modalArg.destroy();
                        },
                    },
                ],
            });
        }
        async showDeleteUserDialog(userArg) {
            const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
            const currentUserId = this.loginState.identity?.userId;
            if (userArg.id === currentUserId) {
                DeesToast.show({ message: 'You cannot delete the current user.', type: 'error', duration: 4000 });
                return;
            }
            await DeesModal.createAndShow({
                heading: 'Delete User',
                content: html `
        <div style="padding: 8px 0; font-size: 14px; line-height: 1.5;">
          <p>Delete <strong>${userArg.email || userArg.username}</strong>?</p>
          <p style="color: #f59e0b; margin-top: 12px;">This removes the local dcrouter account and cannot be undone.</p>
        </div>
      `,
                menuOptions: [
                    {
                        name: 'Cancel',
                        iconName: 'lucide:x',
                        action: async (modalArg) => await modalArg.destroy(),
                    },
                    {
                        name: 'Delete',
                        iconName: 'lucide:trash2',
                        action: async (modalArg) => {
                            await appstate.usersStatePart.dispatchAction(appstate.deleteUserAction, userArg.id);
                            const state = appstate.usersStatePart.getState();
                            if (state?.error) {
                                DeesToast.show({ message: state.error, type: 'error', duration: 4000 });
                                return;
                            }
                            DeesToast.show({ message: 'User deleted.', type: 'success', duration: 3000 });
                            await modalArg.destroy();
                        },
                    },
                ],
            });
        }
        async firstUpdated() {
            if (this.loginState.isLoggedIn) {
                await appstate.usersStatePart.dispatchAction(appstate.fetchUsersAction, null);
            }
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewUsers = _classThis;
})();
export { OpsViewUsers };
//# sourceMappingURL=data:application/json;base64, 