import { __, _n, sprintf } from '@wordpress/i18n';

/**
 * L'API ne renvoie que des identifiants et des statuts, jamais de texte: chaque interface traduit.
 * C'est ce qui permet a l'ecran WordPress et a l'ecran Shopify de dire la meme chose sans partager
 * une seule chaine, et a un marchand francais de ne jamais lire « feed_config_incomplete ».
 *
 * Regle de repli: un identifiant inconnu s'affiche tel quel plutot que de disparaitre. Le test de
 * couverture des libelles rend le cas rare, il ne le rend pas impossible.
 */

const label = (dictionary: Record<string, string>, key: string): string => dictionary[key] ?? key;

export const stepTitle = (id: string): string =>
  label(
    {
      connect_store: __('Connect your store', 'convrail'),
      link_ads_account: __('Link your ChatGPT Ads account', 'convrail'),
      activate_tracking: __('Activate tracking on your store', 'convrail'),
      first_event: __('Receive a first event', 'convrail'),
      sync_catalog: __('Retrieve your products', 'convrail'),
      describe_store: __('Describe your store for ChatGPT', 'convrail'),
      deliver_catalog: __('Send the catalog to OpenAI', 'convrail'),
      go_live: __('Switch to live mode', 'convrail'),
    },
    id,
  );

export const stepStatus = (status: string): string =>
  label(
    {
      todo: __('To do', 'convrail'),
      in_progress: __('In progress', 'convrail'),
      done: __('Done', 'convrail'),
      error: __('Needs fixing', 'convrail'),
      skipped: __('Skipped', 'convrail'),
      locked: __('Locked', 'convrail'),
      unavailable: __('Not available here', 'convrail'),
    },
    status,
  );

export const stepReason = (reason: string): string =>
  label(
    {
      needs_credentials: __('Add your ChatGPT Ads key first.', 'convrail'),
      needs_tracking: __('Activate tracking first.', 'convrail'),
      needs_feed_config: __(
        'Describe your store first: without a store name and the countries you sell to, the feed cannot be built.',
        'convrail',
      ),
      needs_credentials_and_event: __(
        'Add your key and receive a first event before going live.',
        'convrail',
      ),
      credentials_refused: __('OpenAI refused these credentials.', 'convrail'),
      openai_unreachable: __('OpenAI could not be reached.', 'convrail'),
      delivery_failed: __('The last delivery to OpenAI failed.', 'convrail'),
      generation_failed: __('The last feed could not be built.', 'convrail'),
      feed_config_incomplete: __(
        'Your store name or the countries you sell to are missing.',
        'convrail',
      ),
    },
    reason,
  );

export const deliveryStatus = (status: string): string =>
  label(
    {
      pending: __('Sending', 'convrail'),
      delivered: __('Sent', 'convrail'),
      retrying: __('Retrying', 'convrail'),
      failed: __('Failed', 'convrail'),
      skipped: __('Not sent', 'convrail'),
      unchanged: __('Nothing new to send', 'convrail'),
      deferred: __('Postponed', 'convrail'),
      interrupted: __('Interrupted: the next delivery replaces it', 'convrail'),
      empty: __('Not sent: no product is ready to send yet', 'convrail'),
    },
    status,
  );

export const openaiStatus = (status: string): string =>
  label(
    {
      completed: __('Accepted', 'convrail'),
      completed_with_errors: __('Accepted with errors', 'convrail'),
      skipped: __('Ignored by OpenAI', 'convrail'),
      failed: __('Refused', 'convrail'),
      timeout: __('No answer yet', 'convrail'),
      scanning: __('Being checked', 'convrail'),
      received: __('Received', 'convrail'),
      processing: __('Being processed', 'convrail'),
    },
    status,
  );

export const alertTitle = (type: string): string =>
  label(
    {
      volume_drop: __('Sales dropped sharply', 'convrail'),
      capi_errors: __('Events refused by OpenAI', 'convrail'),
      pixel_broken: __('Tracking stopped reporting', 'convrail'),
      feed_delivery_failed: __('The catalog could not be sent', 'convrail'),
      product_losing_money: __('A product is losing money', 'convrail'),
      out_of_stock_advertised: __('An out-of-stock product is being advertised', 'convrail'),
    },
    type,
  );

