Outiref
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Devis Diagnostic Immobilier En ligne Intégral Diagnostics</title>
<meta name="description" content="Devis diagnostic immobilier en ligne en Hauts-de-France (Amiens, Somme) : DPE, Amiante, Gaz, Électricité, Plomb, ERP et Termites. Diagnostiqueur certifié Intégral Diagnostics.">
<meta name="keywords" content="devis diagnostic immobilier, diagnostic immobilier amiens, diagnostiqueur immobilier somme, dpe amiens, amiante gaz electricite plomb erp termites">
<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
<meta name="content-language" content="fr">
<link rel="canonical" href="https://integral-diagnostics.fr/">
<link rel="alternate" hreflang="fr" href="https://integral-diagnostics.fr/">
<link rel="alternate" hreflang="fr-FR" href="https://integral-diagnostics.fr/">
<link rel="alternate" hreflang="x-default" href="https://integral-diagnostics.fr/">
<link rel="sitemap" type="application/xml" href="/sitemap.xml">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#0d4e91">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="Intégral Diag">
<link rel="apple-touch-icon" href="/img/logoFinal.png">
<link rel="icon" href="/img/favicon.ico">
<link rel="preconnect" href="https://js.stripe.com">
<link rel="dns-prefetch" href="https://www.google.com">
<meta property="og:type" content="website">
<meta property="og:locale" content="fr_FR">
<meta property="og:site_name" content="Intégral Diagnostics">
<meta property="og:title" content="Devis Diagnostic Immobilier en Ligne — Intégral Diagnostics">
<meta property="og:description" content="Devis diagnostic immobilier en ligne en Hauts-de-France (Amiens, Somme) : DPE, Amiante, Gaz, Électricité, Plomb, ERP et Termites.">
<meta property="og:url" content="https://integral-diagnostics.fr/">
<meta property="og:image" content="https://integral-diagnostics.fr/img/social-card.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Devis Diagnostic Immobilier en Ligne — Intégral Diagnostics">
<meta name="twitter:description" content="Devis diagnostic immobilier en ligne en Hauts-de-France (Amiens, Somme) : DPE, Amiante, Gaz, Électricité, Plomb, ERP et Termites.">
<meta name="twitter:image" content="https://integral-diagnostics.fr/img/social-card.png">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="index.css">
<script type="application/ld+json">
[
  {
    "@context": "https://schema.org",
    "@type": ["LocalBusiness", "ProfessionalService"],
    "name": "Intégral Diagnostics",
    "description": "Diagnostiqueur immobilier certifié en Hauts-de-France. DPE, Amiante, Gaz, Électricité, Plomb (CREP), ERP, Termites, Surfaces (Carrez/Boutin). Devis en ligne, intervention rapide.",
    "url": "https://integral-diagnostics.fr",
    "telephone": "+33781600775",
    "email": "contact@integral-diagnostics.fr",
    "address": {
      "@type": "PostalAddress",
      "addressLocality": "Hervilly",
      "postalCode": "80640",
      "addressRegion": "Hauts-de-France",
      "addressCountry": "FR"
    },
    "geo": {
      "@type": "GeoCoordinates",
      "latitude": 49.898,
      "longitude": 2.910
    },
    "areaServed": {
      "@type": "AdministrativeArea",
      "name": "Hauts-de-France"
    },
    "priceRange": "€€",
    "currenciesAccepted": "EUR",
    "paymentAccepted": ["Carte bancaire", "Virement"],
    "image": "https://integral-diagnostics.fr/img/logoFinal.png",
    "logo": "https://integral-diagnostics.fr/img/logoFinal.png",
    "aggregateRating": {
      "@type": "AggregateRating",
      "ratingValue": "5",
      "bestRating": "5",
      "worstRating": "1",
      "ratingCount": "1"
    },
    "hasOfferCatalog": {
      "@type": "OfferCatalog",
      "name": "Diagnostics immobiliers",
      "itemListElement": [
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "DPE — Diagnostic de Performance Énergétique"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "Diagnostic Amiante"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "Diagnostic Gaz"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "Diagnostic Électricité"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "CREP — Constat de Risque d'Exposition au Plomb"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "ERP — État des Risques et Pollutions"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "Diagnostic Termites et État parasitaire"}},
        {"@type": "Offer", "itemOffered": {"@type": "Service", "name": "Mesurage Loi Carrez et Loi Boutin"}}
      ]
    }
  },
  {
    "@context": "https://schema.org",
    "@type": "Organization",
    "name": "Intégral Diagnostics",
    "alternateName": "Integral Diagnostics",
    "description": "Diagnostiqueur immobilier certifié en Hauts-de-France. DPE, Amiante, Gaz, Électricité, Plomb (CREP), ERP, Termites, Surfaces (Carrez/Boutin).",
    "url": "https://integral-diagnostics.fr",
    "logo": {
      "@type": "ImageObject",
      "url": "https://integral-diagnostics.fr/img/logoFinal.png",
      "width": 200,
      "height": 200
    },
    "image": "https://integral-diagnostics.fr/img/social-card.png",
    "telephone": "+33781600775",
    "email": "contact@integral-diagnostics.fr",
    "address": {
      "@type": "PostalAddress",
      "addressLocality": "Hervilly",
      "postalCode": "80640",
      "addressRegion": "Hauts-de-France",
      "addressCountry": "FR"
    },
    "areaServed": {
      "@type": "AdministrativeArea",
      "name": "Hauts-de-France"
    },
    "foundingDate": "2010",
    "legalName": "Intégral Diagnostics",
    "sameAs": [
      "https://www.societe.com/societe/integral-diagnostics-512225988.html"
    ]
  },
  {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "name": "Intégral Diagnostics",
    "url": "https://integral-diagnostics.fr",
    "inLanguage": "fr-FR",
    "potentialAction": {
      "@type": "OrderAction",
      "target": "https://integral-diagnostics.fr/"
    }
  }
]
</script>
</head>
<body>
<a href="#main-content" class="skip-link">Aller au contenu principal</a>
<div class="site">

<div class="pre-header">
  <div class="pre-header-inner">
          <a href="/connexion.php" class="btn btn-ghost auth-action">Connexion</a>
      <a href="/inscription.php" class="btn btn-ghost auth-action">Inscription</a>
      </div>
</div>
<header>
  <div class="header-wrapper">
    <div class="header-left">
      <img src="/img/logoFinal.png" class="logo" alt="Logo Intégral Diagnostics">
    </div>
    <div class="header-center">
      <a href="tel:+33781600775" class="phone-link" title="Appeler Intégral Diagnostics">
        <svg class="phone-icon" width="60" height="60" viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
          <rect class="body" x="55" y="20" width="90" height="160" rx="12" ry="12" fill="currentColor"/>
          <rect x="63" y="32" width="74" height="128" rx="4" ry="4" fill="#ffffff"/>
          <rect x="88" y="24" width="24" height="4" rx="2" ry="2" fill="#ffffff"/>
          <circle cx="100" cy="170" r="7" fill="#ffffff"/>
        </svg>0781 600 775
      </a>
      <div class="muted"><strong>Vos diagnostics immobiliers dans les Hauts-de-France</strong></div>
    </div>
    <div class="header-right">
      <button class="hamburger" aria-label="Menu"><span></span><span></span><span></span></button>
    </div>
  </div>
  <nav class="desktop-menu">
    <ul>
                                            <li><a href="/DPE.php" title="Diagnostic de performance énergétique">DPE</a></li>
                            <li><a href="/Electricité.php" title="Diagnostic électricité">Électricité</a></li>
                            <li><a href="/gaz.php" title="Diagnostic gaz">Gaz</a></li>
                            <li><a href="/amiante.php" title="Diagnostic amiante">Amiante</a></li>
                            <li><a href="/CREP.php" title="Constat de risque d&#039;exposition au plomb">CREP</a></li>
                            <li><a href="/erp.php" title="État des risques et pollutions">ERP</a></li>
                            <li><a href="/Termites.php" title="Diagnostic termites">Termites</a></li>
                            <li><a href="/Surfaces.php" title="Mesurage loi Carrez / Boutin">Surfaces</a></li>
                            <li><a href="/contact.php" title="Nous contacter">Contact</a></li>
                            <li><a href="/RGPD.php" title="Politique de confidentialité">Confidentialité</a></li>
                            <li><a href="/mentions-legales.php" title="Mentions légales">Mentions légales</a></li>
                            <li><a href="/espace-client/espace-client.php" title="Mon espace client">Mon Espace</a></li>
                  </ul>
  </nav>
</header>

<div class="quick-access-bar">
  <a href="/inscription.php" class="quick-access-link quick-access-link-client">
    👤 Espace client
  </a>
  <a href="/inscription.php" class="quick-access-link quick-access-link-pro">
    🏢 Espace professionnel
  </a>
</div>

<div class="slots-bar" id="slotsBar">
  <span class="slots-bar-label"> 📅Prochaines Disponiblités:</span>
  <span id="slotsBarContent" class="creneaux-loading">Chargement…</span>
</div>

<main id="main-content">
<section class="content" >
  <div class="hero hero-home">
    <h1 class="hero-home-title">Devis Diagnostic Immobilier et RDV En Ligne</h1> <div class="hero-home-lead-wrap">  <p class="lead-text">Sélectionnez vos diagnostics (DPE, Amiante, Gaz, Électricité, Plomb, ERP, Termites), indiquez le type de bien, la surface, l'année de construction et laissez vous guider.</p></div> 
<aside class="panel">
<div class="row-fields" style="display:grid;grid-template-columns:1fr 1fr;gap:14px;" id="main-fields-grid">
  <div class="field field-small">
    <label>Type de bien&nbsp;<span class="req">*</span></label>
    <select id="typeBien" style="padding:5px 8px;">
      <option value="">Sélectionnez</option>
      <option value="appartement">Appartement</option>
      <option value="maison">Maison</option>
      <option value="erp">Tertiaire</option>
    </select>
  </div>

  <div class="field field-small">
    <label>Copropriété&nbsp;<span class="req">*</span></label>
    <select id="coproSelect" style="padding:5px 8px;border-radius:6px;border:1px solid #ccc;font-size:.9rem;width:100%;">
      <option value="">Sélectionnez</option>
      <option value="oui">Oui</option>
      <option value="non">Non</option>
    </select>
  </div>

  <div class="field field-small">
    <label>Je souhaite un diagnostic pour&nbsp;<span class="req">*</span></label>
    <select id="cadre" style="padding:5px 8px;">
      <option value="">Sélectionnez</option>
      <option value="vente">Vendre</option>
      <option value="location">Louer</option>
      <option value="vente">Indécis</option>
      <option value="travaux">Travaux ou démolition</option>
    </select>
  </div>

  <div class="field field-small">
    <label>Surface (m2)&nbsp;<span class="req">*</span></label>
    <input type="number" id="surface" min="1" value="" placeholder="Surface approximative?" style="padding:5px 8px;">
  </div>
</div>

<div class="annee-section" id="annee-section-req">
  <div class="annee-title">Année de construction&nbsp;<span class="req">*</span></div>

  <div class="annee-blocs">
    <div class="annee-card" data-cat="Avant 1949">Avant le 1/01/1949</div>
    <div class="annee-card" data-cat="1949 1997">Du 1/01/1949 au 30/06/1997</div>
    <div class="annee-card" data-cat="Après 1997">À partir du 1/07/1997</div>
  </div>

  <div class="annee-blocs">
    <input type="date" id="anneeConstruction" style="width:175px;padding:6px;border-radius:6px;border:1px solid #ccc;color:#22324a;-webkit-text-fill-color:#22324a;background:#fff;">
    
      <div class="diag-item"><input type="checkbox" id="anneeInconnue">Inconnue
      
   </div>
  </div>
</div>
<!-- Champs installation synchronisés par le wizard (masqués) -->
<input type="checkbox" class="diag-install" id="inst-elec"  value="inst-elec"  data-price="0" style="display:none;">
<input type="checkbox" class="diag-install" id="inst-gaz"   value="inst-gaz"   data-price="0" style="display:none;">
<input type="checkbox" class="diag-install" id="plaque-gaz" value="plaque-gaz" data-price="0" style="display:none;">

