$(function () {
  const perHour = 15;
  const hostingCost = 450;
  const taxation = 0.18;
  const hours = {
    platform: 0,
    industry: 0,
    screen: 16,
    integrations: {
      map: 40,
      payment: 40,
      devices: 40,
      sms: 40,
      crm: 40,
      email: 40,
      notSure: 40,
    },
    features: {
      dashboard: 40,
      userManagement: 40,
      wallet: 40,
      ratings: 16,
      chatting: 56,
      notification: 16,
      qr: 16,
      analytics: 40,
      upload: 24,
      videoStreaming: 40,
      events: 40,
      referral: 40,
    },
  };

  function hoursCalculation(data) {
    const totalScreensValue = parseInt(data.screens);
    const hoursPerScreenValue = hours.screen * totalScreensValue; // Calculate total hours for screens

    console.log(hoursPerScreenValue);
    // Calculate total hours for integrations based on selected integrations
    const selectedIntegrations = data.integrations;
    const totalIntegrationsValue = selectedIntegrations.reduce(
      (total, integration) => {
        if (hours.integrations[integration]) {
          return total + hours.integrations[integration];
        }
        return total;
      },
      0
    );

    // Calculate total hours for features based on selected features
    const selectedFeatures = data.features;
    const totalFeaturesValue = selectedFeatures.reduce((total, feature) => {
      if (hours.features[feature]) {
        return total + hours.features[feature];
      }
      return total;
    }, 0);

    let platformCostMultiplier = 1; // Default multiplier
    let platformHours = "";

    const totalHoursValue =
      hoursPerScreenValue + totalIntegrationsValue + totalFeaturesValue;

    if (data.platform === "web") {
      platformHours = `${totalHoursValue} (Web)`;
    } else if (data.platform === "mobile") {
      platformHours = `${totalHoursValue} (Mobile)`;
    } else if (data.platform === "both") {
      platformHours = `${totalHoursValue} (Web), ${totalHoursValue} (Mobile) `;
      platformCostMultiplier = 2;
    }

    const totalHours = totalHoursValue * platformCostMultiplier;
    const totalAmount = totalHours * perHour;

    // Set values for the specified IDs in HTML
    document.getElementById(
      "totalScreens"
    ).textContent = `${totalScreensValue} (Screen) - `;
    document.getElementById(
      "hoursPerScreen"
    ).textContent = `${hoursPerScreenValue} (hours)`;
    document.getElementById("totalIntegrations").textContent =
      selectedIntegrations
        .map(
          (integration) =>
            `${integration} - ${hours.integrations[integration]} (hours)`
        )
        .join(", ");
    document.getElementById("totalFeatures").textContent = selectedFeatures
      .map((feature) => `${feature} - ${hours.features[feature]} (hours)`)
      .join(", ");
    document.getElementById("totalPlatforms").textContent = platformHours;
    document.getElementById("totalPlatforms").textContent = platformHours;
    document.getElementById("totalHours").textContent = `${totalHours} - Hours`;
    document.getElementById("totalAmount").textContent = `$ ${totalAmount}`;
  }

  // Calculate total hours
  function calculateTotalHours(data, hours) {
    // Calculate total hours for screens
    const totalScreensValue = parseInt(data.screens);
    const hoursPerScreenValue = hours.screen * totalScreensValue;

    // Calculate total hours for integrations based on selected integrations
    const selectedIntegrations = data.integrations;
    const totalIntegrationsValue = selectedIntegrations.reduce(
      (total, integration) => {
        if (hours.integrations[integration]) {
          return total + hours.integrations[integration];
        }
        return total;
      },
      0
    );

    // Calculate total hours for features based on selected features
    const selectedFeatures = data.features;
    const totalFeaturesValue = selectedFeatures.reduce((total, feature) => {
      if (hours.features[feature]) {
        return total + hours.features[feature];
      }
      return total;
    }, 0);

    const totalHoursValue =
      hoursPerScreenValue + totalIntegrationsValue + totalFeaturesValue;

    const integrationsData = selectedIntegrations.map((integration) => ({
      type: integration.charAt(0).toUpperCase() + integration.slice(1),
      hrs: hours.integrations[integration],
      total: hours.integrations[integration] * perHour,
    }));

    const featureData = selectedFeatures.map((feature) => ({
      type: feature.charAt(0).toUpperCase() + feature.slice(1),
      hrs: hours.features[feature],
      total: hours.features[feature] * perHour,
    }));

    const platformData =
      data.platform === "both"
        ? [
            {
              type: "Web",
              hrs: totalHoursValue,
              total: totalHoursValue * perHour,
            },
            {
              type: "Mobile",
              hrs: totalHoursValue,
              total: totalHoursValue * perHour,
            },
          ]
        : [
            {
              type: data.platform.charAt(0).toUpperCase() + data.platform.slice(1),
              hrs: totalHoursValue,
              total: totalHoursValue * perHour,
            },
          ];

    const platformCost =
      data.platform === "both" ? totalHoursValue * 2 : totalHoursValue;

    const subTotal = hostingCost + platformCost * perHour;
    const tax = subTotal * taxation;
    const grandTotal = tax + subTotal;

    let hourCal = [
      {
        item: "Screen",
        type: `${totalScreensValue} (S)`,
        hrs: hoursPerScreenValue,
        total: hoursPerScreenValue * perHour,
      },
      { item: "Integrations", children: integrationsData },
      { item: "Features", children: featureData },
      { item: "Platform", children: platformData },
      {
        item: "Hosting",
        type: `8GB Ram/100 GB Storage`,
        hrs: `---`,
        total: hostingCost,
      },
      {
        item: "Sub Total",
        type: null,
        hrs: null,
        total: subTotal,
        footer: true,
      },
      {
        item: "Tax (18%)",
        type: null,
        hrs: null,
        total: tax.toFixed(2),
        footer: true,
      },
      {
        item: "Grand Total",
        type: null,
        hrs: null,
        total: grandTotal,
        footer: true,
      },
    ];

    return hourCal;
  }

  // Create the invoice table dynamically and bind it to HTM
  function createInvoiceTable(data) {
    const totalHoursData = calculateTotalHours(data, hours);
    const table = document.getElementById("invoiceTable");
    const rowsData = [];
    totalHoursData.forEach((record) => {
      if (record.children) {
        record.children.forEach((child, index) => {
          let children = {
            data: [
              index == 0 ? record.item : "",
              child.type,
              child.hrs,
              "$" + child.total,
            ],
          };
          if (index == record.children.length - 1) {
            children["props"] = { class: "article-row" };
          }
          rowsData.push(children);
        });
      } else if (record.footer) {
        rowsData.push({
          data: ["", "", record.item, "$" + record.total],
          footer: true,
        });
      } else {
        rowsData.push({
          data: [record.item, record.type, record.hrs, "$" + record.total],
          props: { class: "article-row" },
        });
      }
    });
    // Populate the table with rows and data
    rowsData.forEach((rowData) => {
      const row = document.createElement("tr");
      let footer = rowData.footer;
      rowData.data.forEach((cellData, index) => {
        const cell = document.createElement("td");
        cell.textContent = cellData;
        // Check if it's the first cell and add the class accordingly
        if (rowData?.props?.class) {
          cell.classList.add(rowData.props.class);
        }
        if (index === 0) {
          cell.classList.add("article");
        } else {
          cell.classList.add("article-record");
        }
        if (footer) {
          if (index === 0) {
            cell.classList.add("table-label");
          } else {
            cell.classList.add("table-value");
          }
        } else if (rowData[0] === "") {
          cell.classList.add("article-row");
        }

        row.appendChild(cell);
      });
      table.appendChild(row);
    });
  }

  let form = $("#wizard").steps({
    headerTag: "h4",
    bodyTag: "section",
    transitionEffect: "fade",
    enableAllSteps: false,
    transitionEffectSpeed: 300,
    labels: {
      next: "Next",
      previous: "Previous",
      finish: "Get Estimation",
    },
    onInit: function (event, current) {
      $(".actions a[href=\\#finish]").attr("id", "getEstimation");
    },
    onStepChanging: function (event, currentIndex, newIndex) {
      if (newIndex >= 1) {
        $(".steps ul li:first-child a img").attr(
          "src",
          "assets/img/stepper/platform.png"
        );
      } else {
        $(".steps ul li:first-child a img").attr(
          "src",
          "assets/img/stepper/platform-active.png"
        );
      }

      if (newIndex === 1) {
        $(".steps ul li:nth-child(2) a img").attr(
          "src",
          "assets/img/stepper/industry-active.png"
        );
      } else {
        $(".steps ul li:nth-child(2) a img").attr(
          "src",
          "assets/img/stepper/industry.png"
        );
      }

      if (newIndex === 2) {
        $(".steps ul li:nth-child(3) a img").attr(
          "src",
          "assets/img/stepper/screens-active.png"
        );
      } else {
        $(".steps ul li:nth-child(3) a img").attr(
          "src",
          "assets/img/stepper/screens.png"
        );
      }

      if (newIndex === 3) {
        $(".steps ul li:nth-child(4) a img").attr(
          "src",
          "assets/img/stepper/integrations-active.png"
        );
      } else {
        $(".steps ul li:nth-child(4) a img").attr(
          "src",
          "assets/img/stepper/integrations.png"
        );
      }

      if (newIndex === 4) {
        $(".steps ul li:nth-child(5) a img").attr(
          "src",
          "assets/img/stepper/features-active.png"
        );
      } else {
        $(".steps ul li:nth-child(5) a img").attr(
          "src",
          "assets/img/stepper/features.png"
        );
      }

      if (newIndex === 5) {
        $(".steps ul li:nth-child(6) a img").attr(
          "src",
          "assets/img/stepper/budget-active.png"
        );
        $(".actions ul").addClass("step-4");

        const data = form.serializeArray();
        const processedData = processFormData(data);
        console.log(processedData);
        createInvoiceTable(processedData);
      } else {
        $(".steps ul li:nth-child(6) a img").attr(
          "src",
          "assets/img/stepper/budget.png"
        );
        $(".actions ul").removeClass("step-4");
      }
      return true;
    },
  });
  console.log(form);
  // Event when the form is submitted

  $("#getEstimation").on("click", function (e) {
    const data = form.serializeArray();
    const processedData = processFormData(data);
    console.log(processedData);
    // You can do more with the data here, like sending it to the server

    // To prevent the form submission and handle it manually
    return false;
  });

  // Custom Button Jquery Steps
  $(".forward").click(function () {
    $("#wizard").steps("next");
  });
  $(".backward").click(function () {
    $("#wizard").steps("previous");
  });
  // Create Steps Image
  $(".steps ul li:first-child")
    .append(
      '<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">'
    )
    .find("a")
    .append('<img src="assets/img/stepper/platform-active.png" alt=""> ')
    .append('<span class="step-order">Platform</span>');
  $(".steps ul li:nth-child(2)")
    .append(
      '<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">'
    )
    .find("a")
    .append('<img src="assets/img/stepper/industry.png" alt="">')
    .append('<span class="step-order">Industry</span>');
  $(".steps ul li:nth-child(3)")
    .append(
      '<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">'
    )
    .find("a")
    .append('<img src="assets/img/stepper/screens.png" alt="">')
    .append('<span class="step-order">Screens</span>');
  $(".steps ul li:nth-child(4)")
    .append(
      '<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">'
    )
    .find("a")
    .append('<img src="assets/img/stepper/integrations.png" alt="">')
    .append('<span class="step-order">Integrations</span>');
  $(".steps ul li:nth-child(5)")
    .append(
      '<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">'
    )
    .find("a")
    .append('<img src="assets/img/stepper/features.png" alt="">')
    .append('<span class="step-order">Features</span>');
  /* $('.steps ul li:nth-child(6)').append('<img src="assets/img/stepper/step-arrow.png" alt="" class="step-arrow">').find('a').append('<img src="assets/img/stepper/timelines.png" alt="">').append('<span class="step-order">Timelines</span>'); */
  $(".steps ul li:last-child a")
    .append('<img src="assets/img/stepper/budget.png" alt="">')
    .append('<span class="step-order">Estimation</span>');

  $(".control-group").change(function () {
    if ($(this).find('input[type="radio"]').length > 0) {
      // Handle single-select (radio) sections
      $(".control-group").removeClass("selected");
      $(".item-name").removeClass("highlighted");
      $(this).addClass("selected");
      const itemId = $(this).find(".item-name").attr("id");
      const itemName = $(this).find(".item-name").text();
      console.log(`Selected item ID: ${itemId}`);
      console.log(`Selected item Name: ${itemName}`);
    } else if ($(this).find('input[type="checkbox"]').length > 0) {
      // Handle multiple-select (checkbox) sections
      $(this).toggleClass("selected");
      $(this).find(".item-name").toggleClass("highlighted");
      const itemId = $(this).find(".item-name").attr("id");
      const isChecked = $(this).find('input[type="checkbox"]').prop("checked");
      const itemName = $(this).find(".item-name").text();
      console.log(`Selected item ID: ${itemId}`);
      console.log(`Selected item Name: ${itemName}`, isChecked);
    }
  });

  $(document).on("mouseenter", ".control-group", function() {
    // Show the tooltip with class 'CustomToolTip'
    console.log("control-group focus");
    $('.wizard-fieldset').addClass('card-hover');
});

// When any '.control-group' element is blurred (loses focus)
$(document).on("mouseleave", ".control-group", function() {
    // Hide the tooltip
    console.log("control-group blur");
    $('.wizard-fieldset').removeClass('card-hover');
});

    // When an element with class 'control-group' is focused
    $('.cost-calculator .control-group').focus(function() {
      // Show the tooltip with class 'CustomToolTip'
      console.log("control-group focus");
      $('.wizard-fieldset').addClass('card-hover');
    });
  
    // When the focused element is blurred (loses focus)
    $(".control-group").blur(function () {
      console.log("control-group blur");
      // Hide the tooltip
      $('.wizard-fieldset').removeClass('card-hover');
    });

if (location.protocol === 'https:') {
    console.clear();
    console.log('%cHey Techy! We\'re looking for people like you. Checkout our openings at https://www.intellixon.com/career', 'color: #00FF00; font-size: 24px; font-weight: bold;');
    console.log = function() {};
    console.warn = function() {};
    console.error = function() {};
}

  function processFormData(formData) {
    const processedData = {};

    formData.forEach((item) => {
      if (item.name === "integrations" || item.name === "features") {
        if (!processedData[item.name]) {
          processedData[item.name] = [];
        }
        processedData[item.name].push(item.value);
      } else {
        processedData[item.name] = item.value;
      }
    });

    return processedData;
  }
});

$(document).ready(function () {
  $("#print").click(function (e) {
    console.log("#print");
    e.preventDefault();
    console.log(e);
    printContent("invoice");
  });



  function printContent(elementId) {
    let printContents = document.getElementById(elementId).innerHTML;
    let originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
  }
});