/**
 * Detail d'une alerte, compose ici a partir du type et des valeurs.
 *
 * Le serveur envoie aussi une phrase anglaise (`message`), qui sert aux journaux et aux courriels.
 * L'afficher telle quelle donnait « 1 send(s) to OpenAI failed for good in the last hour » a un
 * marchand francais: elle ne sert donc que de repli, pour un type qu'on ne connaitrait pas.
 */
export const alertDetail = (
  type: string,
  params: Record<string, string | number> | null | undefined,
  fallback: string,
): string => {
  const value = (key: string) => String(params?.[key] ?? '');
  /*
   * Les alertes creees avant que les parametres soient stockes n'en portent aucun. Sans ce
   * garde-fou, la phrase s'affichait amputee de son chiffre (« envoi(s) vers OpenAI ont
   * definitivement echoue »), ce qui donne une alerte a moitie ecrite sur l'ecran d'un marchand.
   */
  const has = (key: string) => params?.[key] !== undefined && params?.[key] !== null;
  const others = Number(params?.others ?? 0);
  const alsoOthers =
    others > 0
      ? ' ' +
        sprintf(
          /* translators: %d: number of other products concerned. */
          _n(
            '%d other product is affected too.',
            '%d other products are affected too.',
            others,
            'convrail',
          ),
          others,
        )
      : '';
  switch (type) {
    case 'volume_drop':
      return has('events') && has('baseline')
        ? sprintf(
            /* translators: %1$s: events received, %2$s: usual daily number. */
            __(
              'Only %1$s events in the last 24 hours, against about %2$s on a normal day. Some sales may be going uncounted.',
              'convrail',
            ),
            value('events'),
            value('baseline'),
          )
        : __(
            'Tracking volume fell sharply in the last 24 hours, against a normal day. Some sales may be going uncounted.',
            'convrail',
          );
    case 'capi_errors':
      return has('batches')
        ? sprintf(
            /* translators: %s: number of failed sends. */
            _n(
              '%s send to OpenAI could not be delivered in the last hour, even after retries, so some sales were not reported. Check your Conversions key in Settings.',
              '%s sends to OpenAI could not be delivered in the last hour, even after retries, so some sales were not reported. Check your Conversions key in Settings.',
              Number(params?.batches ?? 0),
              'convrail',
            ),
            value('batches'),
          )
        : __(
            'Sends to OpenAI could not be delivered in the last hour, even after retries, so some sales were not reported. Check your Conversions key in Settings.',
            'convrail',
          );
    case 'pixel_broken':
      return __(
        'Your store keeps receiving orders, but the pixel has reported no visit in the last 24 hours: it looks broken or blocked.',
        'convrail',
      );
    case 'feed_delivery_failed':
      return has('runs')
        ? sprintf(
            /* translators: %s: number of failed deliveries. */
            _n(
              '%s catalog delivery failed in the last 24 hours, so ChatGPT does not have your latest catalog.',
              '%s catalog deliveries failed in the last 24 hours, so ChatGPT does not have your latest catalog.',
              Number(params?.runs ?? 0),
              'convrail',
            ),
            value('runs'),
          )
        : __(
            'A catalog delivery failed in the last 24 hours, so ChatGPT does not have your latest catalog.',
            'convrail',
          );
    case 'product_losing_money':
      return (
        sprintf(
          /* translators: %1$s: product, %2$s: amount, %3$s: currency, %4$s: total lost. */
          __(
            '%1$s cost %2$s %3$s more in ads than it earned over 30 days. Total lost: %4$s %3$s.',
            'convrail',
          ),
          value('product'),
          value('amount'),
          value('currency'),
          value('total'),
        ) + alsoOthers
      );
    case 'out_of_stock_advertised':
      return (
        sprintf(
          /* translators: %1$s: product, %2$s: amount spent, %3$s: currency. */
          __(
            '%1$s is out of stock and still being advertised. %2$s %3$s spent on products you cannot ship.',
            'convrail',
          ),
          value('product'),
          value('wasted'),
          value('currency'),
        ) + alsoOthers
      );
    default:
      return fallback;
  }
};