<!-- =================== WIZARD Diagnostics Existants =================== -->
<div class="annee-section" id="wizardSection">
  <div class="annee-title">Avez-vous des diagnostics ou documents à votre nom&nbsp;?&nbsp;<span class="req">*</span></div>
  <div class="wiz-oui-non">
    <button type="button" class="wiz-btn wiz-btn-non" id="wizardNon">Non</button>
    <button type="button" class="wiz-btn wiz-btn-oui" id="wizardOui">Oui</button>
  </div>
  <p style="margin:6px 0 0;font-size:.8rem;color:#b45309;font-style:italic;">La législation impose que les diagnostics obligatoires soient au nom du propriétaire, vendeur ou bailleur.</p>

  <div id="wizardStep2" style="display:none;">
    <div class="wiz-grid wiz-grid-existing-diags">

      <!-- ⚡ ÉLECTRICITÉ -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">⚡ Électricité</div>
        <label class="wiz-lbl" for="wiz-elec-date-install">Date de l'installation</label>
        <select id="wiz-elec-date-install" class="wiz-select">
          <option value="">Sélectionnez</option>
          <option value=">15">Plus de 15 ans</option>
          <option value="<15">Moins de 15 ans</option>
        </select>
        <label class="wiz-lbl is-disabled" id="lbl-wiz-consuel" style="pointer-events:none;" title="Disponible seulement si installation &gt; 15 ans"><input type="checkbox" id="wiz-consuel" disabled> Consuel &lt; 3 ans</label>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-elec">J'ai Déjà un diag électricité à mon nom.</label>
        <div class="wiz-sub" id="wiz-elec-sub">
          <select id="wiz-elec-when" class="wiz-select">
            <option value="">Date du diagnostic…</option>
            <option value="v3">Moins de 3 ans</option>
            <option value="v6">Entre 3 et 6 ans</option>
            <option value="old">Plus de 6 ans</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-elec-none">Je n'ai pas de diag électricité à mon nom</label>
      </div>

      <!-- 🔥 GAZ -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">🔥 Gaz</div>
        <label class="wiz-lbl" for="wiz-gaz-date-install">Date de l'installation</label>
        <select id="wiz-gaz-date-install" class="wiz-select">
          <option value="">Sélectionnez</option>
          <option value=">15">Plus de 15 ans</option>
          <option value="<15">Moins de 15 ans</option>
        </select>
        <label class="wiz-lbl is-disabled" id="lbl-wiz-qualigaz" style="pointer-events:none;" title="Disponible seulement si installation &gt; 15 ans"><input type="checkbox" id="wiz-qualigaz" disabled> Qualigaz &lt; 3 ans</label>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-gaz">J'ai Déjà un diag gaz à mon nom.</label>
        <div class="wiz-sub" id="wiz-gaz-sub">
          <select id="wiz-gaz-when" class="wiz-select">
            <option value="">Date du diagnostic…</option>
            <option value="v3">Moins de 3 ans</option>
            <option value="v6">Entre 3 et 6 ans</option>
            <option value="old">Plus de 6 ans</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-gaz-none">Je n'ai pas de diag gaz à mon nom</label>
      </div>

      <!-- 🏠 DPE -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">🏠 DPE</div>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-dpe">J'ai Déjà un DPE à mon nom</label>
        <div class="wiz-sub" id="wiz-dpe-sub">
          <select id="wiz-dpe-when" class="wiz-select">
            <option value="">Situation du DPE…</option>
            <option value="apres2021-ok">Après le 30/06/2021 &amp; &lt; 10 ans</option>
            <option value="avant2021">Avant le 01/07/2021</option>
            <option value="old">Plus de 10 ans</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-dpe-none">Je n'ai pas de DPE à mon nom</label>
      </div>

      <!-- ⚠️ ERP / ENSA -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">⚠️ ERP / ENSA</div>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-erp">J'ai déjà un ERP/ENSA à mon nom</label>
        <div class="wiz-sub" id="wiz-erp-sub">
          <select id="wiz-erp-when" class="wiz-select">
            <option value="">Date de l'ERP/ENSA…</option>
            <option value="ok">Moins de 6 mois</option>
            <option value="old">Plus de 6 mois</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-erp-none">Je n'ai pas d'ERP/ENSA à mon nom</label>
      </div>

      <!-- 🎯 PLOMB -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">🎯 Plomb (CREP)</div>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-plomb">J'ai Déjà un diag plomb à mon nom</label>
        <div class="wiz-sub" id="wiz-plomb-sub">
          <select id="wiz-plomb-result" class="wiz-select">
            <option value="">Résultat…</option>
            <option value="negatif">Négatif (pas de plomb)</option>
            <option value="positif">Positif (présence de plomb)</option>
          </select>
          <div id="wiz-plomb-date-sub" style="display:none;margin-top:6px;">
            <select id="wiz-plomb-when" class="wiz-select">
              <option value="">Date du diagnostic…</option>
              <option value="v1">Moins de 1 an</option>
              <option value="v6">Entre 1 et 6 ans</option>
              <option value="old">Plus de 6 ans</option>
            </select>
          </div>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-plomb-none">Je n'ai pas de diag CREP à mon nom</label>
      </div>

      <!-- 🏚️ AMIANTE -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">🏚️ Amiante</div>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-amiante">J'ai Déjà un diag amiante</label>
        <div class="wiz-sub" id="wiz-amiante-sub">
          <select id="wiz-amiante-result" class="wiz-select">
            <option value="">Résultat…</option>
            <option value="negatif">Négatif (pas d'amiante)</option>
            <option value="positif">Positif (présence d'amiante)</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-amiante-none">Je n'ai pas de diag amiante à mon nom</label>
      </div>

      <!-- 🐛 TERMITES -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">🐛 Termites</div>
        <label class="wiz-lbl"><input type="checkbox" id="wiz-has-termites">J'ai Déjà un état termites à mon nom</label>
        <div class="wiz-sub" id="wiz-termites-sub">
          <select id="wiz-termites-when" class="wiz-select">
            <option value="">Date du diagnostic…</option>
            <option value="ok">Moins de 6 mois</option>
            <option value="old">Plus de 6 mois</option>
          </select>
        </div>
        <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-termites-none">Je n'ai pas de diag termites à mon nom</label>
      </div>

      <!-- 📐 SURFACES -->
      <div class="wiz-bloc">
        <div class="wiz-bloc-head">📐 Surfaces</div>
        <div id="wiz-carrez-row" style="display:none;">
          <label class="wiz-lbl"><input type="checkbox" id="wiz-has-carrez">Loi Carrez existante à mon nom</label>
          <div class="wiz-sub" id="wiz-carrez-sub">
            <label class="wiz-lbl"><input type="checkbox" id="wiz-carrez-travaux"> Travaux depuis le mesurage?</label>
          </div>
          <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-carrez-none">Je n'ai pas de mesurage Carrez à mon nom</label>
        </div>
        <div id="wiz-boutin-row" style="display:none;">
          <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-has-boutin"> Loi Boutin existante à mon nom</label>
          <div class="wiz-sub" id="wiz-boutin-sub">
            <label class="wiz-lbl"><input type="checkbox" id="wiz-boutin-travaux"> Travaux depuis le mesurage?</label>
          </div>
          <label class="wiz-lbl" style="margin-top:4px;"><input type="checkbox" id="wiz-boutin-none">Je n'ai pas de mesurage Boutin</label>
        </div>
        <p id="wiz-surfaces-hint" class="wiz-note" style="margin-top:6px;">Les options Carrez / Boutin s'affichent selon le cadre et la copropriété renseignés.</p>
      </div>

    </div><!-- /.wiz-grid -->
    <div class="wiz-result-bar" id="wiz-result-bar"></div>
  </div><!-- /#wizardStep2 -->
</div><!-- /#wizardSection -->

<div class="annee-section">
<div class="annee-title">Informations complémentaires</div>
<div class="diag-list" style="display:flex;flex-wrap:wrap;gap:14px;align-items:flex-end;">
  <div style="flex:1 1 170px;min-width:160px;">
    <label style="display:block;font-size:.82rem;font-weight:600;color:#334155;margin-bottom:3px;">Type de chauffage&nbsp;*</label>
    <select id="chauffage" style="width:100%;padding:6px;border-radius:6px;border:1px solid #ccc;">
      <option value="">Sélectionnez</option>
      <option value="collectif">Collectif</option>
      <option value="individuel">Individuel</option>
      <option value="inconnue">Inconnu</option>
    </select>
  </div>
  <div style="flex:1 1 200px;min-width:180px;">
    <label style="display:block;font-size:.82rem;font-weight:600;color:#334155;margin-bottom:3px;">Type de radiateurs&nbsp;*</label>
    <select id="typeRadiateur" style="width:100%;padding:6px;border-radius:6px;border:1px solid #ccc;">
      <option value="">Sélectionnez</option>
      <option value="electrique">Radiateurs électriques</option>
      <option value="gaz">Radiateurs gaz</option>
      <option value="eau">Radiateurs à eau</option>
      <option value="inconnu">Inconnu</option>
    </select>
  </div>
  <div style="flex:1 1 160px;min-width:150px;">
    <label style="display:block;font-size:.82rem;font-weight:600;color:#334155;margin-bottom:3px;">Climatisation&nbsp;*</label>
    <select id="climatisationSelect" style="width:100%;padding:6px;border-radius:6px;border:1px solid #ccc;text-align:center;">
      <option value="">Sélectionnez</option>
      <option value="oui">Oui</option>
      <option value="non">Non</option>
    </select>
  </div>
  <div style="flex:1 1 160px;min-width:150px;">
    <label style="display:block;font-size:.82rem;font-weight:600;color:#334155;margin-bottom:3px;">Cuisson gaz&nbsp;*</label>
    <select id="cuissonGazSelect" style="width:100%;padding:6px;border-radius:6px;border:1px solid #ccc;text-align:center;">
      <option value="">Sélectionnez</option>
      <option value="oui">Oui</option>
      <option value="non">Non</option>
    </select>
  </div>
</div>
</div>

<div class="annee-section">
<div class="annee-title">
  Diagnostics</div>
  <div class="diag-list diag-list-main" >
     <div class="diag-item">
      <input type="checkbox" class="diag" id="gaz" value="gaz" data-price="100">
      Gaz <span class="diag-price"> à partir de 100 €</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic règlementaire obligatoire
par diagnostiqueur certifié selon conditions.</span>
    </div>
    <div class="diag-item">
      <input type="checkbox" class="diag" id="elec" value="elec" data-price="100">
      Électricité <span class="diag-price"> à partir de 100 €</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic règlementaire obligatoire
par diagnostiqueur certifié selon conditions.</span>
    </div>
    <div class="diag-item"><input type="checkbox" class="diag" id="dpe" value="dpe" data-price="120">DPE <span class="diag-price"> à partir de 120€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic règlementaire obligatoire
par diagnostiqueur certifié selon conditions.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="amiante" value="amiante" data-price="120">Amiante <span class="diag-price"> à partir de 120€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic obligatoire
par diagnostiqueur certifié pour les constructions avant le 1/07/1997.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="plomb" value="plomb" data-price="120">Plomb <span class="diag-price"> à partir de 120€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic obligatoire
par diagnostiqueur certifié pour les constructions avant le 1/01/1949.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="erp" value="erp" data-price="25">ERP/ENSA <span class="diag-price"> 25€</span> <span style="font-size:12px;color:#555;">(offert avec autre diag.)</span><span class="diag-regl-hint">Diagnostic règlementaire obligatoire
selon conditions.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="termites" value="termites" data-price="100">Termites <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic règlementaire obligatoire
par diagnostiqueur certifié selon Arrêté.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="paras" value="paras" data-price="100">État parasitaire <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic supplémentaire</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="assainissement" value="assainissement" data-price="100">Assainissement <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic supplémentaire</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="etat-lieux" value="etat_lieux" data-price="100">État des lieux <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Diagnostic supplémentaire</span></div>
  </div>
  <div id="travaux-info-msg" style="display:none;margin-top:8px;padding:12px 14px;background:#fff8e1;border:1px solid #ffe082;border-radius:8px;font-size:.85rem;color:#5d4037;line-height:1.6;">
    <strong>&#9432; Aucun diagnostic obligatoire pour les constructions à partir du 1<sup>er</sup> juillet 1997.</strong><br>
    Si un doute sur la présence d'amiante ou de plomb subsiste, vous êtes invités à prendre contact :<br>
    <a href="tel:+33781600775" style="color:#0d4e91;font-weight:700;">&#128222; 07 81 60 07 75</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/contact.php" style="color:#0d4e91;font-weight:700;">&#9993; Page contact</a>
  </div>
  <div id="zone-checker" style="margin-top:8px;padding:10px 12px;background:#f0f5fb;border-radius:8px;border:1px solid #d0dbd7;position:relative;">
    <div style="font-size:12.5px;font-weight:600;color:#2361a7;margin-bottom:6px;">
      &#128205; Vérifier l'adresse du bien — zones termites &amp; PEB (bruit aérien)&nbsp;<span class="req">*</span>
    </div>
    <div style="display:flex;gap:8px;align-items:flex-start;position:relative;">
      <div style="flex:1;position:relative;">
        <input type="text" id="zone-adresse-input" autocomplete="off"
          placeholder="Ex : 12 rue des Lilas, 33000 Bordeaux"
          style="width:100%;padding:7px 10px;border:1px solid #aac4e0;border-radius:6px;font-size:13px;box-sizing:border-box;">
        <ul id="zone-suggestions"
            style="display:none;position:absolute;top:100%;left:0;right:0;background:#fff;                   border:1px solid #aac4e0;border-top:none;border-radius:0 0 6px 6px;                   list-style:none;margin:0;padding:0;z-index:200;box-shadow:0 4px 12px rgba(0,0,0,.12);"></ul>
      </div>
      <button type="button" id="zone-btn-verif"
              style="padding:7px 14px;background:#2361a7;color:#fff;border:none;border-radius:6px;                     font-size:13px;font-weight:700;cursor:pointer;white-space:nowrap;flex-shrink:0;">
        Vérifier
      </button>
    </div>
    <div style="display:flex;gap:16px;flex-wrap:wrap;margin-top:8px;">
      <div id="zone-result-termites" style="flex:1;min-width:200px;font-size:13px;font-weight:600;"></div>
      <div id="zone-result-peb"      style="flex:1;min-width:200px;font-size:13px;font-weight:600;"></div>
    </div>
    <div style="margin:6px 0 0;font-size:.8rem;color:#b45309;font-style:italic;">
      Vérifications basées sur données publiques — Non contractuelles. Il est important de vérifier auprès de votre Mairie.
    </div>
  </div>

  <!-- Inputs cachés pour stocker l'adresse du bien (toujours présents) -->
  <input type="hidden" id="hidden-bien-numero">
  <input type="hidden" id="hidden-bien-rue">
  <input type="hidden" id="hidden-bien-cp">
  <input type="hidden" id="hidden-bien-ville">
</div>
<!-- Section Métrage -->
<div class="annee-section">
<div class="annee-title">
  Métrage Surface</div>
  <div class="diag-list">
    <div class="diag-item"><input type="checkbox" class="diag" id="d-carrez" value="carrez" data-price="100">Loi Carrez <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Mesurage conforme obligatoire pour vente en copropriété.</span></div>
    <div class="diag-item"><input type="checkbox" class="diag" id="d-boutin" value="boutin" data-price="100">Loi Boutin <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span><span class="diag-regl-hint">Mesurage conforme obligatoire pour location.</span></div>
     <div class="diag-item"><input type="checkbox" class="diag" id="d-habitable" value="surface habitable" data-price="100">Habitable <span class="diag-price"> à partir de 100€</span><span style="color:#e53e3e;font-weight:700;">*</span> <span style="font-size:12px;color:#555;">(offert avec DPE)</span><span class="diag-regl-hint">Mesurage supplémentaire pièce par pièce sur demande.</span></div>
  </div>
</div>
<div class="annee-section">
<div class="annee-title">
  Options</div>
  <div class="diag-list">
    <div class="diag-item">
      <input type="checkbox" class="diag option-supp" id="logement-vetuste" value="logement-vetuste" data-price="0">
      Logement vétuste <span style="font-size:.75rem;color:#475569;font-weight:600;">+10%</span>
    </div>
    <div class="diag-item">
      <input type="checkbox" class="diag option-supp" id="urgence-24h" value="urgence-24h" data-price="0">
      Urgence 24h <span style="font-size:.75rem;color:#475569;font-weight:600;">+15% sur demande</span>
    </div>
    <div id="urgence-notice" style="display:none;margin:4px 0 6px;padding:11px 14px;background:#fff8e1;border:1px solid #f59e0b;border-radius:12px;font-size:.87rem;color:#7c4a00;line-height:1.5;">
      📞 Vous avez sélectionné l'option <strong>Urgence 24h</strong>. La prise de rendez-vous en ligne n'est pas disponible pour ce type d'intervention. Merci de contacter notre diagnostiqueur directement au <a href="tel:+33781600775" style="color:#b45309;font-weight:700;white-space:nowrap;">07 81 60 07 75</a> afin de confirmer votre créneau. Votre devis peut néanmoins être enregistré dès maintenant.
    </div>
    <div class="diag-item">
      <input type="checkbox" class="diag option-supp" id="dimanche-nuit" value="dimanche-nuit" data-price="0">
      Dimanche / Nuit <span style="font-size:.75rem;color:#475569;font-weight:600;">+30%</span>
    </div>
    <div class="diag-item" id="km-supplement-item" style="display:none;background:#fff3e0;border-radius:4px;padding:4px 8px;">
      <input type="checkbox" id="supplement-km" checked disabled>
      <span id="km-supplement-label">Participation aux frais kilométriques : </span>
    </div>
  </div>
</div>

    <div class="price-box">
      <div style="font-size:.75rem;color:#64748b;margin-bottom:6px;line-height:1.4;"><span style="color:#e53e3e;font-weight:700;">*</span> Tarif indicatif ajusté automatiquement selon la surface, le type de bien et la combinaison de diagnostics retenus.</div>
      <div class="total" id="total">0 €</div>
      <div style="font-size:.72rem;color:#94a3b8;margin-top:2px;">Tarif arrondi à l'euro le plus proche.</div>
      <div class="breakdown" id="breakdown"></div>
      <!-- === Créneaux disponibles === -->
      <!-- === / Créneaux === -->
      <div class="btn-row">
        <button class="btn btn-primary" id="btnValider">✅ Valider le devis</button>
        <button class="btn btn-primary" id="btnPrendreRdv">📅 Prendre RDV</button>
      </div>
      <div id="erpEnsaNotice" style="display:none;margin-top:10px;padding:12px 16px;background:#e8f5e9;border:1px solid #a5d6a7;border-radius:6px;font-size:.88rem;color:#2e7d32;line-height:1.5;">
        Les diagnostics ERP (État des Risques et Pollutions) et ENSA (État des Nuisances Sonores Aériennes) sont des documents réglementaires établis à partir des bases de données officielles. Aucune intervention sur site n'est requise. Vos documents seront disponibles au téléchargement dès validation du règlement.
      </div>
      <div id="horsPerimetreMsg">
        <strong>&#128683; Zone hors périmètre d'intervention (&gt; 150 km)</strong><br>
        La prise de rendez-vous en ligne n'est pas disponible pour cette adresse.<br>
       Merci de prendre contact :
        <a href="tel:+33781600775">&#128222; 07 81 60 07 75</a>
        &nbsp;|&nbsp;
        <a href="/contact.php">&#9993; Page contact</a>
      </div>
      </div>
      <p style="margin-top:8px;font-size:.8rem;color:#0d4e91;">RDV sans création de compte. Vos coordonnées, l'adresse du bien à diagnostiquer et un acompte de 20€ seront demandés avant l'accès à l'agenda.</p>
            <div class="public-rdv-panel" id="publicRdvPanel">
        <div class="public-rdv-header">
          <h3>Prise de RDV sans compte</h3>
          <div class="public-rdv-header-links">
            <span>ou</span>
            <a href="/inscription.php">créer un compte</a>
            <span>ou</span>
            <a href="/connexion.php">me connecter</a>
          </div>
        </div>
        <p>Renseignez directement vos coordonnées et l'adresse du bien depuis cette page. Un acompte fixe de 20 € vous sera demandé avant l'accès au calendrier.</p>
        <p class="public-rdv-note">Vous allez être recontacté pour confirmer vos besoins.</p>
        <div class="public-rdv-steps">
          <div class="public-rdv-step active" id="publicStepIndicator1"><span class="public-rdv-step-number">1</span> Paiement</div>
          <div class="public-rdv-step" id="publicStepIndicator2"><span class="public-rdv-step-number">2</span> Coordonnées</div>
          <div class="public-rdv-step" id="publicStepIndicator3"><span class="public-rdv-step-number">3</span> Validation</div>
        </div>
        <div class="public-rdv-stage active" id="publicRdvStage1">
          <div class="public-payment-options">
            <label><input type="radio" name="public-payment-mode" value="acompte_stripe" checked> Acompte 20 € — <span class="payment-brand-line"><img class="payment-brand-stripe" src="/img/stripe.png" alt="Stripe"> Carte bancaire</span></label>
            <label><input type="radio" name="public-payment-mode" value="total_stripe"> Total <span class="payment-total-label">—</span> — <span class="payment-brand-line"><img class="payment-brand-stripe" src="/img/stripe.png" alt="Stripe"> Carte bancaire</span></label>
            <label><input type="radio" name="public-payment-mode" value="total_paypal"> Total <span class="payment-total-label">—</span> — <span class="payment-brand-line"><span class="payment-brand-paypal">PayPal</span><span class="payment-brand-4x">4X</span><small>si éligible</small></span></label>
          </div>
          <div class="public-payment-next">
            <button class="btn btn-primary" id="btnPublicPaymentNext" type="button">Suivant</button>
          </div>
        </div>
        <div class="public-rdv-stage" id="publicRdvStage2">
          <div class="public-compliance-box">
            <h4>Informations précontractuelles</h4>
            <p>Avant toute prise de rendez-vous ou paiement, veuillez prendre connaissance des éléments suivants.</p>
            <ul>
              <li>Le montant affiché est un devis estimatif net de TVA, établi sur la base des informations que vous avez déclarées. Il pourra être confirmé ou ajusté si le dossier réel diffère.</li>
              <li>Les diagnostics sont réalisés conformément à la réglementation en vigueur, dans le cadre d'une visite non destructive limitée aux zones accessibles le jour de l'intervention.</li>
              <li>Les modalités de paiement, d'annulation et de rétractation sont détaillées sur la page <a href="/Paiement.php">Paiement</a> et dans votre espace client après création du dossier.</li>
            </ul>
            <div class="pricing-note">
              Transparence tarifaire : le total estimé correspond aux diagnostics et options sélectionnés. Des participations aux frais kilométriques ou ajustements de périmètre peuvent s'ajouter ou se déduire si l'adresse, la surface, l'accessibilité ou le nombre réel de diagnostics diffère des informations saisies. Le tarif définitif sera établi à l'issue de la mission et, en cas de trop-perçu, un avoir ou un remboursement sera effectué par Intégral Diagnostics.
            </div>
            <div class="consent-checklist">
              <div class="consent-item">
                <input type="checkbox" id="public-accept-estimate">
                <label for="public-accept-estimate">Je reconnais avoir pris connaissance du caractère estimatif du devis, de la possibilité d'ajustement en fonction du dossier réel et des limites d'une intervention non destructive sur les seules zones accessibles.</label>
              </div>
              <div class="consent-item">
                <input type="checkbox" id="public-accept-legal">
                <label for="public-accept-legal">J'ai lu les <a href="/Paiement.php">modalités de paiement</a>, les informations de <a href="/RGPD.php">confidentialité</a> et les <a href="/mentions-legales.php">mentions légales</a>, et je comprends que le droit de rétractation légal s'applique selon les conditions prévues au contrat.</label>
              </div>
            </div>
          </div>
          <div class="public-rdv-grid">
            <div><label for="public-client-prenom">Prénom *</label><input type="text" id="public-client-prenom" autocomplete="given-name"></div>
            <div><label for="public-client-nom">Nom *</label><input type="text" id="public-client-nom" autocomplete="family-name"></div>
            <div><label for="public-client-email">E-mail *</label><input type="email" id="public-client-email" autocomplete="email"></div>
            <div><label for="public-client-tel">Téléphone *</label><input type="tel" id="public-client-tel" autocomplete="tel"></div>
            <div><label for="public-client-numero">N° de rue client *</label><input type="text" id="public-client-numero" autocomplete="address-line1" inputmode="numeric" pattern="[0-9]*" oninput="this.value=this.value.replace(/[^0-9]/g,'')"></div>
            <div><label for="public-client-rue">Rue client *</label><input type="text" id="public-client-rue" autocomplete="street-address"></div>
            <div><label for="public-client-cp">Code postal client *</label><input type="text" id="public-client-cp" maxlength="5" autocomplete="postal-code"></div>
            <div><label for="public-client-ville">Ville client *</label><input type="text" id="public-client-ville" autocomplete="address-level2"></div>
            <div class="full"><label><input type="checkbox" id="public-copy-address"> Même adresse pour le bien à diagnostiquer</label></div>
            <div><label for="public-bien-numero">N° de rue du bien *</label><input type="text" id="public-bien-numero" inputmode="numeric" pattern="[0-9]*" oninput="this.value=this.value.replace(/[^0-9]/g,'')"></div>
            <div><label for="public-bien-rue">Rue du bien *</label><input type="text" id="public-bien-rue"></div>
            <div><label for="public-bien-cp">Code postal du bien *</label><input type="text" id="public-bien-cp" maxlength="5"></div>
            <div><label for="public-bien-ville">Ville du bien *</label><input type="text" id="public-bien-ville"></div>
          </div>
          <div class="public-rdv-actions">
            <button class="btn btn-primary" id="btnPublicCoordsNext" type="button">Suivant</button>
          </div>
        </div>
        <div class="public-rdv-stage" id="publicRdvStage3">
          <div class="public-rdv-summary" id="publicRdvSummary"></div>
          <div class="public-rdv-actions">
            <button class="btn btn-primary" id="btnPublicRdvConfirm">Confirmer et payer</button>
          </div>
        </div>
        <div class="public-rdv-inline-msg" id="publicRdvMsg"></div>
      </div>
      <div id="surface-error" style="display:none; color:#b00020; margin-top:10px; font-weight:600;">
En Tertiaire pour les surfaces supérieures à 250 m2 merci de prendre contact :
<a href="https://www.integral-diagnostics.fr/contact.php" target="_blank">
Accéder à la page contact
</a>
</div>
      <div id="calendar-container" style="display:none;margin-top:20px;"></div>
    </div>
  </aside>
</section>

<!-- Carousel + Avis -->
 
<section class="diagnostics-carousel">
  <h2>Les diagnostics immobiliers : DPE, Amiante, Gaz, Électricité, Plomb, ERP, Termites</h2>
  <div class="carousel-wrapper">
    <button class="carousel-btn prev">&#10094;</button>
    <div class="carousel-track">
      <a href="DPE.php" class="carousel-item"><img src="/img/Performance_DPE.png" alt="DPE" width="200" height="150" loading="lazy"><span>DPE</span></a>
      <a href="Électricité.php" class="carousel-item"><img src="/img/Electricite.png" alt="Électricité" width="200" height="150" loading="lazy"><span>Électricité</span></a>
      <a href="gaz.php" class="carousel-item"><img src="/img/Diaggaz.png" alt="Gaz" width="200" height="150" loading="lazy"><span>Gaz</span></a>
      <a href="amiante.php" class="carousel-item"><img src="/img/DiagAMIANTE.png" alt="Amiante" width="200" height="150" loading="lazy"><span>Amiante</span></a>
      <a href="CREP.php" class="carousel-item"><img src="/img/CREPLOMB.png" alt="Plomb" width="200" height="150" loading="lazy"><span>CREP (Plomb)</span></a>
      <a href="erp.php" class="carousel-item"><img src="/img/EtatdesrisquesPollutions.png" alt="Diagnostic ERP — État des Risques et Pollutions" width="200" height="150" loading="lazy"><span>ERP</span></a>
      <a href="Termites.php" class="carousel-item"><img src="/img/EPTERMITES.png" alt="Termites" width="200" height="150" loading="lazy"><span>Termites</span></a>
      <a href="Surfaces.php" class="carousel-item"><img src="/img/carrezboutin.png" alt="Diagnostic Loi Carrez et Loi Boutin" width="200" height="150" loading="lazy"><span>Surfaces</span></a>
    </div>
    <button class="carousel-btn next">&#10095;</button>
  </div>


  
</section><!-- /diagnostics-carousel -->

<section class="home-why-section" style="max-width:960px;margin:32px auto;padding:16px 24px;border:2px solid transparent;border-radius:10px;background:linear-gradient(#fff,#fff) padding-box,linear-gradient(90deg,#2361a7,#136c38) border-box;">
  <h2 style="font-size:1.2rem;color:#334155;margin-bottom:8px;">Pourquoi choisir Intégral Diagnostics ?</h2>
  <ul class="home-why-list" style="list-style-type:disc;padding-left:20px;color:#334155;display:grid;grid-template-columns:1fr 1fr;gap:6px 18px;margin:0;line-height:1.45;">
    <li> Diagnostiqueur Immobilier certifié Bureau Veritas   </li>
    <li> Devis instantané en ligne, sans engagement   </li>
    <li> Prise de RDV rapide et flexible   </li>
    <li> Espace client sécurisé pour suivre vos diagnostics   </li>
    <li> Rapports rapides et conformes   </li>  
    <li> Réactivité, Urgence 24h, Urgence Dimanche et fériés   </li>
  </ul>
</section>

<section class="city-diagnostics-links" style="max-width:960px;margin:24px auto 32px;">
  <h2>Diagnostics Immobiliers en Hauts-de-France — zones d'interventions</h2>
  <ul>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/Ailly%20sur%20Noye/" title="Diagnostics immobiliers Ailly-sur-Noye">Ailly-sur-Noye</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/albert/" title="Diagnostics immobiliers Albert">Albert</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/amiens/" title="Diagnostics immobiliers Amiens">Amiens</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/arras/" title="Diagnostics immobiliers Arras">Arras</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/bapaume/" title="Diagnostics immobiliers Bapaume">Bapaume</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/bethune/" title="Diagnostics immobiliers Béthune">Béthune</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/cambrai/" title="Diagnostics immobiliers Cambrai">Cambrai</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/caudry/" title="Diagnostics immobiliers Caudry">Caudry</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/Chaulnes/" title="Diagnostics immobiliers Chaulnes">Chaulnes</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/compiegne/" title="Diagnostics immobiliers Compiègne">Compiègne</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/Corbie/" title="Diagnostics immobiliers Corbie">Corbie</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/douai/" title="Diagnostics immobiliers Douai">Douai</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/doullens/" title="Diagnostics immobiliers Doullens">Doullens</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/ham/" title="Diagnostics immobiliers Ham">Ham</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/laon/" title="Diagnostics immobiliers Laon">Laon</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/montdidier/" title="Diagnostics immobiliers Montdidier">Montdidier</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/moreuil/" title="Diagnostics immobiliers Moreuil">Moreuil</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/nesle/" title="Diagnostics immobiliers Nesle">Nesle</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/noyon/" title="Diagnostics immobiliers Noyon">Noyon</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/peronne/" title="Diagnostics immobiliers Péronne">Péronne</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/roisel/" title="Diagnostics immobiliers Roisel">Roisel</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/Rosi%C3%A8res%20en%20Santerre/" title="Diagnostics immobiliers Rosières-en-Santerre">Rosières-en-Santerre</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/roye/" title="Diagnostics immobiliers Roye">Roye</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/saint-quentin-02/" title="Diagnostics immobiliers Saint-Quentin">Saint-Quentin</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/tergnier/" title="Diagnostics immobiliers Tergnier">Tergnier</a></li>
    <li><a href="/diagnostics-immobiliers-hauts-de-france/Villers-Bretonneux/" title="Diagnostics immobiliers Villers-Bretonneux">Villers-Bretonneux</a></li>
  </ul>
</section>

</main>
<footer>
    <div class="footer-partner-logos">
    <img src="/img/Klarity.png" alt="Klarity">
    <img src="/img/BV.png" alt="Bureau Veritas">
  </div>
      <span>© <span id="year"></span> Intégral Diagnostics — Hauts-de-France — RCS 512225988</span>
  <p class="footer-bottom-bar">
    <a href="/contact.php">Signaler un problème</a>
    <span class="footer-sep" aria-hidden="true">·</span>
    <a href="#" id="ck-reopen">Gérer mes cookies</a>
    <span class="footer-sep" aria-hidden="true">·</span>
    <a href="/RGPD.php">Confidentialité</a>
    <span class="footer-sep" aria-hidden="true">·</span>
    <a href="/mentions-legales.php">Mentions légales</a>
  </p>
</footer>

<!-- ── Bannière consentement cookies (CNIL-conforme) ────────────────────── -->
<style>
#cookie-banner{display:none;position:fixed;bottom:0;left:0;right:0;z-index:99999;background:#1a2a1a;color:#f0f0f0;padding:16px 20px;padding-bottom:calc(16px + env(safe-area-inset-bottom));box-shadow:0 -4px 18px rgba(0,0,0,.35);font-family:inherit;font-size:.88rem;line-height:1.5;}
#cookie-banner a{color:#fff;text-decoration:underline;}
#cookie-banner strong{font-size:.95rem;}
.ck-btn{padding:9px 18px;border-radius:6px;font-weight:700;font-size:.85rem;cursor:pointer;transition:opacity .15s;}
.ck-btn-accept{border:none;background:#20a44a;color:#fff;}
.ck-btn-refuse{border:1px solid #888;background:transparent;color:#ddd;}
.ck-btn-manage{border:1px solid #fff;background:transparent;color:#fff;font-size:.78rem;padding:7px 12px;}
.ck-btn:hover{opacity:.85;}
/* Panneau préférences */
#cookie-prefs{display:none;position:fixed;bottom:0;left:0;right:0;z-index:100000;background:#111e11;color:#f0f0f0;padding:20px 24px;padding-bottom:calc(20px + env(safe-area-inset-bottom));box-shadow:0 -6px 24px rgba(0,0,0,.5);font-family:inherit;font-size:.88rem;line-height:1.6;max-height:80vh;overflow-y:auto;}
#cookie-prefs h3{margin:0 0 10px;font-size:1rem;color:#fff;}
#cookie-prefs a{color:#fff;text-decoration:underline;}
.ck-cat{display:flex;align-items:flex-start;gap:12px;margin-bottom:14px;padding:10px 12px;background:#1e301e;border-radius:6px;}
.ck-cat, .ck-cat *{color:#fff;}
.ck-cat label{font-weight:700;font-size:.88rem;color:#fff;}
.ck-cat p{margin:2px 0 0;font-size:.78rem;color:#fff;}
.ck-cat a{color:#fff;text-decoration:underline;}
.ck-toggle{flex-shrink:0;margin-top:3px;width:38px;height:20px;appearance:none;-webkit-appearance:none;background:#555;border-radius:10px;cursor:pointer;position:relative;transition:background .2s;}
.ck-toggle:checked{background:#20a44a;}
.ck-toggle::after{content:'';position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:left .2s;}
.ck-toggle:checked::after{left:20px;}
.ck-toggle:disabled{opacity:.5;cursor:not-allowed;}
</style>

<!-- Bandeau principal -->
<div id="cookie-banner" role="dialog" aria-label="Consentement aux cookies" aria-modal="true">
  <div style="max-width:1100px;margin:0 auto;display:flex;flex-wrap:wrap;align-items:center;gap:14px;">
    <div style="flex:1;min-width:220px;">
      <strong>Ce site utilise des cookies</strong><br>
      Nous utilisons des cookies <strong>strictement nécessaires</strong> au fonctionnement (session, sécurité) et, avec votre accord, des cookies <strong>analytiques</strong> (Google Analytics 4) pour améliorer nos services. Votre choix est conservé 13 mois.<br>
      <a href="/RGPD.php" target="_blank" rel="noopener">Politique de confidentialité</a>
    </div>
    <div style="display:flex;flex-wrap:wrap;gap:8px;flex-shrink:0;align-items:center;">
      <button class="ck-btn ck-btn-accept" id="ck-accept-all">Tout accepter</button>
      <button class="ck-btn ck-btn-refuse" id="ck-refuse-all">Tout refuser</button>
      <button class="ck-btn ck-btn-manage" id="ck-open-prefs">Gérer mes préférences</button>
    </div>
  </div>
</div>

<!-- Panneau préférences granulaires -->
<div id="cookie-prefs" role="dialog" aria-label="Gestion des cookies" aria-modal="true">
  <h3>Gérer mes préférences cookies</h3>
  <div class="ck-cat">
    <input type="checkbox" class="ck-toggle" id="ck-cat-essential" checked disabled aria-label="Cookies essentiels">
    <div>
      <label for="ck-cat-essential">Cookies essentiels</label>
      <p>Session PHP, sécurité CSRF, consentement cookies. Nécessaires au fonctionnement du site, ne peuvent pas être désactivés.</p>
    </div>
  </div>
  <div class="ck-cat">
    <input type="checkbox" class="ck-toggle" id="ck-cat-analytics" aria-label="Cookies analytiques">
    <div>
      <label for="ck-cat-analytics">Cookies analytiques — Google Analytics 4</label>
      <p>Mesure d'audience anonymisée (pages visitées, durée, provenance). Aucune donnée personnelle transmise. Données conservées 26 mois chez Google. <a href="https://policies.google.com/privacy" target="_blank" rel="noopener">Politique Google</a>.</p>
    </div>
  </div>
  <div style="display:flex;gap:10px;margin-top:16px;flex-wrap:wrap;">
    <button class="ck-btn ck-btn-accept" id="ck-save-prefs">Enregistrer mes choix</button>
    <button class="ck-btn ck-btn-refuse" id="ck-close-prefs">Annuler</button>
  </div>
  <p style="font-size:.72rem;color:#888;margin-top:10px;">Votre choix est conservé pendant 13 mois. Vous pouvez le modifier à tout moment via le lien "Cookies" en bas de page.</p>
</div>

<script>
(function () {
  var GA_ID = "G-BPFYYVVB6T";
  var STORAGE_KEY = 'integral_cookie_consent_v2';
  var banner  = document.getElementById('cookie-banner');
  var prefs   = document.getElementById('cookie-prefs');
  var ckAnal  = document.getElementById('ck-cat-analytics');
  var gaLoaded = false;

  function loadGA() {
    if (gaLoaded || !GA_ID || GA_ID === 'G-XXXXXXXXXX') return;
    gaLoaded = true;
    var s = document.createElement('script');
    s.async = true;
    s.src = 'https://www.googletagmanager.com/gtag/js?id=' + GA_ID;
    document.head.appendChild(s);
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    window.gtag = gtag;
    gtag('js', new Date());
    gtag('config', GA_ID, {anonymize_ip: true});
  }

  function saveConsent(analytics) {
    var exp = new Date();
    exp.setMonth(exp.getMonth() + 13);
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({analytics: analytics, expires: exp.toISOString()}));
    } catch(e) {}
    if (analytics) loadGA();
  }

  function readConsent() {
    try {
      var raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return null;
      var data = JSON.parse(raw);
      if (!data.expires || new Date(data.expires) < new Date()) { localStorage.removeItem(STORAGE_KEY); return null; }
      return data;
    } catch(e) { return null; }
  }

  function hideBanner() { banner.style.display = 'none'; }
  function hidePrefs()  { prefs.style.display  = 'none'; }
  function showPrefs()  { prefs.style.display  = 'block'; hideBanner(); }

  // Init au chargement
  var saved = readConsent();
  if (!saved) {
    banner.style.display = 'block';
  } else {
    if (saved.analytics) loadGA();
  }

  // Tout accepter
  document.getElementById('ck-accept-all').addEventListener('click', function () {
    saveConsent(true); hideBanner(); hidePrefs();
  });
  // Tout refuser
  document.getElementById('ck-refuse-all').addEventListener('click', function () {
    saveConsent(false); hideBanner(); hidePrefs();
  });
  // Ouvrir préférences
  document.getElementById('ck-open-prefs').addEventListener('click', function () {
    var saved = readConsent();
    if (ckAnal) ckAnal.checked = saved ? !!saved.analytics : false;
    showPrefs();
  });
  // Enregistrer préférences
  document.getElementById('ck-save-prefs').addEventListener('click', function () {
    var analytics = ckAnal ? ckAnal.checked : false;
    saveConsent(analytics); hidePrefs(); hideBanner();
  });
  // Fermer préférences sans sauvegarder
  document.getElementById('ck-close-prefs').addEventListener('click', function () {
    hidePrefs();
    if (!readConsent()) banner.style.display = 'block';
  });

  // Lien "Cookies" en bas de page (déclenche le panneau à tout moment)
  document.addEventListener('click', function (e) {
    if (e.target && e.target.id === 'ck-reopen') {
      var saved = readConsent();
      if (ckAnal) ckAnal.checked = saved ? !!saved.analytics : false;
      showPrefs();
    }
  });
}());
</script>
</div>

<div id="rdv-modal-overlay" class="rdv-modal-overlay" aria-hidden="true">
  <div class="rdv-modal" role="dialog" aria-modal="true" aria-labelledby="rdv-modal-title">
    <div class="rdv-modal-header">
      <p id="rdv-modal-title" class="rdv-modal-title">Prise de rendez-vous</p>
      <button type="button" id="rdv-modal-close" class="rdv-modal-close" aria-label="Fermer la fenetre de rendez-vous">Fermer</button>
    </div>
    <iframe id="rdv-modal-frame" class="rdv-modal-frame" src="about:blank" title="Prise de rendez-vous" allow="payment"></iframe>
  </div>
</div>

<script>
document.getElementById("year").textContent = new Date().getFullYear();

// --- Variables ---
const anneeCards = document.querySelectorAll(".annee-card");
const anneeInput = document.getElementById("anneeConstruction");
const anneeInconnue = document.getElementById("anneeInconnue");
const amiante = document.getElementById("amiante");
const plomb = document.getElementById("plomb");
const carrez = document.getElementById("d-carrez");
const boutin = document.getElementById("d-boutin");
const typeBienSelect = document.getElementById("typeBien");
const cadreSelect = document.getElementById("cadre");
const coproSelect = document.getElementById("coproSelect");
const surfaceInput = document.getElementById("surface");

// --- Fonctions utilitaires et calcul prix ---
function format(n){return n.toLocaleString('fr-FR',{minimumFractionDigits:2});}
function remiseDegressive(n){if(n<=1)return 0;if(n==2)return 0.20;if(n==3)return 0.30;if(n==4)return 0.35;return 0.40;}
function updatePaymentTotalLabels(total) {
  document.querySelectorAll('.payment-total-label').forEach(el => {
    el.textContent = format(total) + ' €';
  });
}
function surfaceMajor(s){if(s<=100)return 0;if(s<=150)return 0.1;if(s<=200)return 0.2;if(s<=250)return 0.3;return 0.45;}
var _kmSupplementAmount = 0;
var _kmDistance = 0;
var _horsPerimetre = false;
var HERVILLY_LAT = 49.920795;
var HERVILLY_LON = 3.120644;
var KM_RATE = 0.6;
function haversineKm(lat1, lon1, lat2, lon2) {
  var R = 6371;
  var dLat = (lat2 - lat1) * Math.PI / 180;
  var dLon = (lon2 - lon1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1 * Math.PI/180) * Math.cos(lat2 * Math.PI/180) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
}
const isConnected = false;
const csrfToken = "f12d9372659c1b5c444894cabcd7183566b410599d584ea9af903d2f89bd5573";
const publicRdvModalUrl = "";

const rdvModalOverlay = document.getElementById('rdv-modal-overlay');
const rdvModalFrame = document.getElementById('rdv-modal-frame');
const rdvModalClose = document.getElementById('rdv-modal-close');

function isAllowedModalUrl(url) {
  try {
    const resolved = new URL(url, window.location.origin);
    if (resolved.origin !== window.location.origin) return false;
    const allowed = ['/espace-client/stripe-checkout.php', '/espace-client/paypal-checkout.php', '/agenda/'];
    return allowed.some(p => resolved.pathname.startsWith(p));
  } catch (_) { return false; }
}

function openRdvModal(url) {
  if (!rdvModalOverlay || !rdvModalFrame || !url) {
    if (url) {
      window.location.href = url;
    }
    return;
  }
  if (!isAllowedModalUrl(url)) {
    console.warn('URL bloquée pour l\'iframe modal :', url);
    return;
  }
  rdvModalFrame.src = url;
  rdvModalOverlay.classList.add('open');
  rdvModalOverlay.setAttribute('aria-hidden', 'false');
  document.body.style.overflow = 'hidden';
}

let paymentCompleted = false;

function closeRdvModal() {
  if (!rdvModalOverlay || !rdvModalFrame) {
    return;
  }
  rdvModalOverlay.classList.remove('open');
  rdvModalOverlay.setAttribute('aria-hidden', 'true');
  rdvModalFrame.src = 'about:blank';
  document.body.style.overflow = '';
  if (paymentCompleted) {
    paymentCompleted = false;
    window.location.href = '/index.php';
  }
}

// --- Année construction ---
let anneeCategorie = "";
window._travauxMode = false;
function resetAnneeCards(){anneeCards.forEach(c=>c.classList.remove("active"));}
function isErpEnsaOnly(){
    var diags = Array.from(document.querySelectorAll('.diag:checked:not(.option-supp)'));
    return diags.length > 0 && diags.every(function(d){ return d.value === 'erp'; });
}

function updateDiagnosticsByYear(){
    const wg = window._wizGrised || new Set();
    const amianteWasForced = amiante.disabled || amiante.parentNode.classList.contains("diag-obligatoire");
    const isMaisonLocation = typeBienSelect.value === "maison" && cadreSelect.value === "location";
    // Si uniquement ERP/ENSA, pas d'auto-cochage amiante/plomb
  const msgObligatoire = "Obligatoire\npour cette période de construction.";
    const msgNonObligatoire = "Non obligatoire\npour cette période de construction.";
  const msgDefaultAmiante = "Diagnostic obligatoire\npar diagnostiqueur certifié pour les constructions avant le 1/07/1997.";
  const msgDefaultPlomb = "Diagnostic obligatoire\npar diagnostiqueur certifié pour les constructions avant le 1/01/1949.";
  function getDefaultHint(diag){ return diag === amiante ? msgDefaultAmiante : msgDefaultPlomb; }
    function setHint(el, text){ var h = el.querySelector('.diag-regl-hint'); if(h) h.textContent = text; }
    if (isErpEnsaOnly()) {
        [amiante, plomb].forEach(function(d){
            if(wg.has(d.id)) return; // wizard gère
            d.checked = false;
            d.disabled = false;
            d.parentNode.classList.remove('disabled','diag-obligatoire','diag-grise');
      setHint(d.parentNode, getDefaultHint(d));
        });
        return;
    }
    [amiante, plomb].forEach(d=>{
        if(wg.has(d.id)) return; // wizard gère
        d.disabled=false;
        d.parentNode.classList.remove("disabled","diag-obligatoire","diag-grise");
    setHint(d.parentNode, getDefaultHint(d));
    });
    if (isMaisonLocation && !wg.has(amiante.id)) {
        if (amianteWasForced) amiante.checked = false;
        amiante.disabled = false;
        amiante.parentNode.classList.remove("disabled","diag-obligatoire","diag-grise");
        setHint(amiante.parentNode, "Non obligatoire en location pour une maison individuelle — réalisable à la demande du client.");
    }
    if(anneeCategorie==="Avant 1949"){
        if(!isMaisonLocation && !wg.has(amiante.id)){amiante.checked=true; amiante.disabled=true; amiante.parentNode.classList.add("diag-obligatoire"); setHint(amiante.parentNode, msgObligatoire);}
        if(!wg.has(plomb.id)){plomb.checked=true; plomb.disabled=true; plomb.parentNode.classList.add("diag-obligatoire"); setHint(plomb.parentNode, msgObligatoire);}
    } else if(anneeCategorie==="1949 1997"){
        if(!isMaisonLocation && !wg.has(amiante.id)){amiante.checked=true; amiante.disabled=true; amiante.parentNode.classList.add("diag-obligatoire"); setHint(amiante.parentNode, msgObligatoire);}
        if(!wg.has(plomb.id)){plomb.checked=false; plomb.disabled=true; plomb.parentNode.classList.add("diag-grise"); setHint(plomb.parentNode, msgNonObligatoire);}
    } else if(anneeCategorie==="Après 1997"){
        if(!isMaisonLocation && !wg.has(amiante.id)){amiante.checked=false; amiante.disabled=true; amiante.parentNode.classList.add("diag-grise"); setHint(amiante.parentNode, msgNonObligatoire);}
        if(!wg.has(plomb.id)){plomb.checked=false; plomb.disabled=true; plomb.parentNode.classList.add("diag-grise"); setHint(plomb.parentNode, msgNonObligatoire);}
    } else if(anneeCategorie==="inconnue"){
      if(!isMaisonLocation && !wg.has(amiante.id)){amiante.checked=false; amiante.disabled=false; setHint(amiante.parentNode, msgDefaultAmiante);}
      if(!wg.has(plomb.id)){plomb.checked=false; plomb.disabled=false; setHint(plomb.parentNode, msgDefaultPlomb);}
    }
    updateTravauxMsg();
}

// --- Event listeners année ---
anneeCards.forEach(card=>{
    card.addEventListener("click", ()=>{
        resetAnneeCards();
        card.classList.add("active");
        anneeCategorie = card.dataset.cat;
        anneeInput.value="";
        anneeInconnue.checked=false;
        updateDiagnosticsByYear();
        calculPrix();
    });
});
anneeInput.addEventListener("change", ()=>{
    resetAnneeCards();
    anneeCategorie="";
    anneeInconnue.checked=false;
    const val = anneeInput.value; // format YYYY-MM-DD
    if(val){
        const d = new Date(val + 'T00:00:00');
        const limite1 = new Date('1949-01-01T00:00:00');
        const limite2 = new Date('1997-07-01T00:00:00');
        if(d < limite1) anneeCategorie="Avant 1949";
        else if(d < limite2) anneeCategorie="1949 1997";
        else anneeCategorie="Après 1997";
    }
    updateDiagnosticsByYear();
    calculPrix();
});
anneeInconnue.addEventListener("change", ()=>{
    if(anneeInconnue.checked){
        resetAnneeCards();
        anneeCategorie="inconnue";
        anneeInput.value="";
        updateDiagnosticsByYear();
        calculPrix();
    }
});

// --- Cadre et copro ---
function updateCadre(){
    const cadre = cadreSelect.value;
    const wg = window._wizGrised || new Set();
    if(cadre==="vente"){
        if(!wg.has(boutin.id)){boutin.checked=false; boutin.disabled=true; boutin.parentNode.classList.add("disabled");}
        if(coproSelect.value === 'oui'){
            if(!wg.has(carrez.id)){carrez.checked=true; carrez.disabled=false; carrez.parentNode.classList.remove("disabled");}
        } else {
            if(!wg.has(carrez.id)){carrez.checked=false; carrez.disabled=true; carrez.parentNode.classList.add("disabled");}
        }
    } else if(cadre==="location"){
        if(!wg.has(carrez.id)){carrez.checked=false; carrez.disabled=true; carrez.parentNode.classList.add("disabled");}
        if(!wg.has(boutin.id)){boutin.checked=true; boutin.disabled=false; boutin.parentNode.classList.remove("disabled");}
    } else {
        if(!wg.has(carrez.id)){carrez.checked=false; carrez.disabled=true; carrez.parentNode.classList.add("disabled");}
        if(!wg.has(boutin.id)){boutin.checked=false; boutin.disabled=true; boutin.parentNode.classList.add("disabled");}
    }
    // Termites : case libre sauf en mode travaux/démolition
    var termitesEl = document.getElementById('termites');
    if (termitesEl && !wg.has('termites') && cadreSelect.value !== 'travaux') {
        var tItem = termitesEl.closest ? termitesEl.closest('.diag-item') : termitesEl.parentNode;
        termitesEl.disabled = false;
        tItem.classList.remove('diag-grise');
        tItem.removeAttribute('title');
    }
}
function updateCopropriete(){
    const wg = window._wizGrised || new Set();
    if(cadreSelect.value==="vente"){
        if(!wg.has(carrez.id)){
            if(coproSelect.value === 'oui'){ carrez.checked=true; carrez.disabled=false; carrez.parentNode.classList.remove("disabled"); }
            else{ carrez.checked=false; carrez.disabled=true; carrez.parentNode.classList.add("disabled"); }
        }
    }
}

// --- Calcul prix ---
function calculPrix(){
    updateCadre();
    updateCopropriete();
    updateDiagnosticsByYear();
    syncSurfaceHabitableWithDpe(false);
    
    let subtotal = 0;
    const checkedDiags = Array.from(document.querySelectorAll(".diag:checked"));
    let diagCount = 0;
    const hasNonErpDiag = checkedDiags.some(d => !d.classList.contains("option-supp") && d.value !== "erp");

    const hasDpe = checkedDiags.some(d => d.value === "dpe");

    checkedDiags.forEach(d=>{
        if(d.classList.contains("option-supp")) return;
        if(d.value==="erp"){
            if(!hasNonErpDiag) subtotal += parseFloat(d.dataset.price)||0;
        } else if(d.value==="surface habitable"){
            if(!hasDpe){
                subtotal += parseFloat(d.dataset.price)||0;
                diagCount++;
            }
        } else {
            subtotal += parseFloat(d.dataset.price)||0;
            diagCount++;
        }
    });

    // appliquer remise dégressive
    let total = subtotal - subtotal * remiseDegressive(diagCount);

    // Si ERP/ENSA seul : prix fixe, pas de majoration surface/type/options
    if (!hasNonErpDiag && subtotal > 0) {
        total = subtotal;
    } else {
        // majoration surface
        total *= 1 + surfaceMajor(parseInt(surfaceInput.value)||0);

        // options supplémentaires
        if(document.getElementById("logement-vetuste")?.checked) total *= 1.10;
        if(document.getElementById("urgence-24h")?.checked) total *= 1.15;
        if(document.getElementById("dimanche-nuit")?.checked) total *= 1.30;

        // majoration type de bien
        if(typeBienSelect.value === "erp" || typeBienSelect.value === "tertiaire"){
            total *= 1.30;
        }
        if(typeBienSelect.value === "maison"){
            total *= 1.10;
        }
    }

    // Vérifier si uniquement ERP/ENSA (aucun déplacement, pas de km)
    var onlyErpEnsa = isErpEnsaOnly();
    var btnRdv = document.getElementById('btnPrendreRdv');
    var notice = document.getElementById('erpEnsaNotice');
    var kmItem = document.getElementById('km-supplement-item');

    // Urgence 24h — bloquer RDV, afficher message
    (function() {
      var urgenceCb = document.getElementById('urgence-24h');
      var urgenceNotice = document.getElementById('urgence-notice');
      function handleUrgence() {
        var on = urgenceCb && urgenceCb.checked;
        if (urgenceNotice) urgenceNotice.style.display = on ? 'block' : 'none';
        var brdv = document.getElementById('btnPrendreRdv');
        if (brdv) {
          brdv.disabled = on || brdv._disabledByErp;
          brdv.title = on ? 'Appelez-nous pour confirmer la disponibilité' : '';
          brdv.style.opacity = on ? '.5' : '';
          brdv.style.cursor = on ? 'not-allowed' : '';
        }
      }
      if (urgenceCb) urgenceCb.addEventListener('change', handleUrgence);
      handleUrgence();
    })();

    if (onlyErpEnsa) {
        _kmSupplementAmount = 0;
        if (kmItem) kmItem.style.display = 'none';
        btnRdv.disabled = true;
        btnRdv.style.opacity = '.5';
        btnRdv.style.cursor = 'not-allowed';
        notice.style.display = '';
        // Griser les champs inutiles (pas de visite sur site)
        [typeBienSelect, cadreSelect, surfaceInput, anneeInput].forEach(function(el){
            el.disabled = true; el.style.opacity = '.45';
        });
        anneeCards.forEach(function(c){ c.style.opacity = '.45'; c.style.pointerEvents = 'none'; });
        if (anneeInconnue) { anneeInconnue.disabled = true; }
        // Griser copropriété + chauffage/refroidissement
        ['coproSelect','chauffage','typeRadiateur','climatisationSelect','cuissonGazSelect'].forEach(function(id){
            var el = document.getElementById(id);
            if (!el) return;
            el.disabled = true;
            var wrap = el.closest ? el.closest('div[style]') : el.parentNode;
            if (wrap) wrap.style.opacity = '.45';
        });
    } else {
        btnRdv.disabled = false;
        btnRdv.style.opacity = '';
        btnRdv.style.cursor = '';
        notice.style.display = 'none';
        // Réactiver les champs
        [typeBienSelect, cadreSelect, surfaceInput, anneeInput].forEach(function(el){
            el.disabled = false; el.style.opacity = '';
        });
        anneeCards.forEach(function(c){ c.style.opacity = ''; c.style.pointerEvents = ''; });
        if (anneeInconnue) { anneeInconnue.disabled = false; }
        // Réactiver copropriété + chauffage/refroidissement
        ['coproSelect','chauffage','typeRadiateur','climatisationSelect','cuissonGazSelect'].forEach(function(id){
            var el = document.getElementById(id);
            if (!el) return;
            el.disabled = false;
            var wrap = el.closest ? el.closest('div[style]') : el.parentNode;
            if (wrap) wrap.style.opacity = '';
        });
        // Bloquer si hors périmètre (> 150 km) — sauf si ERP/ENSA seul (pas de déplacement)
        if (_horsPerimetre && !onlyErpEnsa) {
            btnRdv.disabled = true;
            btnRdv.style.opacity = '.4';
            btnRdv.style.cursor = 'not-allowed';
            var _bv = document.getElementById('btnValider');
            if (_bv) { _bv.disabled = true; _bv.style.opacity = '.4'; _bv.style.cursor = 'not-allowed'; }
        }
    }

    // supplément kilométrique (montant fixe)
    total += _kmSupplementAmount;

    total = Math.round(total);
    document.getElementById("total").textContent = format(total) + " €";
    updatePaymentTotalLabels(total);

    return total;
}
// --- Event listeners généraux ---
document.querySelectorAll(".diag, select, input").forEach(el=>{
    el.addEventListener("change", calculPrix);
});

// --- Surface habitable offerte avec DPE ---
function syncSurfaceHabitableWithDpe(recalculate){
    var dpeChk     = document.getElementById('dpe');
    var surfChk    = document.getElementById('d-habitable');
    var carrezChk   = document.getElementById('d-carrez');
    var boutinChk   = document.getElementById('d-boutin');
    if (!dpeChk || !surfChk) return;
    var surfItem = surfChk.closest ? surfChk.closest('.diag-item') : surfChk.parentNode;
    var otherSurfaceSelected = !!((carrezChk && carrezChk.checked) || (boutinChk && boutinChk.checked));

    if (otherSurfaceSelected) {
        surfChk.checked = false;
        surfChk.disabled = true;
        if (surfItem) {
            surfItem.classList.add('disabled', 'diag-grise');
            surfItem.title = 'Déjà couvert par le mesurage sélectionné';
        }
    } else if (dpeChk.checked) {
        surfChk.checked = true;
        surfChk.disabled = true;
        if (surfItem) {
            surfItem.classList.add('disabled', 'diag-grise');
            surfItem.title = 'Surface habitable offerte avec le DPE';
        }
    } else {
        surfChk.checked = false;
        surfChk.disabled = false;
        if (surfItem) {
            surfItem.classList.remove('disabled', 'diag-grise');
            surfItem.removeAttribute('title');
        }
    }

    if (recalculate) calculPrix();
}

(function(){
    var dpeChk     = document.getElementById('dpe');
    var surfChk    = document.getElementById('d-habitable');
    var carrezChk   = document.getElementById('d-carrez');
    var boutinChk   = document.getElementById('d-boutin');
    if (!dpeChk || !surfChk) return;
    dpeChk.addEventListener('change', function(){
        syncSurfaceHabitableWithDpe(true);
    });
    [carrezChk, boutinChk].forEach(function(chk) {
        if (chk) chk.addEventListener('change', function(){ syncSurfaceHabitableWithDpe(true); });
    });
}());

// --- Mode Travaux et démolitions ---
function updateTravauxMsg() {
    var msg = document.getElementById('travaux-info-msg');
    if (!msg) return;
    msg.style.display = (window._travauxMode && anneeCategorie === 'Après 1997') ? '' : 'none';
}

function applyTravauxMode() {
    var isTravaux = (cadreSelect.value === 'travaux');
    window._travauxMode = isTravaux;
    var wg = window._wizGrised || new Set();
    document.querySelectorAll('.diag:not(.option-supp)').forEach(function(d) {
        if (d.id === 'amiante' || d.id === 'plomb') return;
        if (wg.has(d.id)) return;
        var item = d.closest ? d.closest('.diag-item') : d.parentNode;
        if (isTravaux) {
            d.dataset.travauxDisabled = '1';
            d.checked = false;
            d.disabled = true;
            if (item) { item.classList.add('diag-grise'); item.title = 'Non applicable en travaux / démolitions'; }
        } else if (d.dataset.travauxDisabled) {
            delete d.dataset.travauxDisabled;
            d.disabled = false;
            if (item) { item.classList.remove('diag-grise'); item.removeAttribute('title'); }
        }
    });
    updateDiagnosticsByYear();
    calculPrix();
}

cadreSelect.addEventListener('change', applyTravauxMode);

// --- Exclusion mutuelle Termites / État parasitaire ---
(function(){
    var chkT = document.getElementById('termites');
    var chkP = document.getElementById('paras');
    if (!chkT || !chkP) return;
    function syncExclusion() {
        var itemT = chkT.closest('.diag-item');
        var itemP = chkP.closest('.diag-item');
        if (chkT.checked) {
            chkP.checked = false;
            chkP.disabled = true;
            itemP.style.opacity = '0.4';
            itemP.style.pointerEvents = 'none';
            chkT.disabled = false;
            itemT.style.opacity = '';
            itemT.style.pointerEvents = '';
        } else if (chkP.checked) {
            chkT.checked = false;
            chkT.disabled = true;
            itemT.style.opacity = '0.4';
            itemT.style.pointerEvents = 'none';
            chkP.disabled = false;
            itemP.style.opacity = '';
            itemP.style.pointerEvents = '';
        } else {
            chkT.disabled = false;
            chkP.disabled = false;
            itemT.style.opacity = '';
            itemT.style.pointerEvents = '';
            itemP.style.opacity = '';
            itemP.style.pointerEvents = '';
        }
        calculPrix();
    }
    chkT.addEventListener('change', syncExclusion);
    chkP.addEventListener('change', syncExclusion);
    window._syncTermitesParas = syncExclusion;
}());

// ======== WIZARD Diagnostics & installations existants ========
window._wizGrised = new Set();
(function () {
    var G = window._wizGrised;

    function setDiag(el, state, tooltip) {
        if (!el) return;
        var item = el.closest ? el.closest('.diag-item') : el.parentNode;
        if (!item) return;
        item.classList.remove('diag-grise', 'wiz-valide');
        item.removeAttribute('title');
        var badge = item.querySelector('.wiz-badge');
        if (!badge) {
            badge = document.createElement('span');
            badge.className = 'wiz-badge';
            item.appendChild(badge);
        }
        badge.className = 'wiz-badge';
        badge.textContent = '';
        if (state === 'valide') {
            el.checked = false; el.disabled = true;
            item.classList.add('diag-grise', 'wiz-valide');
            item.title = tooltip || 'Diagnostic valide — déjà réalisé';
            badge.className = 'wiz-badge valide'; badge.textContent = '✓ Valide';
            G.add(el.id);
        } else if (state === 'expire') {
            el.checked = true; el.disabled = false;
            item.title = tooltip || 'Diagnostic expiré — à refaire';
            badge.className = 'wiz-badge expire'; badge.textContent = '↻ À refaire';
            G.delete(el.id);
        } else {
            el.disabled = false;
            G.delete(el.id);
        }
    }

    function applyWizard() {
        var cadre       = (document.getElementById('cadre') || {}).value || '';
        var diagElec    = document.getElementById('elec');
        var diagGaz     = document.getElementById('gaz');
        var diagDpe     = document.getElementById('dpe');
        var diagErp     = document.getElementById('erp');
        var diagEnsa    = document.getElementById('ensa');
        var diagPlomb   = document.getElementById('plomb');
        var diagAmiante = document.getElementById('amiante');
        var diagTermites= document.getElementById('termites');
        var diagCarrez  = document.getElementById('d-carrez');
        var diagBoutin  = document.getElementById('d-boutin');

        // — Dates d'installation —
        var elecInstallVal = (document.getElementById('wiz-elec-date-install') || {}).value || '';
        var gazInstallVal  = (document.getElementById('wiz-gaz-date-install')  || {}).value || '';

        // — Consuel : visible seulement si install > 15 ans —
        var consuelEl  = document.getElementById('wiz-consuel');
        var consuelLbl = document.getElementById('lbl-wiz-consuel');
        if (consuelEl) {
            var consuelEnabled = elecInstallVal === '>15';
            consuelEl.disabled = !consuelEnabled;
            if (consuelLbl) {
                consuelLbl.style.opacity       = consuelEnabled ? '' : '0.4';
                consuelLbl.style.pointerEvents = consuelEnabled ? '' : 'none';
                consuelLbl.style.cursor        = consuelEnabled ? '' : 'not-allowed';
            }
            if (!consuelEnabled && consuelEl.checked) { consuelEl.checked = false; }
        }

        // — Qualigaz : visible seulement si install > 15 ans —
        var qualigazEl  = document.getElementById('wiz-qualigaz');
        var qualigazLbl = document.getElementById('lbl-wiz-qualigaz');
        if (qualigazEl) {
            var qualigazEnabled = gazInstallVal === '>15';
            qualigazEl.disabled = !qualigazEnabled;
            if (qualigazLbl) {
                qualigazLbl.style.opacity       = qualigazEnabled ? '' : '0.4';
                qualigazLbl.style.pointerEvents = qualigazEnabled ? '' : 'none';
                qualigazLbl.style.cursor        = qualigazEnabled ? '' : 'not-allowed';
            }
            if (!qualigazEnabled && qualigazEl.checked) { qualigazEl.checked = false; }
        }

        // — Consuel coché → bloque Diag élec existant —
        var consuelChecked = !!(consuelEl && consuelEl.checked);
        var hasElecEl  = document.getElementById('wiz-has-elec');
        var hasElecLbl = hasElecEl ? hasElecEl.closest('label') : null;
        if (hasElecEl) {
            hasElecEl.disabled = consuelChecked;
            if (hasElecLbl) {
                hasElecLbl.style.opacity       = consuelChecked ? '0.4' : '';
                hasElecLbl.style.pointerEvents = consuelChecked ? 'none'  : '';
            }
            if (consuelChecked && hasElecEl.checked) {
                hasElecEl.checked = false;
                var _elecSub = document.getElementById('wiz-elec-sub');
                if (_elecSub) { _elecSub.classList.remove('open'); _elecSub.querySelectorAll('select').forEach(function(s){ s.value=''; }); }
            }
        }

        // — Qualigaz coché → bloque Diag gaz existant —
        var qualigazChecked = !!(qualigazEl && qualigazEl.checked);
        var hasGazEl  = document.getElementById('wiz-has-gaz');
        var hasGazLbl = hasGazEl ? hasGazEl.closest('label') : null;
        if (hasGazEl) {
            hasGazEl.disabled = qualigazChecked;
            if (hasGazLbl) {
                hasGazLbl.style.opacity       = qualigazChecked ? '0.4' : '';
                hasGazLbl.style.pointerEvents = qualigazChecked ? 'none'  : '';
            }
            if (qualigazChecked && hasGazEl.checked) {
                hasGazEl.checked = false;
                var _gazSub = document.getElementById('wiz-gaz-sub');
                if (_gazSub) { _gazSub.classList.remove('open'); _gazSub.querySelectorAll('select').forEach(function(s){ s.value=''; }); }
            }
        }

        // — Sync champs installation masqués —
        var instElecEl  = document.getElementById('inst-elec');
        var instGazEl   = document.getElementById('inst-gaz');
        var plaqueGazEl = document.getElementById('plaque-gaz');
        if (instElecEl)  instElecEl.checked  = elecInstallVal === '>15';
        if (instGazEl)   instGazEl.checked   = gazInstallVal  === '>15';
        if (plaqueGazEl) plaqueGazEl.checked = (document.getElementById('cuissonGazSelect') || {}).value === 'oui';

        // — ÉLECTRICITÉ —
        var consuel  = consuelChecked;
        var hasElec  = !!(hasElecEl && hasElecEl.checked);
        var elecWhen = (document.getElementById('wiz-elec-when') || {}).value || '';
        if (elecInstallVal === '<15') {
            setDiag(diagElec, 'valide', 'Installation < 15 ans — diagnostic électricité non requis');
        } else if (consuel) {
            setDiag(diagElec, 'valide', 'Consuel < 3 ans — diagnostic électricité non requis');
        } else if (hasElec && elecWhen) {
            var elecOk = (cadre === 'vente' && elecWhen === 'v3') || (cadre === 'location' && (elecWhen === 'v3' || elecWhen === 'v6'));
            setDiag(diagElec, elecOk ? 'valide' : 'expire', elecOk ? 'Diagnostic électricité valide' : 'Diagnostic électricité expiré — à refaire');
        } else if (elecInstallVal === '>15') {
            setDiag(diagElec, 'expire', 'Installation > 15 ans — diagnostic électricité requis');
        } else { setDiag(diagElec, 'reset'); }

        // — GAZ —
        var qualigaz = qualigazChecked;
        var hasGaz   = !!(hasGazEl && hasGazEl.checked);
        var gazWhen  = (document.getElementById('wiz-gaz-when') || {}).value || '';
        if (gazInstallVal === '<15') {
            setDiag(diagGaz, 'valide', 'Installation < 15 ans — diagnostic gaz non requis');
        } else if (qualigaz) {
            setDiag(diagGaz, 'valide', 'Qualigaz < 3 ans — diagnostic gaz non requis');
        } else if (hasGaz && gazWhen) {
            var gazOk = (cadre === 'vente' && gazWhen === 'v3') || (cadre === 'location' && (gazWhen === 'v3' || gazWhen === 'v6'));
            setDiag(diagGaz, gazOk ? 'valide' : 'expire', gazOk ? 'Diagnostic gaz valide' : 'Diagnostic gaz expiré — à refaire');
        } else if (gazInstallVal === '>15') {
            setDiag(diagGaz, 'expire', 'Installation > 15 ans — diagnostic gaz requis');
        } else { setDiag(diagGaz, 'reset'); }

        // — DPE —
        var hasDpe  = !!(document.getElementById('wiz-has-dpe') || {}).checked;
        var dpeWhen = (document.getElementById('wiz-dpe-when') || {}).value || '';
        if (hasDpe && dpeWhen) {
            setDiag(diagDpe, dpeWhen === 'apres2021-ok' ? 'valide' : 'expire',
                dpeWhen === 'apres2021-ok' ? 'DPE valide (après le 30/06/2021, < 10 ans)' : 'DPE invalide — à refaire');
        } else { setDiag(diagDpe, 'reset'); }

        // — ERP / ENSA —
        var hasErp  = !!(document.getElementById('wiz-has-erp') || {}).checked;
        var erpWhen = (document.getElementById('wiz-erp-when') || {}).value || '';
        if (hasErp && erpWhen) {
            var erpState = erpWhen === 'ok' ? 'valide' : 'expire';
            var erpLabel = erpWhen === 'ok' ? 'ERP/ENSA valide (< 6 mois)' : 'ERP/ENSA expiré — à refaire';
            setDiag(diagErp,  erpState, erpLabel);
            setDiag(diagEnsa, erpState, erpLabel);
        } else { setDiag(diagErp, 'reset'); setDiag(diagEnsa, 'reset'); }

        // — PLOMB —
        var hasPlomb    = !!(document.getElementById('wiz-has-plomb') || {}).checked;
        var plombResult = (document.getElementById('wiz-plomb-result') || {}).value || '';
        var plombWhen   = (document.getElementById('wiz-plomb-when') || {}).value || '';
        if (hasPlomb && plombResult) {
            if (plombResult === 'negatif') {
                setDiag(diagPlomb, 'valide', 'Plomb négatif — validité illimitée');
            } else if (plombWhen) {
                var plombOk = (cadre === 'vente' && plombWhen === 'v1') || (cadre === 'location' && (plombWhen === 'v1' || plombWhen === 'v6'));
                setDiag(diagPlomb, plombOk ? 'valide' : 'expire', plombOk ? 'Diagnostic plomb valide' : 'Diagnostic plomb expiré — à refaire');
            } else { setDiag(diagPlomb, 'reset'); }
        } else { setDiag(diagPlomb, 'reset'); }

        // — AMIANTE —
        var hasAmiante    = !!(document.getElementById('wiz-has-amiante') || {}).checked;
        var amianteResult = (document.getElementById('wiz-amiante-result') || {}).value || '';
        if (hasAmiante && amianteResult) {
            setDiag(diagAmiante, amianteResult === 'negatif' ? 'valide' : 'expire',
                amianteResult === 'negatif' ? 'Amiante négatif — validité illimitée' : 'Amiante positif — à refaire selon travaux');
        } else { setDiag(diagAmiante, 'reset'); }

        // — TERMITES —
        var hasTermites  = !!(document.getElementById('wiz-has-termites') || {}).checked;
        var termitesWhen = (document.getElementById('wiz-termites-when') || {}).value || '';
        var termLocNote  = document.getElementById('wiz-termites-loc-note');
        if (termLocNote) termLocNote.style.display = cadre === 'location' ? '' : 'none';
        if (hasTermites && termitesWhen && cadre !== 'location') {
            setDiag(diagTermites, termitesWhen === 'ok' ? 'valide' : 'expire',
                termitesWhen === 'ok' ? 'État termites valide (< 6 mois)' : 'État termites expiré — à refaire');
        } else { setDiag(diagTermites, 'reset'); }

        // — CARREZ / BOUTIN : visibilité selon cadre + copropriété —
        var coproVal   = (document.getElementById('coproSelect') || {}).value || '';
        var showCarrez = cadre === 'vente' && coproVal === 'oui';
        var showBoutin = cadre === 'location';
        var carrezRow  = document.getElementById('wiz-carrez-row');
        var boutinRow  = document.getElementById('wiz-boutin-row');
        var surfHint   = document.getElementById('wiz-surfaces-hint');
        if (carrezRow) carrezRow.style.display = showCarrez ? '' : 'none';
        if (boutinRow) boutinRow.style.display = showBoutin ? '' : 'none';
        if (surfHint)  surfHint.style.display  = (!showCarrez && !showBoutin) ? '' : 'none';

        // — CARREZ —
        if (!showCarrez) {
            ['wiz-has-carrez','wiz-carrez-travaux','wiz-carrez-none'].forEach(function(id){ var e=document.getElementById(id); if(e) e.checked=false; });
            var _cs = document.getElementById('wiz-carrez-sub'); if(_cs) _cs.classList.remove('open');
            setDiag(diagCarrez, 'reset');
        } else {
            var hasCarrez     = !!(document.getElementById('wiz-has-carrez') || {}).checked;
            var carrezTravaux = !!(document.getElementById('wiz-carrez-travaux') || {}).checked;
            if (hasCarrez) {
                setDiag(diagCarrez, carrezTravaux ? 'expire' : 'valide',
                    carrezTravaux ? 'Carrez invalidé par travaux' : 'Carrez valide — pas de travaux');
            } else { setDiag(diagCarrez, 'reset'); }
        }

        // — BOUTIN —
        if (!showBoutin) {
            ['wiz-has-boutin','wiz-boutin-travaux','wiz-boutin-none'].forEach(function(id){ var e=document.getElementById(id); if(e) e.checked=false; });
            var _bs = document.getElementById('wiz-boutin-sub'); if(_bs) _bs.classList.remove('open');
            setDiag(diagBoutin, 'reset');
        } else {
            var hasBoutin     = !!(document.getElementById('wiz-has-boutin') || {}).checked;
            var boutinTravaux = !!(document.getElementById('wiz-boutin-travaux') || {}).checked;
            if (hasBoutin) {
                setDiag(diagBoutin, boutinTravaux ? 'expire' : 'valide',
                    boutinTravaux ? 'Boutin invalidé par travaux' : 'Boutin valide — pas de travaux');
            } else { setDiag(diagBoutin, 'reset'); }
        }

        // — Barre résumé —
        var bar = document.getElementById('wiz-result-bar');
        if (bar) {
            var labels = {dpe:'DPE',elec:'Électricité',gaz:'Gaz',erp:'ERP',ensa:'ENSA',plomb:'Plomb',amiante:'Amiante',termites:'Termites','d-carrez':'Carrez','d-boutin':'Boutin'};
            var parts = Object.keys(labels).filter(function(k){ return G.has(k); })
                              .map(function(k){ return '<span style="color:#136c38;font-weight:700;">✓ '+labels[k]+'</span>'; });
            if (parts.length) {
                bar.style.display = '';
                bar.innerHTML = '<strong>Diagnostics déjà valides (non facturés)&nbsp;:</strong> ' + parts.join(' &bull; ');
            } else { bar.style.display = 'none'; }
        }
        calculPrix();
    }
    window._applyWizard = applyWizard;

    // Affichage/masquage des sous-questions
    function bindSubToggle(checkId, subId) {
        var chk = document.getElementById(checkId);
        var sub = document.getElementById(subId);
        if (!chk || !sub) return;
        chk.addEventListener('change', function () {
            sub.classList.toggle('open', this.checked);
            if (!this.checked) {
                sub.querySelectorAll('select').forEach(function(s){ s.value = ''; });
                sub.querySelectorAll('input[type=checkbox]').forEach(function(c){ c.checked = false; });
            }
            applyWizard();
        });
    }
    [['wiz-has-elec','wiz-elec-sub'],['wiz-has-gaz','wiz-gaz-sub'],['wiz-has-dpe','wiz-dpe-sub'],
     ['wiz-has-erp','wiz-erp-sub'],['wiz-has-plomb','wiz-plomb-sub'],
     ['wiz-has-amiante','wiz-amiante-sub'],['wiz-has-termites','wiz-termites-sub'],
     ['wiz-has-carrez','wiz-carrez-sub'],['wiz-has-boutin','wiz-boutin-sub']
    ].forEach(function(p){ bindSubToggle(p[0], p[1]); });

    // — Pas de diag : exclusion mutuelle avec les autres cases de chaque bloc —
    var wizNonePairs = [
        { none: 'wiz-elec-none',     others: [{id:'wiz-consuel', sub:null}, {id:'wiz-has-elec', sub:'wiz-elec-sub'}] },
        { none: 'wiz-gaz-none',      others: [{id:'wiz-qualigaz', sub:null}, {id:'wiz-has-gaz', sub:'wiz-gaz-sub'}] },
        { none: 'wiz-dpe-none',      others: [{id:'wiz-has-dpe',     sub:'wiz-dpe-sub'}] },
        { none: 'wiz-erp-none',      others: [{id:'wiz-has-erp',     sub:'wiz-erp-sub'}] },
        { none: 'wiz-plomb-none',    others: [{id:'wiz-has-plomb',   sub:'wiz-plomb-sub'}] },
        { none: 'wiz-amiante-none',  others: [{id:'wiz-has-amiante', sub:'wiz-amiante-sub'}] },
        { none: 'wiz-termites-none', others: [{id:'wiz-has-termites',sub:'wiz-termites-sub'}] },
        { none: 'wiz-carrez-none',   others: [{id:'wiz-has-carrez',  sub:'wiz-carrez-sub'}] },
        { none: 'wiz-boutin-none',   others: [{id:'wiz-has-boutin',  sub:'wiz-boutin-sub'}] },
    ];
    wizNonePairs.forEach(function(pair) {
        var noneEl = document.getElementById(pair.none);
        if (!noneEl) return;
        // Cocher "pas de diag" → décocher/fermer les autres
        noneEl.addEventListener('change', function () {
            pair.others.forEach(function(item) {
                var el = document.getElementById(item.id);
                if (!el || el.disabled) return;
                el.checked = false;
                if (item.sub) {
                    var sub = document.getElementById(item.sub);
                    if (sub && sub.classList.contains('open')) {
                        sub.classList.remove('open');
                        sub.querySelectorAll('select').forEach(function(s){ s.value = ''; });
                        sub.querySelectorAll('input[type=checkbox]').forEach(function(c){ c.checked = false; });
                    }
                }
            });
            applyWizard();
        });
        // Cocher une option → décocher "pas de diag"
        pair.others.forEach(function(item) {
            var el = document.getElementById(item.id);
            if (!el) return;
            el.addEventListener('change', function () {
                if (this.checked) { noneEl.checked = false; }
            });
        });
    });

    // Sous-question date plomb positif
    document.getElementById('wiz-plomb-result') && document.getElementById('wiz-plomb-result').addEventListener('change', function () {
        var ds = document.getElementById('wiz-plomb-date-sub');
        if (ds) ds.style.display = this.value === 'positif' ? '' : 'none';
        applyWizard();
    });

    // Tous les selects et cases du wizard
    var step2 = document.getElementById('wizardStep2');
    if (step2) {
        step2.querySelectorAll('select').forEach(function(el){ el.addEventListener('change', applyWizard); });
        ['wiz-consuel','wiz-qualigaz',
         'wiz-carrez-travaux','wiz-boutin-travaux'].forEach(function(id){
            var el = document.getElementById(id);
            if (el) el.addEventListener('change', applyWizard);
        });
    }

    // Boutons Oui / Non
    document.getElementById('wizardOui') && document.getElementById('wizardOui').addEventListener('click', function () {
        step2.style.display = '';
        this.classList.add('active');
        document.getElementById('wizardNon').classList.remove('active');
        applyWizard();
    });
    document.getElementById('wizardNon') && document.getElementById('wizardNon').addEventListener('click', function () {
        step2.style.display = 'none';
        // Reset toutes les cases et selects du wizard
        step2.querySelectorAll('input[type=checkbox]').forEach(function(c){ c.checked = false; });
        step2.querySelectorAll('select').forEach(function(s){ s.value = ''; });
        step2.querySelectorAll('.wiz-sub').forEach(function(s){ s.classList.remove('open'); });
        var pds = document.getElementById('wiz-plomb-date-sub');
        if (pds) pds.style.display = 'none';
        this.classList.add('active');
        document.getElementById('wizardOui').classList.remove('active');
        // Réinitialiser tous les diags
        G.clear();
        ['elec','gaz','dpe','erp','ensa','plomb','amiante','termites','d-carrez','d-boutin'].forEach(function(id){
            setDiag(document.getElementById(id), 'reset');
        });
        ['inst-elec','inst-gaz','plaque-gaz'].forEach(function(id){
            var el = document.getElementById(id); if (el) el.checked = false;
        });
        calculPrix();
    });

    // Relancer le wizard quand le cadre ou la copropriété change
    document.getElementById('cadre') && document.getElementById('cadre').addEventListener('change', function () {
        if (step2 && step2.style.display !== 'none') applyWizard();
    });
    document.getElementById('coproSelect') && document.getElementById('coproSelect').addEventListener('change', function () {
        if (step2 && step2.style.display !== 'none') applyWizard();
    });
}());

// --- Vérificateur unifié zones termites + PEB (api-adresse + dept + IGN WFS) ---
window._zoneVerified = false;
(function(){
    var input   = document.getElementById('zone-adresse-input');
    var list    = document.getElementById('zone-suggestions');
    var btn     = document.getElementById('zone-btn-verif');
    var resT    = document.getElementById('zone-result-termites');
    var resP    = document.getElementById('zone-result-peb');
    var termitesChk = document.getElementById('termites');
    var ensaChk  = document.getElementById('erp');
    var coords  = null;
    var debounce = null;

    function setSuggestions(items){
        list.innerHTML = '';
        if(!items.length){ list.style.display='none'; return; }
        items.forEach(function(f){
            var li = document.createElement('li');
            li.textContent = f.properties.label;
            li.style.cssText = 'padding:8px 12px;cursor:pointer;font-size:13px;border-bottom:1px solid #eee;';
            li.addEventListener('mousedown', function(e){
                e.preventDefault();
                input.value = f.properties.label;
                coords = { lon: f.geometry.coordinates[0], lat: f.geometry.coordinates[1], insee: f.properties.citycode,
                           postcode: f.properties.postcode || '', city: f.properties.city || '',
                           housenumber: f.properties.housenumber || '', street: f.properties.street || f.properties.name || '' };
                list.style.display = 'none';
                resT.textContent = ''; resP.textContent = '';
            });
            li.addEventListener('mouseover', function(){ li.style.background='#edf2fb'; });
            li.addEventListener('mouseout',  function(){ li.style.background=''; });
            list.appendChild(li);
        });
        list.style.display = 'block';
    }

    input.addEventListener('input', function(){
        coords = null;
        window._zoneVerified = false;
        _horsPerimetre = false;
        var _hpm = document.getElementById('horsPerimetreMsg');
        if (_hpm) _hpm.style.display = 'none';
        clearTimeout(debounce);
        var q = input.value.trim();
        if(q.length < 3){ list.style.display='none'; return; }
        debounce = setTimeout(function(){
            fetch('/api/adresse.php?q=' + encodeURIComponent(q))
                .then(function(r){ return r.json(); })
                .then(function(d){ setSuggestions(d.features || []); })
                .catch(function(){ list.style.display='none'; });
        }, 280);
    });

    document.addEventListener('click', function(e){
        if(!input.contains(e.target)) list.style.display='none';
    });

    btn.addEventListener('click', async function(){
        if(!coords){
            resT.innerHTML = '<span style="color:#b45309;">&#9432; Sélectionnez d\'abord une adresse dans la liste.</span>';
            resP.textContent = '';
            return;
        }

        // Pré-remplir les champs adresse du bien (publics si présents, sinon cachés)
        var bNum = document.getElementById('public-bien-numero') || document.getElementById('hidden-bien-numero');
        var bRue = document.getElementById('public-bien-rue') || document.getElementById('hidden-bien-rue');
        var bCp  = document.getElementById('public-bien-cp') || document.getElementById('hidden-bien-cp');
        var bVil = document.getElementById('public-bien-ville') || document.getElementById('hidden-bien-ville');
        if (bNum) bNum.value = coords.housenumber;
        if (bRue) bRue.value = coords.street;
        if (bCp)  bCp.value  = coords.postcode;
        if (bVil) bVil.value = coords.city;

        // Supplément kilométrique via itinéraire routier (OSRM proxy)
        var kmItem = document.getElementById('km-supplement-item');
        var kmLabel = document.getElementById('km-supplement-label');
        var horsPerimetreMsg = document.getElementById('horsPerimetreMsg');
        var btnRdvZone = document.getElementById('btnPrendreRdv');
        var btnValiderZone = document.getElementById('btnValider');
        var KM_FRANCHISE = 40;
        var distKmRoute = 9999;
        try {
            var _rr = await fetch('/api/route-distance.php?from_lon=' + HERVILLY_LON + '&from_lat=' + HERVILLY_LAT + '&to_lon=' + coords.lon + '&to_lat=' + coords.lat);
            var _rd = await _rr.json();
            if (_rd.code === 'Ok') distKmRoute = _rd.routes[0].distance / 1000;
        } catch(e) { /* garde la valeur 9999 si OSRM injoignable */ }
        _kmDistance = Math.round(distKmRoute * 10) / 10;
        if (distKmRoute > 150) {
            _horsPerimetre = true;
            _kmSupplementAmount = 0;
            if (kmItem) kmItem.style.display = 'none';
            if (horsPerimetreMsg) horsPerimetreMsg.style.display = 'block';
            if (btnRdvZone)    { btnRdvZone.disabled = true;    btnRdvZone.style.opacity = '.4';    btnRdvZone.style.cursor = 'not-allowed'; }
            if (btnValiderZone){ btnValiderZone.disabled = true; btnValiderZone.style.opacity = '.4'; btnValiderZone.style.cursor = 'not-allowed'; }
        } else {
            _horsPerimetre = false;
            if (horsPerimetreMsg) horsPerimetreMsg.style.display = 'none';
            if (btnValiderZone){ btnValiderZone.disabled = false; btnValiderZone.style.opacity = ''; btnValiderZone.style.cursor = ''; }
            if (distKmRoute > KM_FRANCHISE) {
                var distFacturee = Math.round((distKmRoute - KM_FRANCHISE) * 2 * 10) / 10;
                _kmSupplementAmount = Math.round(distFacturee * KM_RATE * 100) / 100;
                kmLabel.textContent = 'Participation aux frais kilométriques : ' + _kmDistance + ' km (' + distFacturee + ' km facturés A/R) — ' + _kmSupplementAmount.toLocaleString('fr-FR', {minimumFractionDigits:2}) + ' €';
                if (kmItem) kmItem.style.display = '';
            } else {
                _kmSupplementAmount = 0;
                if (kmItem) kmItem.style.display = 'none';
            }
        }
        calculPrix();

        resT.innerHTML = '<span style="color:#555;">&#8987; Vérification termites...</span>';
        resP.innerHTML = '<span style="color:#555;">&#8987; Vérification PEB...</span>';
        btn.disabled = true;

        var pT = fetch('/api/georisques-termites.php?code_insee=' + encodeURIComponent(coords.insee) + (coords.street ? '&rue=' + encodeURIComponent(coords.street) : ''))
                    .then(function(r){ return r.json(); });
        var pP = fetch('/api/peb.php?lat=' + coords.lat + '&lon=' + coords.lon)
                    .then(function(r){ return r.json(); });

        Promise.allSettled([pT, pP]).then(function(res){
            btn.disabled = false;
            window._zoneVerified = true;
            var _zcEl = document.getElementById('zone-checker');
            if (_zcEl) _zcEl.classList.remove('_req-err-section');
            var changed = false;

            // --- Termites ---
            var lienArrete = ' <a href="https://www.service-public.gouv.fr/particuliers/vosdroits/R75824" target="_blank" rel="noopener noreferrer" style="font-size:12px;text-decoration:underline;">Consulter les arrêtés</a>';
            if (res[0].status === 'fulfilled') {
                var t = res[0].value;
                if (t.zone === true) {
                    resT.innerHTML = '<span style="color:#c0392b;">&#9888; Zone termitée — case Termites cochée automatiquement.</span>' + lienArrete;
                    var cadreVal = document.getElementById('cadre')?.value;
                    var termitesGrised = (window._wizGrised || new Set()).has('termites');
                    if (termitesChk && !termitesChk.checked && cadreVal !== 'location' && !termitesGrised) { termitesChk.checked = true; changed = true; if (window._syncTermitesParas) window._syncTermitesParas(); }
                    if (cadreVal === 'location') resT.innerHTML += ' <em style="color:#b45309;">(non requis légalement en location — réalisable à la demande du client)</em>';
                } else if (t.zone === 'partiel' || t.source === 'departement_probable' || t.source === 'commune_partielle') {
                    resT.innerHTML = '<span style="color:#e67e22;">&#9888; Zone partiellement termitée — contactez votre mairie. Case Termites cochée automatiquement.</span>' + lienArrete;
                    var cadreVal2 = document.getElementById('cadre')?.value;
                    var termitesGrised2 = (window._wizGrised || new Set()).has('termites');
                    if (termitesChk && !termitesChk.checked && cadreVal2 !== 'location' && !termitesGrised2) { termitesChk.checked = true; changed = true; if (window._syncTermitesParas) window._syncTermitesParas(); }
                    if (cadreVal2 === 'location') resT.innerHTML += ' <em style="color:#b45309;">(non requis légalement en location — réalisable à la demande du client)</em>';
                } else {
                    var today = new Date(); var dd = String(today.getDate()).padStart(2,'0'); var mm = String(today.getMonth()+1).padStart(2,'0'); var yyyy = today.getFullYear();
                    resT.innerHTML = '<span style="color:#136c38;">&#10003; Aucun arrêté à la date du ' + dd + '/' + mm + '/' + yyyy + '. Niveau d\'infestation inconnu.</span>' + lienArrete;
                }
            } else {
                resT.innerHTML = '<span style="color:#888;">&#9888; Vérification termites impossible.</span>';
            }

            // --- PEB ---
            if (res[1].status === 'fulfilled') {
                var p = res[1].value;
                if (p.zone === true && p.aeroports && p.aeroports.length) {
                    var a = p.aeroports[0];
                    var zoneStr = (p.zonePEB || a.zone || '');
                    var zoneBadge = zoneStr ? ' <b>Zone ' + zoneStr + '</b>' : '';
                    var lien = a.arrete ? ' <a href="' + a.arrete + '" target="_blank" rel="noopener" style="color:#c0392b;font-weight:normal;">Arrêté PEB</a>' : '';
                    resP.innerHTML =
                        '<span style="color:#c0392b;">&#9992; PEB' + zoneBadge + ' — ' + a.nom + '.' + lien + ' — case ENSA cochée automatiquement.</span>';
                    if (ensaChk && !ensaChk.checked) { ensaChk.checked = true; changed = true; }
                } else if (p.zone === null) {
                    resP.innerHTML = '<span style="color:#888;">&#9888; Vérification PEB impossible.</span>';
                } else {
                    resP.innerHTML = '<span style="color:#136c38;">&#10003; Bien hors zone PEB.</span>';
                }
            } else {
                resP.innerHTML = '<span style="color:#888;">&#9888; Vérification PEB impossible.</span>';
            }

            if (changed) calculPrix();
        });
    });
}());

// --- Helpers validation visuelle ---
function _reqErr(id) {
  var el = document.getElementById(id);
  if (!el) return;
  el.classList.add('_req-err');
  var clear = function(){ el.classList.remove('_req-err'); el.removeEventListener('change', clear); el.removeEventListener('input', clear); };
  el.addEventListener('change', clear);
  el.addEventListener('input', clear);
}
function _reqErrSection(id) {
  var el = document.getElementById(id);
  if (el) el.classList.add('_req-err-section');
}
function _clearAllReqErr() {
  document.querySelectorAll('._req-err, ._req-err-section').forEach(function(el){
    el.classList.remove('_req-err', '_req-err-section');
  });
}

// --- Validation + sauvegarde session + redirection recap ---
function validateConfigurator(){
    _clearAllReqErr();

    // Vérification zones termites & PEB requise
    if (!window._zoneVerified) {
        _reqErrSection('zone-checker');
        var zoneChecker = document.getElementById('zone-checker');
        if (zoneChecker) zoneChecker.scrollIntoView({ behavior: 'smooth', block: 'center' });
        alert('Veuillez vérifier l\'adresse du bien (zones termites & PEB) avant de continuer.');
        return;
    }

    // ERP/ENSA seuls : pas besoin de type, cadre, surface, année
    if (isErpEnsaOnly()) {
        return { typeBien: typeBienSelect.value || 'na', cadre: cadreSelect.value || 'na', surface: 0 };
    }

    const typeBien = typeBienSelect.value;
    const cadre = cadreSelect.value;
    const surface = parseInt(surfaceInput.value);
    const anneeSelected = anneeInput.value || anneeCategorie || anneeInconnue.checked;

    const copro = (document.getElementById('coproSelect') || {}).value || '';
    var _mainErr = [];
    if (typeBien === '')              { _reqErr('typeBien');    _mainErr.push('Type de bien'); }
    if (cadre === '')                 { _reqErr('cadre');       _mainErr.push('Cadre'); }
    if (isNaN(surface) || surface <= 0) { _reqErr('surface'); _mainErr.push('Surface'); }
    if (copro === '')                 { _reqErr('coproSelect'); _mainErr.push('Copropriété'); }
    if (_mainErr.length > 0) {
        document.getElementById('typeBien').scrollIntoView({ behavior: 'smooth', block: 'center' });
        alert('Veuillez renseigner : ' + _mainErr.join(', ') + '.');
        return;
    }

    if (!anneeSelected) {
        _reqErrSection('annee-section-req');
        var anneeEl = document.getElementById('annee-section-req');
        if (anneeEl) anneeEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
        alert("Veuillez sélectionner une année de construction ou cocher 'Inconnue'.");
        return;
    }

    // — Informations complémentaires requises —
    if (!isErpEnsaOnly()) {
        var _infErrors = [];
        if (!document.getElementById('chauffage').value)          { _reqErr('chauffage');          _infErrors.push('Type de chauffage'); }
        if (!document.getElementById('typeRadiateur').value)      { _reqErr('typeRadiateur');      _infErrors.push('Type de radiateurs'); }
        if (!(document.getElementById('climatisationSelect') || {}).value) { _reqErr('climatisationSelect'); _infErrors.push('Climatisation'); }
        if (!(document.getElementById('cuissonGazSelect')    || {}).value) { _reqErr('cuissonGazSelect');    _infErrors.push('Cuisson gaz'); }
        if (_infErrors.length > 0) {
            document.getElementById('chauffage').scrollIntoView({ behavior: 'smooth', block: 'center' });
            alert('Veuillez compléter les informations complémentaires :\n\u2022 ' + _infErrors.join('\n\u2022 '));
            return;
        }
    }

    // — Wizard Oui/Non requis —
    var wizOuiBtnEl = document.getElementById('wizardOui');
    var wizNonBtnEl = document.getElementById('wizardNon');
    if (wizOuiBtnEl && wizNonBtnEl &&
        !wizOuiBtnEl.classList.contains('active') &&
        !wizNonBtnEl.classList.contains('active')) {
        _reqErrSection('wizardSection');
        var wizSecEl = document.getElementById('wizardSection');
        if (wizSecEl) wizSecEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
        alert('Veuillez indiquer si vous avez des diagnostics ou documents existants \u00e0 votre nom (Oui ou Non).');
        return;
    }

    // — Si Oui, chaque bloc doit avoir au moins une réponse —
    if (wizOuiBtnEl && wizOuiBtnEl.classList.contains('active') &&
        document.getElementById('wizardStep2')) {
        var _g  = function(id) { return document.getElementById(id); };
        var _c  = function(id) { var e=_g(id); return !!(e && e.checked); };
        var _v  = function(id) { var e=_g(id); return !!(e && e.value); };
        var wizErrors = [];
        if (!_v('wiz-elec-date-install') && !_c('wiz-consuel') && !_c('wiz-has-elec') && !_c('wiz-elec-none'))
            wizErrors.push('\u26a1 Électricité');
        if (!_v('wiz-gaz-date-install') && !_c('wiz-qualigaz') && !_c('wiz-has-gaz') && !_c('wiz-gaz-none'))
            wizErrors.push('\ud83d\udd25 Gaz');
        if (!_c('wiz-has-dpe')     && !_c('wiz-dpe-none'))     wizErrors.push('\ud83c\udfe0 DPE');
        if (!_c('wiz-has-erp')     && !_c('wiz-erp-none'))     wizErrors.push('\u26a0\ufe0f ERP/ENSA');
        if (!_c('wiz-has-plomb')   && !_c('wiz-plomb-none'))   wizErrors.push('\ud83c\udfaf Plomb');
        var _typeBienVal2 = (document.getElementById('typeBien')||{}).value||'';
        var _cadreVal2 = (document.getElementById('cadre')||{}).value||'';
        var _amianteFacultatifMaisonLocation = _typeBienVal2 === 'maison' && _cadreVal2 === 'location';
        if (!_amianteFacultatifMaisonLocation && !_c('wiz-has-amiante') && !_c('wiz-amiante-none')) wizErrors.push('\ud83c\udfd6\ufe0f Amiante');
        if (!_c('wiz-has-termites')&& !_c('wiz-termites-none'))wizErrors.push('\ud83d\udc1b Termites');
        var _coproVal2 = (document.getElementById('coproSelect')||{}).value||'';
        if (_cadreVal2 === 'vente' && _coproVal2 === 'oui' && !_c('wiz-has-carrez') && !_c('wiz-carrez-none'))
            wizErrors.push('\ud83d\udcd0 Carrez');
        if (_cadreVal2 === 'location' && !_c('wiz-has-boutin') && !_c('wiz-boutin-none'))
            wizErrors.push('\ud83d\udcd0 Boutin');
        if (wizErrors.length > 0) {
            var _s2 = document.getElementById('wizardStep2');
            if (_s2) _s2.scrollIntoView({ behavior: 'smooth', block: 'start' });
            alert('Veuillez compléter toutes les rubriques du questionnaire :\n\u2022 ' + wizErrors.join('\n\u2022 ') + '\n\nPour chaque rubrique, cochez au moins une option ou \"Pas de diag\".');
            return;
        }
    }

    // Vérification tertiaire > 250 m2
    const surfaceError = document.getElementById("surface-error");
    surfaceError.style.display = "none";
    if(typeBien === "erp" && surface > 250){
        surfaceError.style.display = "block";
      return null;
    }

    return { typeBien, cadre, surface };
  }

  function buildDevisPayload(){
    const validated = validateConfigurator();
    if (!validated) {
      return null;
    }

    // --- Récupération diagnostics ---
    let diagnosticsArray = Array.from(document.querySelectorAll(".diag:checked:not(.option-supp)")).map(d => d.value);
    // ERP/ENSA sont toujours un document commun — on inclut les deux dans le payload
    if (diagnosticsArray.includes('erp') && !diagnosticsArray.includes('ensa')) {
        diagnosticsArray = [...diagnosticsArray, 'ensa'];
    }

    // --- Calcul de la base HORS options (pour calculer les montants en € des options) ---
    let baseAvantOptions = 0;
    {
        let _sub = 0, _nb = 0;
        const _all = Array.from(document.querySelectorAll(".diag:checked:not(.option-supp)"));
        const _hasNonErp = _all.some(x => x.value !== "erp");
        const _hasDpe = _all.some(x => x.value === "dpe");
        _all.forEach(d => {
            if (d.value === "erp") {
                if (!_hasNonErp) _sub += parseFloat(d.dataset.price) || 0;
            } else if (d.value === "surface habitable") {
                if (!_hasDpe) {
                    _sub += parseFloat(d.dataset.price) || 0;
                    _nb++;
                }
            } else {
                _sub += parseFloat(d.dataset.price) || 0;
                _nb++;
            }
        });
        baseAvantOptions = _sub * (1 - remiseDegressive(_nb));
        if (_hasNonErp) {
            baseAvantOptions *= 1 + surfaceMajor(parseInt(surfaceInput.value) || 0);
            if (typeBien === "erp" || typeBien === "tertiaire") baseAvantOptions *= 1.30;
            if (typeBien === "maison") baseAvantOptions *= 1.10;
        }
    }

    // --- Récupération options avec montants en € (percentages appliqués sur la base courante) ---
    const optionsArray = [];
    const optionsTarifsArray = [];
    let runningBase = baseAvantOptions;

    if (document.getElementById("logement-vetuste")?.checked) {
        const amt = Math.round(runningBase * 0.10 * 100) / 100;
        optionsArray.push("Logement vétuste +10%");
        optionsTarifsArray.push(amt);
        runningBase *= 1.10;
    }
    if (document.getElementById("urgence-24h")?.checked) {
        const amt = Math.round(runningBase * 0.15 * 100) / 100;
        optionsArray.push("Urgence 24h +15%");
        optionsTarifsArray.push(amt);
        runningBase *= 1.15;
    }
    if (document.getElementById("dimanche-nuit")?.checked) {
        const amt = Math.round(runningBase * 0.30 * 100) / 100;
        optionsArray.push("Dimanche / Nuit +30%");
        optionsTarifsArray.push(amt);
    }
    if (_kmSupplementAmount > 0) {
        optionsArray.push('Participation aux frais kilométriques (' + Math.round(_kmDistance) + ' km)');
        optionsTarifsArray.push(_kmSupplementAmount);
    }

    // --- Préparer l'objet à envoyer ---
    return {
      typeBien: validated.typeBien,
      cadre: validated.cadre,
        surface: surfaceInput.value,
        annee: anneeInput.value || anneeCategorie,
        diagnostics: diagnosticsArray,
        diagnostics_tarifs: (() => {
            const hasDpe = diagnosticsArray.includes('dpe');
            const hasNonErp = diagnosticsArray.some(d => d !== 'erp' && d !== 'ensa');
            return diagnosticsArray.map(d => {
                if (d === 'surface habitable' && hasDpe) return 0;
                if (d === 'ensa') return 0;
                if (d === 'erp') return hasNonErp ? 0 : (parseFloat(document.querySelector('.diag[value="erp"]')?.dataset.price) || 0);
                const el = document.querySelector(`.diag[value="${d}"]`);
                return el ? parseFloat(el.dataset.price) || 0 : 0;
            });
        })(),
        options: optionsArray,
        options_tarifs: optionsTarifsArray,
        instElec15: document.getElementById("inst-elec").checked,
        instGaz15: document.getElementById("inst-gaz").checked,
        plaqueGaz: (document.getElementById('cuissonGazSelect') || {}).value === 'oui',
        termitesVolontaire: cadreSelect.value === 'location' && !!(document.getElementById('termites') || {}).checked,
        chauffage: document.getElementById("chauffage").value,
        typeRadiateur: document.getElementById("typeRadiateur").value,
        climatisation: (document.getElementById('climatisationSelect') || {}).value || '',
        cuissonGaz: (document.getElementById('cuissonGazSelect') || {}).value || '',
        vetuste: document.getElementById("logement-vetuste").checked,
        dimancheNuit: document.getElementById("dimanche-nuit").checked,
        urgence24h: document.getElementById("urgence-24h").checked,
        copro: coproSelect.value === 'oui',
        anneeInconnue: anneeInconnue.checked,
        total: calculPrix(),
        bienNumero: (document.getElementById('hidden-bien-numero')?.value.trim() || document.getElementById('public-bien-numero')?.value.trim() || ''),
        bienRue: (document.getElementById('hidden-bien-rue')?.value.trim() || document.getElementById('public-bien-rue')?.value.trim() || ''),
        bienCP: (document.getElementById('hidden-bien-cp')?.value.trim() || document.getElementById('public-bien-cp')?.value.trim() || ''),
        bienVille: (document.getElementById('hidden-bien-ville')?.value.trim() || document.getElementById('public-bien-ville')?.value.trim() || '')
    };
    }

    function persistDevisSession(data){
      return fetch("/espace-client/devis_session.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...data, csrf_token: csrfToken })
      }).then(r => r.json());
    }

    function goToRecap(openRdv = false){
      const data = buildDevisPayload();
      if (!data) {
        return;
      }

    // --- Envoi avec fetch ---
      persistDevisSession(data)
    .then(res => {
        if (res.success) {
            window.location.href = openRdv ? "/recapitulatif.php?rdv=1" : "/recapitulatif.php";
        } else {
            alert("Une erreur est survenue. Veuillez réessayer.");
        }
    })
    .catch(e => alert("Erreur réseau : " + e.message));
      }

  function showPublicRdvMessage(message, type) {
    const box = document.getElementById('publicRdvMsg');
    if (!box) return;
    box.className = 'public-rdv-inline-msg ' + type;
    box.textContent = message;
  }

  function setPublicStep(step) {
    const stages = [1, 2, 3];
    stages.forEach((value) => {
      const stage = document.getElementById('publicRdvStage' + value);
      const indicator = document.getElementById('publicStepIndicator' + value);
      if (stage) {
        stage.classList.toggle('active', value === step);
      }
      if (indicator) {
        indicator.classList.remove('active', 'done');
        if (value < step) {
          indicator.classList.add('done');
        } else if (value === step) {
          indicator.classList.add('active');
        }
      }
    });
  }

  function getPublicRdvFormData() {
    return {
      clientPrenom: document.getElementById('public-client-prenom')?.value.trim() || '',
      clientNom: document.getElementById('public-client-nom')?.value.trim() || '',
      clientEmail: document.getElementById('public-client-email')?.value.trim() || '',
      clientTel: document.getElementById('public-client-tel')?.value.trim() || '',
      clientNumero: document.getElementById('public-client-numero')?.value.trim() || '',
      clientRue: document.getElementById('public-client-rue')?.value.trim() || '',
      clientCP: document.getElementById('public-client-cp')?.value.trim() || '',
      clientVille: document.getElementById('public-client-ville')?.value.trim() || '',
      bienNumero: document.getElementById('public-bien-numero')?.value.trim() || '',
      bienRue: document.getElementById('public-bien-rue')?.value.trim() || '',
      bienCP: document.getElementById('public-bien-cp')?.value.trim() || '',
      bienVille: document.getElementById('public-bien-ville')?.value.trim() || ''
    };
  }

  function openPublicRdvPanel() {
    const data = buildDevisPayload();
    if (!data) {
      return;
    }

    const panel = document.getElementById('publicRdvPanel');
    if (!panel) {
      return;
    }

    panel.classList.add('open');
    setPublicStep(1);
    showPublicRdvMessage('Complétez vos coordonnées pour régler l\'acompte de 20 € avant la prise de rendez-vous.', 'success');
    panel.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

function validatePublicCoordinates() {
    const formData = getPublicRdvFormData();
    const requiredFields = [
      ['clientPrenom', 'Prénom'],
      ['clientNom', 'Nom'],
      ['clientEmail', 'E-mail'],
      ['clientTel', 'Téléphone'],
      ['clientNumero', 'N° de rue client'],
      ['clientRue', 'Rue client'],
      ['clientCP', 'Code postal client'],
      ['clientVille', 'Ville client'],
      ['bienNumero', 'N° de rue du bien'],
      ['bienRue', 'Rue du bien'],
      ['bienCP', 'Code postal du bien'],
      ['bienVille', 'Ville du bien']
    ];

    const missing = requiredFields.filter(([key]) => !formData[key]).map(([, label]) => label);
    if (missing.length > 0) {
      showPublicRdvMessage('Champs obligatoires manquants : ' + missing.join(', ') + '.', 'error');
      return null;
    }

    return formData;
}

function buildPublicRdvSummary(formData) {
    const selectedPayment = document.querySelector('input[name="public-payment-mode"]:checked');
    const paymentLabel = selectedPayment?.value === 'total_paypal'
        ? 'PayPal'
        : selectedPayment?.value === 'total_stripe'
          ? 'Carte Stripe (total)'
          : 'Acompte 20 € — Stripe';
    const amountLabel = selectedPayment?.value === 'acompte_stripe'
      ? '20 €'
      : (document.querySelector('.payment-total-label')?.textContent || 'Total du devis');
    const amountTitle = selectedPayment?.value === 'acompte_stripe' ? 'Acompte à régler' : 'Montant à régler';
    const summary = document.getElementById('publicRdvSummary');
    if (!summary) {
        return;
    }

    summary.innerHTML = [
        '<p><strong>Mode de paiement :</strong> ' + paymentLabel + '</p>',
        '<p><strong>Client :</strong> ' + formData.clientPrenom + ' ' + formData.clientNom + ' - ' + formData.clientEmail + ' - ' + formData.clientTel + '</p>',
        '<p><strong>Adresse client :</strong> ' + formData.clientNumero + ' ' + formData.clientRue + ', ' + formData.clientCP + ' ' + formData.clientVille + '</p>',
        '<p><strong>Bien à diagnostiquer :</strong> ' + formData.bienNumero + ' ' + formData.bienRue + ', ' + formData.bienCP + ' ' + formData.bienVille + '</p>',
        '<p><strong>' + amountTitle + ' :</strong> ' + amountLabel + '</p>'
    ].join('');
}

  function submitPublicRdvFromIndex() {
    const devisPayload = buildDevisPayload();
    if (!devisPayload) {
      return;
    }

    const formData = validatePublicCoordinates();
    if (!formData) {
      return;
    }

    const selectedPayment = document.querySelector('input[name="public-payment-mode"]:checked');
    if (!selectedPayment) {
      showPublicRdvMessage('Choisissez un mode de paiement.', 'error');
      return;
    }

    const confirmButton = document.getElementById('btnPublicRdvConfirm');
    if (confirmButton) {
      confirmButton.disabled = true;
      confirmButton.textContent = 'Préparation du paiement...';
    }

    const sessionPayload = {
      ...devisPayload,
      ...formData
    };

    persistDevisSession(sessionPayload)
      .then((res) => {
        if (!res.success) {
          throw new Error('Impossible de préparer la demande.');
        }

        return fetch('/create_public_rdv.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            csrf_token: csrfToken,
            payment_mode: selectedPayment.value,
            return_to: 'index',
            acceptedEstimateNotice: !!document.getElementById('public-accept-estimate')?.checked,
            acceptedLegalNotice: !!document.getElementById('public-accept-legal')?.checked,
            ...formData
          })
        });
      })
      .then(async (response) => {
        const result = await response.json();
        if (!response.ok || !result.success) {
          if (result.error_type === 'existing_account') {
            const box = document.getElementById('publicRdvMsg');
            if (box) {
              box.className = 'public-rdv-inline-msg error';
              box.innerHTML = 'Un compte existe déjà avec cette adresse e-mail. Veuillez vous <a href="#" style="color:inherit;text-decoration:underline" id="existingAccountLink">connecter</a>';
            }
            const link = document.getElementById('existingAccountLink');
            if (link) {
              link.addEventListener('click', function(e) {
                e.preventDefault();
                const payload = buildDevisPayload();
                if (payload) {
                  persistDevisSession(payload).then(() => {
                    window.location.href = '/connexion.php?return_to=devis';
                  });
                } else {
                  window.location.href = '/connexion.php';
                }
              });
            }
            return;
          }
          throw new Error(result.message || 'Impossible de creer la demande de RDV.');
        }
        showPublicRdvMessage('Paiement en cours dans la fenetre de rendez-vous...', 'success');
        openRdvModal(result.redirect_url);
      })
      .catch((error) => {
        showPublicRdvMessage(error.message || 'Erreur lors de la creation de la demande de RDV.', 'error');
        if (confirmButton) {
          confirmButton.disabled = false;
          confirmButton.textContent = "Confirmer et payer";
        }
      });
  }

  function goToPublicPaymentNextStep() {
    const selectedPayment = document.querySelector('input[name="public-payment-mode"]:checked');
    if (!selectedPayment) {
      showPublicRdvMessage('Choisissez un mode de paiement.', 'error');
      return;
    }

    setPublicStep(2);
    showPublicRdvMessage('Mode sélectionné. Renseignez vos coordonnées.', 'success');
    const firstField = document.getElementById('public-client-prenom');
    if (firstField) {
      firstField.focus();
    }
  }

  function goToPublicValidationStep() {
    const acceptEstimate = document.getElementById('public-accept-estimate');
    const acceptLegal = document.getElementById('public-accept-legal');
    if (!acceptEstimate?.checked || !acceptLegal?.checked) {
      showPublicRdvMessage('Merci de cocher les deux cases des informations précontractuelles avant de continuer.', 'error');
      return;
    }

    const formData = validatePublicCoordinates();
    if (!formData) {
      return;
    }

    buildPublicRdvSummary(formData);
    setPublicStep(3);
    showPublicRdvMessage('Vérifiez le récapitulatif puis lancez le paiement.', 'success');
    const confirmButton = document.getElementById('btnPublicRdvConfirm');
    if (confirmButton) {
      confirmButton.scrollIntoView({ behavior: 'smooth', block: 'center' });
      confirmButton.focus();
    }
  }

      document.getElementById("btnValider").addEventListener("click", () => {
        // ERP/ENSA seuls : flux direct sans RDV → erp-commander.php (gère connecté et non-connecté)
        if (isErpEnsaOnly()) {
          const _erpAdresseInput = document.getElementById('zone-adresse-input');
          const _erpAdresseVal = _erpAdresseInput ? _erpAdresseInput.value.trim() : '';
          window.location.href = '/erp-commander.php' + (_erpAdresseVal ? '?adresse=' + encodeURIComponent(_erpAdresseVal) : '');
          return;
        }
        goToRecap(false);
      });
      document.getElementById("btnPrendreRdv").addEventListener("click", () => {
      // Vérifier si uniquement ERP/ENSA (pas de RDV nécessaire)
      const checkedDiags = Array.from(document.querySelectorAll('.diag:checked:not(.option-supp)')).map(d => d.value.toLowerCase());
      const nonErpEnsa = checkedDiags.filter(d => d !== 'erp' && d !== 'ensa');
      if (checkedDiags.length > 0 && nonErpEnsa.length === 0) {
        alert('Les diagnostics ERP et ENSA ne nécessitent pas de rendez-vous. Ces documents sont à télécharger directement.');
        return;
      }
      if (isConnected) {
        goToRecap(true);
        return;
      }
      openPublicRdvPanel();
      });

      document.getElementById('public-copy-address')?.addEventListener('change', (event) => {
      if (!event.target.checked) {
        return;
      }
      document.getElementById('public-bien-numero').value = document.getElementById('public-client-numero').value;
      document.getElementById('public-bien-rue').value = document.getElementById('public-client-rue').value;
      document.getElementById('public-bien-cp').value = document.getElementById('public-client-cp').value;
      document.getElementById('public-bien-ville').value = document.getElementById('public-client-ville').value;
      });

      document.getElementById('btnPublicRdvConfirm')?.addEventListener('click', submitPublicRdvFromIndex);
      document.getElementById('btnPublicPaymentNext')?.addEventListener('click', goToPublicPaymentNextStep);
      document.getElementById('btnPublicCoordsNext')?.addEventListener('click', goToPublicValidationStep);

      if (rdvModalClose) {
        rdvModalClose.addEventListener('click', closeRdvModal);
      }

      if (rdvModalOverlay) {
        rdvModalOverlay.addEventListener('click', (event) => {
          if (event.target === rdvModalOverlay) {
            closeRdvModal();
          }
        });
      }

      document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && rdvModalOverlay && rdvModalOverlay.classList.contains('open')) {
          closeRdvModal();
        }
      });

      rdvModalFrame?.addEventListener('load', () => {
        if (!rdvModalOverlay || !rdvModalOverlay.classList.contains('open')) {
          return;
        }

        let frameUrl = '';
        try {
          frameUrl = rdvModalFrame.contentWindow?.location?.href || '';
        } catch (_) {
          return;
        }

        if (!frameUrl) {
          return;
        }

        try {
          const parsed = new URL(frameUrl, window.location.origin);
          if (parsed.pathname.startsWith('/agenda/')) {
            paymentCompleted = true;
          }
          const isReturnPage = parsed.pathname === '/index.php' || parsed.pathname === '/recapitulatif.php';
          if (isReturnPage && parsed.searchParams.get('rdv_modal') === '1') {
            window.location.href = parsed.pathname + parsed.search;
          }
        } catch (_) {
          // Ignore malformed iframe URLs.
        }
      });

      if (publicRdvModalUrl) {
        openRdvModal(publicRdvModalUrl);
      }
// --- Initial calcul ---
calculPrix();
</script>
<script>
/* === Créneaux disponibles widget (index.php) === */
(function () {
  'use strict';
  var _debounce = null;

  function loadCreneaux() {
    var bar = document.getElementById('slotsBarContent');
    if (bar) bar.innerHTML = '<span class="creneaux-loading">Chargement\u2026</span>';
    var diags = Array.from(document.querySelectorAll('.diag:checked:not(.option-supp)'))
      .map(function (d) { return d.value.toLowerCase(); }).join(',');
    var url = '/api/prochains-creneaux.php' + (diags ? '?diags=' + encodeURIComponent(diags) : '');
    fetch(url)
      .then(function (r) { return r.json(); })
      .then(function (data) {
        var slots = data.slots || [];
        if (bar) {
          bar.innerHTML = '';
          if (!slots.length) {
            bar.innerHTML = '<span style="font-size:12px;color:#6b7280;">Aucun cr\u00e9neau dans les 60 prochains jours.</span>';
          } else {
            slots.forEach(function (slot) {
              var chip = document.createElement('span');
              chip.className = 'slot-chip';
              chip.textContent = slot.label;
              bar.appendChild(chip);
            });
          }
        }
      })
      .catch(function () {
        if (bar) bar.innerHTML = '<span style="font-size:12px;color:#6b7280;">Indisponible.</span>';
      });
  }

  function schedule() { clearTimeout(_debounce); _debounce = setTimeout(loadCreneaux, 600); }

  document.addEventListener('DOMContentLoaded', function () {
    setTimeout(loadCreneaux, 600);
    document.querySelectorAll('.diag').forEach(function (el) { el.addEventListener('change', schedule); });
    var cadreEl = document.getElementById('cadre');
    if (cadreEl) cadreEl.addEventListener('change', schedule);
  });
}());
</script>
<script src="/script.js" defer></script>
<script>
(function () {
  // Synchronisation des cases gaz/elec masquées (logique propre à index.php)
  var diagGaz = document.getElementById('gaz');
  var diagElec = document.getElementById('elec');
  var gazTriggers = [
    document.getElementById('plaque-gaz'),
    document.getElementById('inst-gaz')
  ].filter(Boolean);
  var elecTrigger = document.getElementById('inst-elec');

  gazTriggers.forEach(function (trigger) {
    trigger.addEventListener('change', function () {
      if (diagGaz) diagGaz.checked = gazTriggers.some(function (t) { return t.checked; });
      calculPrix();
    });
  });

  if (elecTrigger) {
    elecTrigger.addEventListener('change', function () {
      if (diagElec) diagElec.checked = elecTrigger.checked;
      calculPrix();
    });
  }
}());
</script>
</body>
</html>