/* Simulateur de crédit — version simplifiée
   Une seule entrée : le nombre de copropriétés gérées.
   Sortie : plan recommandé + volume moyen + crédit estimé. */

const { useState, useMemo } = React;

const PLANS = [
  { id: "decouverte", name: "Découverte", priceMonthly: 0, priceLabel: "Gratuit", target: "Pour tester la plateforme, sans carte bancaire.", min: 1, max: 1 },
  { id: "essentiel", name: "Essentiel", priceMonthly: 149, priceLabel: "149 €", target: "Petit cabinet indépendant.", min: 2, max: 25 },
  { id: "pro", name: "Pro", priceMonthly: 349, priceLabel: "349 €", target: "Cabinet de taille moyenne.", min: 26, max: 100 },
  { id: "enterprise", name: "Enterprise", priceMonthly: null, priceLabel: "Sur devis", target: "Réseaux et cabinets multi-agences.", min: 101, max: 9999 },
];

/* Volume moyen annuel par copropriété, par type d'audit
   (basé sur les fourchettes réglementaires moyennes). */
const VOLUMES = [
  { key: "dpe", label: "DPE collectifs", per: 0.10, unit: 27.7 },
  { key: "pppt", label: "PPPT", per: 0.07, unit: 50.4 },
  { key: "ae", label: "Audits énergétiques", per: 0.03, unit: 25.2 },
  { key: "dtg", label: "DTG", per: 0.02, unit: 126 },
];

function fmt(n) {
  return Math.round(n).toLocaleString("fr-FR").replace(/\u202f/g, " ");
}

function pickPlan(n) {
  return PLANS.find(p => n >= p.min && n <= p.max) || PLANS[PLANS.length - 1];
}

function CreditCalculator() {
  const [n, setN] = useState(60);
  const plan = useMemo(() => pickPlan(n), [n]);

  const volumes = useMemo(
    () => VOLUMES.map(v => {
      const qty = n * v.per;
      return { ...v, qty, credit: qty * v.unit };
    }),
    [n]
  );
  const totalCredit = volumes.reduce((s, v) => s + v.credit, 0);
  const months = plan.priceMonthly ? totalCredit / plan.priceMonthly : 0;

  return (
    <div className="calc">
      <div className="calc-grid">
        <div className="calc-left">
          <div>
            <div className="calc-cap">Combien de copropriétés gérez-vous ?</div>
            <h3 className="calc-question">Estimez votre crédit annuel en un curseur.</h3>
          </div>

          <div className="calc-slider-block">
            <div className="calc-slider-readout">
              <span className="calc-slider-num">{n}</span>
              <span className="calc-slider-unit">copropriété{n > 1 ? "s" : ""} dans votre portefeuille</span>
            </div>
            <input
              type="range"
              min={1}
              max={150}
              step={1}
              value={n}
              onChange={(e) => setN(parseInt(e.target.value, 10))}
              className="calc-range"
              aria-label="Nombre de copropriétés"
            />
            <div className="calc-range-meta">
              <span>1</span>
              <span>150+</span>
            </div>
          </div>

          <div className="calc-plan">
            <span className="calc-plan-tag">Plan recommandé</span>
            <div className="calc-plan-row">
              <span className="calc-plan-name">{plan.name}</span>
              <span className="calc-plan-price">
                {plan.priceLabel}
                {plan.priceMonthly ? <small> / mois HT</small> : null}
              </span>
            </div>
            <span className="calc-plan-target">{plan.target}</span>
          </div>
        </div>

        <aside className="calc-right">
          {plan.id === "decouverte" ? (
            <React.Fragment>
              <span className="calc-cap on-night">Plan gratuit</span>
              <div className="calc-result-num">0<small> €</small></div>
              <p className="calc-result-sub">Le plan Découverte est offert. Le crédit Vaauban s'active à partir du plan Essentiel.</p>
              <p className="calc-info">Vous pourrez ensuite ajouter une seconde copropriété pour passer au plan Essentiel — et commencer à cumuler du crédit sur vos audits.</p>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <span className="calc-cap on-night">Crédit annuel estimé</span>
              <div className="calc-result-num">{fmt(totalCredit)}<small> €</small></div>
              <p className="calc-result-sub">déduits chaque mois de votre abonnement{plan.priceMonthly ? "" : ", à confirmer dans votre contrat-cadre"}.</p>

              <div className="calc-volumes">
                <span className="calc-cap on-night">Volume moyen annuel</span>
                {volumes.map(v => (
                  <div className="calc-volume-row" key={v.key}>
                    <span>{v.qty < 1 ? "≈ 1" : Math.round(v.qty)} {v.label}</span>
                    <span className="calc-volume-num">{fmt(v.credit)} €</span>
                  </div>
                ))}
              </div>

              {plan.priceMonthly ? (
                <div className="calc-bar-block">
                  <div className="calc-bar-row">
                    <span className="calc-bar-label">Mois d'abonnement remboursés / an</span>
                    <span className="calc-bar-val">{months.toFixed(1)}</span>
                  </div>
                  <div className="calc-bar">
                    <span style={{ width: Math.min(100, (months / 12) * 100) + "%" }} />
                  </div>
                  <div className="calc-bar-meta">
                    <span>0 mois</span>
                    <span>12 mois (an entier)</span>
                  </div>
                </div>
              ) : null}
            </React.Fragment>
          )}

          <div className="calc-note">
            Estimation indicative basée sur des volumes réglementaires moyens (≈ 10 % de DPE, 7 % de PPPT, 3 % d'audits énergétiques, 2 % de DTG par an). Crédit = 7 % de la commission Vaauban sur chaque audit livré.
          </div>
        </aside>
      </div>
    </div>
  );
}

window.CreditCalculator = CreditCalculator;
ReactDOM.createRoot(document.getElementById("credit-calculator")).render(<CreditCalculator />);
