"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useMemo } from "react";
import { Key, ChevronDown, User, Shield, Crown, ShieldCheck, UserCircle } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover.js";
import { Button } from "../ui/button.js";
import { Badge } from "../ui/badge.js";
import { sel } from "../../lib/test/index.js";
function parseTeamRoles(teamRoles) {
  if (!teamRoles) return [];
  const hasHighlight = teamRoles.includes("\u2B50");
  const cleanRoles = teamRoles.replace("\u2B50", "").trim();
  return cleanRoles.split(",").map((part, index, arr) => {
    const trimmed = part.trim();
    const match = trimmed.match(/^(.+?)\s*\((\w+)\)$/);
    if (match) {
      const [, team, role] = match;
      return {
        team: team.trim(),
        role: role.toLowerCase(),
        // Highlight the last item if star was present
        isHighlighted: hasHighlight && index === arr.length - 1
      };
    }
    return {
      team: trimmed,
      role: "member",
      isHighlighted: false
    };
  });
}
function getRoleBadgeStyle(role, isHighlighted) {
  const baseClass = "text-[9px] px-1.5 py-0 h-4 font-medium gap-0.5";
  if (isHighlighted) {
    return {
      className: `${baseClass} bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-900/30 dark:text-amber-400 dark:border-amber-700`,
      icon: Crown
    };
  }
  switch (role) {
    case "owner":
      return {
        className: `${baseClass} bg-purple-100 text-purple-800 border-purple-300 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-700`,
        icon: Crown
      };
    case "admin":
      return {
        className: `${baseClass} bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-700`,
        icon: ShieldCheck
      };
    case "member":
    default:
      return {
        className: `${baseClass} bg-slate-100 text-slate-700 border-slate-300 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-600`,
        icon: UserCircle
      };
  }
}
function UserRoleBadges({ teamRoles }) {
  const parsedRoles = useMemo(() => parseTeamRoles(teamRoles), [teamRoles]);
  if (parsedRoles.length === 0) return null;
  return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1 mt-1", children: parsedRoles.map((parsed, idx) => {
    const style = getRoleBadgeStyle(parsed.role, parsed.isHighlighted);
    const Icon = style.icon;
    return /* @__PURE__ */ jsxs(
      Badge,
      {
        variant: "outline",
        className: style.className,
        children: [
          /* @__PURE__ */ jsx(Icon, { className: "h-2.5 w-2.5" }),
          /* @__PURE__ */ jsx("span", { className: "truncate max-w-[120px]", children: parsed.team }),
          /* @__PURE__ */ jsxs("span", { className: "opacity-60", children: [
            "(",
            parsed.role,
            ")"
          ] })
        ]
      },
      `${parsed.team}-${idx}`
    );
  }) });
}
function DevKeyring({ config }) {
  var _a;
  const [isOpen, setIsOpen] = useState(false);
  if (process.env.NODE_ENV === "production") return null;
  if (!(config == null ? void 0 : config.enabled) || !((_a = config.users) == null ? void 0 : _a.length)) return null;
  const fillForm = useCallback((email, password) => {
    const showEmailButton = document.querySelector('[data-cy="login-show-email"]');
    if (showEmailButton) {
      showEmailButton.click();
      setTimeout(() => fillInputs(email, password), 100);
    } else {
      fillInputs(email, password);
    }
    setIsOpen(false);
  }, []);
  const fillInputs = (email, password) => {
    var _a2;
    const emailInput = document.getElementById("email");
    const passwordInput = document.getElementById("password");
    if (emailInput && passwordInput) {
      const nativeInputValueSetter = (_a2 = Object.getOwnPropertyDescriptor(
        window.HTMLInputElement.prototype,
        "value"
      )) == null ? void 0 : _a2.set;
      nativeInputValueSetter == null ? void 0 : nativeInputValueSetter.call(emailInput, email);
      nativeInputValueSetter == null ? void 0 : nativeInputValueSetter.call(passwordInput, password);
      emailInput.dispatchEvent(new Event("input", { bubbles: true }));
      passwordInput.dispatchEvent(new Event("input", { bubbles: true }));
    }
  };
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex justify-center mt-4",
      "data-cy": sel("auth.devKeyring.container"),
      children: /* @__PURE__ */ jsxs(Popover, { open: isOpen, onOpenChange: setIsOpen, children: [
        /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "text-xs text-muted-foreground hover:text-foreground gap-1.5",
            "data-cy": sel("auth.devKeyring.trigger"),
            children: [
              /* @__PURE__ */ jsx(Key, { className: "h-3 w-3" }),
              /* @__PURE__ */ jsx("span", { children: "Dev Keyring" }),
              /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" })
            ]
          }
        ) }),
        /* @__PURE__ */ jsxs(
          PopoverContent,
          {
            className: "w-80 p-0",
            align: "center",
            "data-cy": sel("auth.devKeyring.content"),
            children: [
              /* @__PURE__ */ jsxs("div", { className: "px-3 py-2 border-b", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(Shield, { className: "h-4 w-4 text-amber-500" }),
                  /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Test Credentials" }),
                  /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-[10px] px-1.5 py-0", children: "DEV ONLY" })
                ] }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "Select a user to auto-fill the login form" })
              ] }),
              /* @__PURE__ */ jsx("div", { className: "max-h-[400px] overflow-y-auto", children: /* @__PURE__ */ jsx("div", { className: "p-1", children: config.users.map((user, index) => /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  onClick: () => fillForm(user.email, user.password),
                  className: "w-full text-left px-3 py-2 rounded-sm hover:bg-accent transition-colors",
                  "data-cy": sel("auth.devKeyring.user", { index }),
                  children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
                    /* @__PURE__ */ jsx(User, { className: "h-4 w-4 text-muted-foreground mt-0.5 shrink-0" }),
                    /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
                      /* @__PURE__ */ jsx("div", { className: "text-sm font-medium truncate", children: user.name }),
                      /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: user.email }),
                      /* @__PURE__ */ jsx(UserRoleBadges, { teamRoles: user.teamRoles })
                    ] })
                  ] })
                },
                user.id || user.email
              )) }) }),
              /* @__PURE__ */ jsxs("div", { className: "px-3 py-2 border-t text-[10px] text-muted-foreground text-center space-y-0.5", children: [
                /* @__PURE__ */ jsxs("div", { children: [
                  "Core: ",
                  /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "Pandora1234" })
                ] }),
                /* @__PURE__ */ jsxs("div", { children: [
                  "Demo: ",
                  /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "Test1234" })
                ] })
              ] })
            ]
          }
        )
      ] })
    }
  );
}
export {
  DevKeyring
};