export const severityLabel = (severity: string): string =>
  label(
    {
      critical: __('Critical', 'convrail'),
      warning: __('Warning', 'convrail'),
      info: __('For information', 'convrail'),
    },
    severity,
  );

export const eventName = (type: string): string =>
  label(
    {
      page_viewed: __('Page viewed', 'convrail'),
      product_viewed: __('Product viewed', 'convrail'),
      collection_viewed: __('Collection viewed', 'convrail'),
      search_submitted: __('Search', 'convrail'),
      add_to_cart: __('Added to cart', 'convrail'),
      product_added_to_cart: __('Added to cart', 'convrail'),
      checkout_started: __('Checkout started', 'convrail'),
      checkout_completed: __('Order placed', 'convrail'),
      // Types ecrits par l'API (taxonomie OpenAI): ce sont eux que l'ecran Activite recoit. Sans
      // eux, un marchand francais lisait « order_created » ou « contents_viewed ».
      contents_viewed: __('Product viewed', 'convrail'),
      items_added: __('Added to cart', 'convrail'),
      order_created: __('Order placed', 'convrail'),
      lead_created: __('Contact request', 'convrail'),
      registration_completed: __('Sign-up', 'convrail'),
      appointment_scheduled: __('Appointment booked', 'convrail'),
      subscription_created: __('Subscription', 'convrail'),
      trial_started: __('Trial started', 'convrail'),
    },
    type,
  );

