import { accountDisplayName, accountStatusLabel, visibleAccountOptions } from "./account-display.js";
import { AccountIdentity } from "./AccountIdentity.jsx";
import { useI18n } from "../../shared/I18nProvider.jsx";

const errorKey = {
  account_config_write_failed: "account.configWriteFailed",
  account_login_rate_limited: "account.rateLimited",
  account_login_start_failed: "account.loginStartFailed"
};

export function AccountsPanel({ accounts, manager, accountMosaic = false }) {
  const { t } = useI18n();
  const visibleAccounts = visibleAccountOptions(accounts);

  function remove(account) {
    const message = t("account.removeConfirm", { name: accountDisplayName(account, accounts) });
    if (window.confirm(message)) manager.remove(account.id);
  }

  return <section className="accounts-panel">
    {manager.error && manager.error !== "account_login_rate_limited" && <p className="account-error" role="alert">{t(errorKey[manager.error] ?? "account.error")}</p>}
    <div className="account-list">
      {visibleAccounts.length === 0 && <p className="account-empty">{t("account.empty")}</p>}
      {visibleAccounts.map((account) => <article className="account-row" key={account.id}>
        <div><strong><AccountIdentity account={account} accounts={accounts} mosaic={accountMosaic} />{account.entitlementLocked && <span aria-label="Pro 잠금"> 🔒 Pro</span>}</strong><span>{accountStatusLabel(account)}</span></div>
        <button className="account-remove" type="button" disabled={manager.pending} onClick={() => remove(account)}>{manager.pendingAccountId === account.id ? t("account.removing") : t("account.remove")}</button>
      </article>)}
    </div>
    <button className="account-add-trigger" type="button" disabled={manager.pending} onClick={(event) => { event.stopPropagation(); manager.add(); }}>{manager.pending && !manager.pendingAccountId ? t("account.starting") : t("account.add")}</button>
    {manager.error === "account_login_rate_limited" && <p className="account-login-rate-limit" role="alert">{t("account.rateLimited")}</p>}
    <p className="account-note">{t("account.note")}</p>
  </section>;
}
