---
/**
 * Simulateur de frais. L'îlot calcule dans le navigateur ; sans JavaScript, le détail de chaque
 * barème et des exemples chiffrés (calculés au build par le même moteur) restent lisibles.
 * Aucun tarif n'est écrit ici : tout vient des barèmes publiés (Q-017).
 */
import { simuler, type Bareme, type Poste } from '@notariat-ci/simulateur';
import { traducteur, type Langue } from '@notariat-ci/i18n';
import Simulateur from '../components/Simulateur';
import Base from '../layouts/Base.astro';
import { donnees } from '../lib/donnees';
import { dateLongue, locale, montantFcfa, pourcentage } from '../lib/format';

interface Props {
  langue: Langue;
}

const { langue } = Astro.props;
const t = traducteur(langue);
const { baremes } = await donnees();
const fr = langue === 'fr';
const loc = locale(langue);
const fcfa = (n: number) => montantFcfa(loc, n);
const libelleBareme = (b: Bareme) => (fr ? b.libelleFr : (b.libelleEn ?? b.libelleFr));
const libellePoste = (p: { libelleFr: string; libelleEn: string | null }) =>
  fr ? p.libelleFr : (p.libelleEn ?? p.libelleFr);
const assiette = (b: Bareme) => (fr ? b.assietteFr : (b.assietteEn ?? b.assietteFr));
const fictif = baremes.some((b) => b.fictif);
const EXEMPLES = [5_000_000, 25_000_000, 100_000_000];

function calcul(b: Bareme, p: Poste): string {
  switch (p.calcul) {
    case 'taux':
      return t('simulateur.calcul_taux', { taux: pourcentage(loc, p.tauxPpm) });
    case 'forfait':
      return t('simulateur.calcul_forfait', { montant: fcfa(p.montant) });
    case 'pourcentage':
      return t('simulateur.calcul_pourcentage', {
        taux: pourcentage(loc, p.tauxPpm),
        bases: p.bases
          .map((code) => b.postes.find((x) => x.code === code))
          .map((x) => (x ? libellePoste(x) : ''))
          .join(', '),
      });
    case 'tranches':
      return p.cumulatives
        ? t('simulateur.tranches_cumulatives')
        : t('simulateur.tranches_taux_unique');
  }
}

const libelles = {
  formulaire: t('simulateur.formulaire'),
  acte: t('simulateur.acte'),
  montant: t('simulateur.montant'),
  montantAide: t('simulateur.montant_aide'),
  montantInvalide: t('simulateur.montant_invalide'),
  resultat: t('simulateur.resultat'),
  poste: t('simulateur.poste'),
  montantColonne: t('simulateur.montant_colonne'),
  sousTotal: t('simulateur.sous_total'),
  total: t('simulateur.total'),
  totalAnnonce: t('simulateur.total_annonce'),
  minimumApplique: t('simulateur.minimum_applique'),
  maximumApplique: t('simulateur.maximum_applique'),
  categories: {
    emoluments: t('simulateur.categorie.emoluments'),
    droits_taxes: t('simulateur.categorie.droits_taxes'),
    debours: t('simulateur.categorie.debours'),
  },
};
const cellule = 'px-3 py-2';
const nombre = `${cellule} text-right font-mono tabular-nums`;
---

