/**
 * What the plugin's PHP hands the bundle (ACC-404), as the
 * `accessibitAdminConfig` global set with `wp_add_inline_script(…, "before")`.
 * The API key is NOT in it: every call goes through the plugin's own REST
 * routes, which add the key server-side.
 */
import type { TrackerLinks } from "../tracker/types";
import type { AccessibilityConfig } from "./accessibility/types";
import type { SetupConfig } from "./setup/types";

export interface WpAdminConfig {
  /** `tracker` from plugin 1.2.0 (ACC-412); `setup` and `accessibility` are
   * the screens the app draws over the plugin's PHP views. */
  page: "widget" | "statement" | "tracker" | "setup" | "accessibility";
  /** `rest_url( 'accessibit/v1' )`, pretty or `?rest_route=` form. */
  restRoot: string;
  /** `wp_create_nonce( 'wp_rest' )`. */
  nonce: string;
  /**
   * `admin-ajax.php?action=rest-nonce`, where core hands a signed-in admin a
   * fresh `wp_rest` nonce. Absent from a plugin older than ACC-411.
   */
  nonceUrl?: string;
  /** `determine_locale()`, e.g. `it_IT`: the locale wp-admin's own strings
   * around the bundle were loaded in. */
  locale: string;
  /**
   * Whether the plugin's own strings are translated into `locale`: a catalog
   * it ships (it_IT, es_ES) or a language pack. The screens follow it, so
   * wp-admin's menu and notices and the bundle around them speak one language
   * (ACC-411). Absent from a plugin older than that: the locale decides alone.
   */
  stringsTranslated?: boolean;
  /** The AccessiBit site this install is connected to. On the Setup screen,
   * which also opens before there is one, `name` is this install's address. */
  site: { id: string; name: string; url: string };
  /**
   * Whether the page may save: false only on the statement page of a site
   * whose plan no longer includes the statement but which published one.
   */
  canEdit: boolean;
  /**
   * The site's homepage in the widget's preview mode, for the Tools tab's
   * preview (ACC-404): set on the widget page only, and honoured by the
   * plugin only for an administrator with this nonce.
   */
  previewUrl?: string;
  /** audit-api's origin, for the public statement link. */
  apiOrigin: string;
  /**
   * The site's audits in the AccessiBit dashboard, for the statement page's
   * "no audit results yet" notice. Absent from a plugin older than ACC-411.
   */
  auditsUrl?: string;
  /**
   * The Tracker screen's links (ACC-412): the dashboard's pages for the site,
   * the wizard that activates it, and the plugin's Setup. Tracker page only.
   */
  trackerLinks?: TrackerLinks;
  /** The Setup screen's: the connection and where its buttons lead. */
  setup?: SetupConfig;
  /** The Accessibility screen's: the connection, its links and its words. */
  accessibility?: AccessibilityConfig;
  /** Seeds for a first statement; all optional. */
  companyName?: string | null;
  userName?: string | null;
  userEmail?: string | null;
}

export const UI_LOCALES = ["en", "it", "es"] as const;
export type UiLocale = (typeof UI_LOCALES)[number];

/** `it_IT` → `it`; anything the dashboard dictionaries lack → `en`. */
export function toUiLocale(wpLocale: string | undefined): UiLocale {
  const lang = (wpLocale ?? "").slice(0, 2).toLowerCase();
  return (UI_LOCALES as readonly string[]).includes(lang)
    ? (lang as UiLocale)
    : "en";
}

/** The bundle's language: the locale's, when the plugin's strings are in it. */
export function uiLocaleOf(
  config: Pick<WpAdminConfig, "locale" | "stringsTranslated">,
): UiLocale {
  return config.stringsTranslated === false ? "en" : toUiLocale(config.locale);
}

/**
 * `it_IT` → `it-IT`, for `Intl`. Some WordPress locales are not valid tags
 * (`pt_PT_ao90`) and would make `Intl` throw, so those fall back to their
 * language and region, then to `en`.
 */
export function toBcp47(wpLocale: string | undefined): string {
  const tag = (wpLocale || "en").replace(/_/g, "-");
  for (const candidate of [tag, tag.split("-").slice(0, 2).join("-")]) {
    try {
      const [canonical] = Intl.getCanonicalLocales(candidate);
      if (canonical) return canonical;
    } catch {
      // not a valid tag
    }
  }
  return "en";
}