/** Motifs de rejet du flux: memes codes que l'ecran Shopify, meme exigence de phrase. */
export const rejectReason = (code: string, message: string): string => {
  const dictionary: Record<string, string> = {
    feed_config_incomplete: __(
      'Fill in this setting, then save: the feed cannot be built without it.',
      'convrail',
    ),
    item_id_required: __('This product has no stable identifier.', 'convrail'),
    item_id_too_long: __('The product identifier is too long.', 'convrail'),
    title_required: __('Add a title.', 'convrail'),
    title_too_long: __('The title is too long.', 'convrail'),
    title_all_caps: __('Write the title in normal case, not in full capitals.', 'convrail'),
    description_required: __('Add a description.', 'convrail'),
    description_too_long: __('The description is too long.', 'convrail'),
    description_html: __('The description contains HTML. Use plain text.', 'convrail'),
    url_invalid: __('The product page needs a full address starting with https://.', 'convrail'),
    brand_required: __('Add a brand, or set a default brand above.', 'convrail'),
    brand_placeholder: __('"Unknown" or "N/A" is not a brand. Use the real one.', 'convrail'),
    brand_too_long: __('The brand is too long.', 'convrail'),
    // Meme regle que l'ecran Ameliorer: pas d'image => en ajouter une; adresse illisible => https.
    image_missing: __('Add a product image so this product can appear in ChatGPT.', 'convrail'),
    image_url_invalid: __('The image needs a full address starting with https://.', 'convrail'),
    image_url_format: __('The image must be a JPEG or a PNG.', 'convrail'),
    price_format: __('The price must read like "25.99 EUR".', 'convrail'),
    price_not_positive: __('The price must be greater than zero.', 'convrail'),
    sale_price_format: __('The sale price must read like "19.99 EUR".', 'convrail'),
    sale_price_not_positive: __('The sale price must be greater than zero.', 'convrail'),
    sale_price_currency_mismatch: __(
      'The sale price uses a different currency from the price.',
      'convrail',
    ),
    sale_price_not_lower: __('The sale price must be lower than the price.', 'convrail'),
    availability_invalid: __('This availability value is not allowed.', 'convrail'),
    availability_date_invalid: __('This date is not readable.', 'convrail'),
    seller_name_required: __('Fill in your store name above.', 'convrail'),
    seller_name_placeholder: __('"Unknown" or "N/A" is not a store name.', 'convrail'),
    seller_name_too_long: __('The store name is too long.', 'convrail'),
    target_countries_invalid: __('Pick your selling countries above.', 'convrail'),
    target_country_unknown: __('One of these countries is not one we can sell to.', 'convrail'),
    boolean_string_expected: __('This setting must be yes or no.', 'convrail'),
    checkout_requires_search: __('Checkout in ChatGPT also requires search to be on.', 'convrail'),
    privacy_policy_required: __(
      'Checkout in ChatGPT needs your privacy policy address.',
      'convrail',
    ),
    tos_required: __('Checkout in ChatGPT needs your terms and conditions address.', 'convrail'),
    gtin_invalid: __('The barcode is not a valid GTIN (8, 12, 13 or 14 digits).', 'convrail'),
    mpn_too_long: __('The manufacturer part number is too long.', 'convrail'),
    identifier_exists_expected: __(
      'Without a barcode or a part number, say so explicitly.',
      'convrail',
    ),
    group_id_too_long: __('The variant group identifier is too long.', 'convrail'),
    group_id_same_as_item: __(
      'The variant group must differ from the product identifier.',
      'convrail',
    ),
    star_rating_range: __('The rating must be between 0 and 5.', 'convrail'),
    review_count_invalid: __(
      'The number of reviews must be a whole number, zero or more.',
      'convrail',
    ),
    return_deadline_invalid: __('The return window must be a whole number of days.', 'convrail'),
    return_deadline_without_returns: __(
      'The return window only applies when the item accepts returns.',
      'convrail',
    ),
    weight_unit_missing: __('The weight needs a unit (g, kg, oz or lb).', 'convrail'),
    weight_unit_invalid: __('This weight unit is not accepted. Use g, kg, oz or lb.', 'convrail'),
    dimensions_unit_missing: __('The dimensions need a unit (in, cm, ft, m or mm).', 'convrail'),
    dimensions_incomplete: __('At least two of length, width and height are needed.', 'convrail'),
    dimensions_unit_invalid: __(
      'This dimension unit is not accepted. Use in, cm, ft, m or mm.',
      'convrail',
    ),
    // Actions d'amelioration (packages/feed/src/completeness.ts): elles ne sont pas des rejets,
    // mais des gains possibles, et elles arrivent par le meme chemin.
    add_gtin: __(
      'Add a barcode or a manufacturer part number: identified products match far better.',
      'convrail',
    ),
    add_category: __('Add a product category.', 'convrail'),
    longer_description: __(
      'Write at least 200 characters of description: the model reads meaning.',
      'convrail',
    ),
    add_sale_price: __('Show the sale price when there is one.', 'convrail'),
    add_more_images: __('Add more images.', 'convrail'),
    add_ratings: __('Send your ratings and review counts: a strong trust signal.', 'convrail'),
    describe_variants: __(
      'Describe your variants (size, color) on listings that have some.',
      'convrail',
    ),
    add_return_window: __(
      'Declare your return policy: a buyer who cannot see it assumes there is none.',
      'convrail',
    ),
  };
  return dictionary[code] ?? message;
};

/** Nom du champ tel que le marchand le voit, pas tel que la specification le nomme. */
export const rejectField = (field: string): string =>
  label(
    {
      config: __('Feed settings', 'convrail'),
      sellerName: __('Store name', 'convrail'),
      targetCountries: __('Countries you sell to', 'convrail'),
      seller_name: __('Store name', 'convrail'),
      target_countries: __('Countries you sell to', 'convrail'),
      item_id: __('Product ID', 'convrail'),
      title: __('Title', 'convrail'),
      description: __('Description', 'convrail'),
      url: __('Product page', 'convrail'),
      brand: __('Brand', 'convrail'),
      image_url: __('Image', 'convrail'),
      price: __('Price', 'convrail'),
      sale_price: __('Sale price', 'convrail'),
      availability: __('Availability', 'convrail'),
      gtin: __('Barcode (GTIN)', 'convrail'),
    },
    field,
  );

/**
 * Nom d'une offre. Comme partout ailleurs dans cette interface, l'API ne renvoie qu'un
 * identifiant: la phrase affichee est ecrite ici, donc traduite.
 */
export function planName(plan: string): string {
  switch (plan) {
    case 'free':
      return __('Free', 'convrail');
    case 'growth':
      return __('Growth', 'convrail');
    case 'scale':
      return __('Scale', 'convrail');
    case 'agency':
      return __('Agency', 'convrail');
    default:
      return plan;
  }
}