<Base langue={langue} titre={t('simulateur.titre')} description={t('simulateur.description')}>
  <h1 class="mb-2 text-4xl font-semibold">{t('simulateur.titre')}</h1>
  <p class="max-w-prose text-lg">{t('simulateur.description')}</p>
  <p class="mt-4 max-w-prose rounded-md border-l-4 border-accent bg-surface p-3 font-semibold">
    {t('simulateur.avertissement')}
  </p>

  <dl class="mt-4 grid max-w-prose gap-x-4 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
    <dt class="font-semibold">{t('simulateur.emoluments')}</dt>
    <dd>{t('simulateur.emoluments_definition')}</dd>
    <dt class="font-semibold">{t('simulateur.debours')}</dt>
    <dd>{t('simulateur.debours_definition')}</dd>
  </dl>

  {baremes.length === 0 ? (
    <p class="mt-8 rounded-lg border-2 border-alerte bg-surface p-4">
      {t('simulateur.aucun_bareme')}
    </p>
  ) : (
    <div class="mt-8 flex flex-col gap-8">
      {fictif && (
        <p class="rounded-md bg-alerte p-3 font-semibold text-sur-alerte" data-bareme-fictif>
          {t('simulateur.fictif')}
        </p>
      )}

      <Simulateur client:idle baremes={baremes} langue={langue} locale={loc} libelles={libelles} />

      {baremes.map((b) => (
        <details class="rounded-lg border border-bordure bg-surface p-4">
          <summary class="flex min-h-11 cursor-pointer items-center font-titre text-xl font-semibold">
            {t('simulateur.detail')} : {libelleBareme(b)}
          </summary>
          <div class="mt-4 flex flex-col gap-4">
            <p>
              {t('simulateur.reference', {
                libelle: libelleBareme(b),
                version: b.version,
                date: dateLongue(loc, b.dateEffet),
              })}
            </p>
            <p class="text-sm text-texte-doux">
              {t('simulateur.source', { source: b.source })}
              {b.verification === 'a_verifier' && <> {t('simulateur.a_verifier')}</>}
            </p>

            {b.postes.map((p) => (
              <section class="border-t border-bordure pt-3">
                <h3 class="text-lg font-semibold">{libellePoste(p)}</h3>
                <p class="text-sm text-texte-doux">{libelles.categories[p.categorie]}</p>
                <p>{calcul(b, p)}</p>
                {p.calcul === 'tranches' && (
                  <table class="mt-2 border-collapse">
                    <caption class="sr-only">{libellePoste(p)}</caption>
                    <tbody>
                      {p.tranches.map((tr) => (
                        <tr class="border-b border-bordure">
                          <th scope="row" class={`${cellule} text-left font-normal`}>
                            {tr.a === null
                              ? t('simulateur.tranche_ouverte', { de: fcfa(tr.de) })
                              : t('simulateur.tranche', { de: fcfa(tr.de), a: fcfa(tr.a) })}
                          </th>
                          <td class={nombre}>
                            {t('simulateur.taux', { taux: pourcentage(loc, tr.tauxPpm) })}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
                {p.minimum !== null && (
                  <p>{t('simulateur.borne_minimum', { montant: fcfa(p.minimum) })}</p>
                )}
                {p.maximum !== null && (
                  <p>{t('simulateur.borne_maximum', { montant: fcfa(p.maximum) })}</p>
                )}
              </section>
            ))}
            <p class="text-sm text-texte-doux">{t('simulateur.arrondi')}</p>

            <h3 class="text-lg font-semibold">{t('simulateur.exemples')}</h3>
            <p>{t('simulateur.exemples_texte')}</p>
            <div class="overflow-x-auto">
              <table class="w-full border-collapse">
                <caption class="sr-only">
                  {t('simulateur.exemples')} : {libelleBareme(b)}
                </caption>
                <thead>
                  <tr class="border-b-2 border-accent">
                    <th scope="col" class={`${cellule} text-left`}>
                      {t('simulateur.poste')}
                    </th>
                    {EXEMPLES.map((montant) => (
                      <th scope="col" class={nombre}>
                        {assiette(b)} : {fcfa(montant)}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {b.postes.map((p, i) => (
                    <tr class="border-b border-bordure">
                      <th scope="row" class={`${cellule} text-left font-normal`}>
                        {libellePoste(p)}
                      </th>
                      {EXEMPLES.map((montant) => (
                        <td class={nombre}>{fcfa(simuler(b, montant).lignes[i]?.montant ?? 0)}</td>
                      ))}
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr class="font-semibold">
                    <th scope="row" class={`${cellule} text-left`}>
                      {t('simulateur.total')}
                    </th>
                    {EXEMPLES.map((montant) => (
                      <td class={nombre}>{fcfa(simuler(b, montant).total)}</td>
                    ))}
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </details>
      ))}
    </div>
  )}
</Base>
