/* ============================================================
   TotaalDakConcept demo - interactions + state
   ============================================================ */
(function () {
  "use strict";

  /* ---------- Shared config ---------- */
  var STORE_KEY = "tdc_demo_state";

  var DEFAULTS = {
    naam: "", organisatie: "", mail: "",
    roof: "Traditioneel dak",
    ondergrond: "Staal",
    thermische: "6,0 ((m2.K)/W) (bouwbesluit)",
    klimaatklasse: "Klimaatklasse II",
    beloopbaarheid: "Goed beloopbaar klasse C",
    afschot: "1,6% afschot",
    isolatie: "PIR",
    bevestiging: "Mechanisch bevestigd",
    ballast: "Geen ballast",
    toplaagMat: "EPDM",
    typeToplaag: "1-laags systeem"
  };

  var ROOF_IMG = {
    "Traditioneel dak": "roof-traditioneel.png",
    "Terras en leefdak": "roof-terras.png",
    "Luchtzuivering NOx": "roof-luchtzuivering.png",
    "Zonreflectie": "roof-zonreflectie.png",
    "PV \u2013 energiepanelen": "roof-pv.png",
    "Parkeerdak": "roof-parkeerdak.png",
    "Groendak \u2013 Extensief": "roof-groendak-ext.png",
    "Groendak \u2013 Intensief": "roof-groendak-int.png",
    "Groendak \u2013 Waterretentie": "roof-groendak-water.png"
  };

  // accordion title -> state key (step 4)
  var TITLE_KEY = {
    "Ondergrond": "ondergrond",
    "Thermische prestatie": "thermische",
    "Klimaatklasse": "klimaatklasse",
    "Beloopbaarheid": "beloopbaarheid",
    "Afschot": "afschot",
    "Isolatie materiaal": "isolatie",
    "Bevestiging daksysteem": "bevestiging",
    "Ballastlaag / dak verharding": "ballast",
    "Toplaag materiaal": "toplaagMat",
    "Type toplaag": "typeToplaag"
  };

  /* ---------- Tiny persistent store (localStorage + safe fallback) ---------- */
  var mem = {};
  function rawGet() {
    try {
      var s = window.localStorage.getItem(STORE_KEY);
      return s ? JSON.parse(s) : {};
    } catch (e) { return mem; }
  }
  function rawSet(obj) {
    mem = obj;
    try { window.localStorage.setItem(STORE_KEY, JSON.stringify(obj)); } catch (e) {}
  }
  function storeSet(patch) {
    var cur = rawGet();
    for (var k in patch) { if (patch.hasOwnProperty(k)) cur[k] = patch[k]; }
    rawSet(cur);
  }

  // merged state: DEFAULTS <- localStorage <- URL hash (url wins, used for the final hop)
  function getState() {
    var st = {};
    var k;
    for (k in DEFAULTS) st[k] = DEFAULTS[k];
    var ls = rawGet();
    for (k in ls) if (ls[k] !== "" && ls[k] != null) st[k] = ls[k];
    try {
      if (location.hash.length > 1) {
        var url = JSON.parse(decodeURIComponent(escape(atob(decodeURIComponent(location.hash.slice(1))))));
        for (k in url) if (url[k] !== "" && url[k] != null) st[k] = url[k];
      }
    } catch (e) {}
    return st;
  }
  function encodeState(st) {
    return encodeURIComponent(btoa(unescape(encodeURIComponent(JSON.stringify(st)))));
  }

  // expose for step 5
  window.TDC = { getState: getState, DEFAULTS: DEFAULTS, ROOF_IMG: ROOF_IMG };

  /* ---------- Toast helper ---------- */
  function showToast(msg) {
    var t = document.getElementById("toast");
    if (!t) {
      t = document.createElement("div");
      t.id = "toast"; t.className = "toast";
      document.body.appendChild(t);
    }
    t.textContent = msg;
    void t.offsetWidth;
    t.classList.add("show");
    clearTimeout(t._timer);
    t._timer = setTimeout(function () { t.classList.remove("show"); }, 3200);
  }

  /* ---------- Accordion open / close (step 4) ---------- */
  document.querySelectorAll(".acc-head").forEach(function (head) {
    head.addEventListener("click", function () {
      head.closest(".acc-item").classList.toggle("open");
    });
  });

  /* ---------- Roof type selection (step 3) ---------- */
  var roofgrid = document.querySelector(".roofgrid");
  if (roofgrid) {
    // persist the default-selected card on load
    var def = roofgrid.querySelector(".roofcard.selected");
    if (def) storeSet({ roof: def.getAttribute("data-roof") });
    roofgrid.querySelectorAll(".roofcard").forEach(function (card) {
      card.addEventListener("click", function () {
        roofgrid.querySelectorAll(".roofcard").forEach(function (c) { c.classList.remove("selected"); });
        card.classList.add("selected");
        storeSet({ roof: card.getAttribute("data-roof") });
      });
    });
  }

  /* ---------- Step 4: sync Gebruiksfunctie with chosen roof + persist defaults ---------- */
  var accordion = document.querySelector(".accordion");
  if (accordion) {
    var st = getState();

    // gebruiksfunctie display = chosen roof
    var funcItem = accordion.querySelector('.acc-item[data-fixed="1"]');
    if (funcItem) {
      var ft = funcItem.querySelector(".acc-value-text");
      if (ft) ft.textContent = st.roof;
      var fc = funcItem.querySelector(".func-card span");
      if (fc) fc.textContent = st.roof;
      var fimg = funcItem.querySelector(".func-card img");
      if (fimg && ROOF_IMG[st.roof]) { fimg.src = "images/" + ROOF_IMG[st.roof]; fimg.alt = st.roof; }
    }

    // persist whatever is selected by default so step 5 is complete
    accordion.querySelectorAll(".acc-item").forEach(function (item) {
      var titleEl = item.querySelector(".acc-title");
      if (!titleEl) return;
      var key = TITLE_KEY[titleEl.textContent.trim()];
      if (!key) return;
      var sel = item.querySelector(".opt-card.selected, .opt-pill.selected");
      if (sel) storeSet(makePatch(key, sel.getAttribute("data-val")));
    });
  }

  function makePatch(key, val) { var o = {}; o[key] = val; return o; }

  function setAccValue(item, value) {
    if (!item) return;
    var txt = item.querySelector(".acc-value-text");
    if (txt) txt.textContent = value;
    var titleEl = item.querySelector(".acc-title");
    if (titleEl) {
      var key = TITLE_KEY[titleEl.textContent.trim()];
      if (key) storeSet(makePatch(key, value));
    }
  }

  /* ---------- Option cards inside an accordion (step 4) ---------- */
  document.querySelectorAll(".acc-body .opt-row").forEach(function (row) {
    row.querySelectorAll(".opt-card").forEach(function (cardEl) {
      cardEl.addEventListener("click", function () {
        row.querySelectorAll(".opt-card").forEach(function (c) { c.classList.remove("selected"); });
        cardEl.classList.add("selected");
        setAccValue(cardEl.closest(".acc-item"), cardEl.getAttribute("data-val"));
      });
    });
  });

  /* ---------- Option pills inside an accordion (step 4) ---------- */
  document.querySelectorAll(".acc-body .opt-pills").forEach(function (group) {
    group.querySelectorAll(".opt-pill").forEach(function (pill) {
      pill.addEventListener("click", function () {
        group.querySelectorAll(".opt-pill").forEach(function (p) { p.classList.remove("selected"); });
        pill.classList.add("selected");
        setAccValue(pill.closest(".acc-item"), pill.getAttribute("data-val"));
      });
    });
  });

  /* ---------- Finish button (step 4) -> go to results (step 5) ---------- */
  var finish = document.getElementById("finish");
  if (finish) {
    finish.addEventListener("click", function () {
      var state = getState();
      window.location.href = "step5.html#" + encodeState(state);
    });
  }

  /* ---------- Step 2 form validation ---------- */
  var toStep3 = document.getElementById("to-step3");
  if (toStep3) {
    var freeProviders = [
      "gmail.com", "googlemail.com", "hotmail.com", "hotmail.nl",
      "outlook.com", "live.nl", "live.com", "yahoo.com", "ymail.com",
      "icloud.com", "me.com", "msn.com", "ziggo.nl", "kpnmail.nl",
      "planet.nl", "home.nl", "gmx.com", "proton.me", "protonmail.com"
    ];
    var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    function clearErr() {
      ["f-naam", "f-org", "f-mail"].forEach(function (id) {
        var el = document.getElementById(id);
        if (el) el.classList.remove("invalid");
      });
    }

    toStep3.addEventListener("click", function () {
      clearErr();
      var ok = true;

      var naam = document.getElementById("naam");
      if (!naam.value.trim()) { document.getElementById("f-naam").classList.add("invalid"); ok = false; }

      var org = document.getElementById("organisatie");
      if (!org.value.trim()) { document.getElementById("f-org").classList.add("invalid"); ok = false; }

      var mail = document.getElementById("mail");
      var mErr = document.getElementById("mail-err");
      var val = mail.value.trim().toLowerCase();
      var domain = val.split("@")[1] || "";
      if (!emailRe.test(val)) {
        mErr.textContent = "Vul a.u.b. een geldig e-mailadres in.";
        document.getElementById("f-mail").classList.add("invalid"); ok = false;
      } else if (freeProviders.indexOf(domain) !== -1) {
        mErr.textContent = "Gebruik a.u.b. uw zakelijke e-mailadres.";
        document.getElementById("f-mail").classList.add("invalid"); ok = false;
      }

      if (ok) {
        storeSet({ naam: naam.value.trim(), organisatie: org.value.trim(), mail: mail.value.trim() });
        window.location.href = "step3.html";
      }
    });

    ["naam", "organisatie", "mail"].forEach(function (id) {
      var input = document.getElementById(id);
      if (input) input.addEventListener("input", function () {
        input.closest(".field").classList.remove("invalid");
      });
    });
  }
})();
