/* ==========================================================================
   SOLARIS LUXE - Luxury Solar Energy Interactive JavaScript Logic
   ========================================================================== */

document.addEventListener('DOMContentLoaded', function () {
  'use strict';

  // ----------------------------------------------------
  // 1. Navbar Scroll Effect & Active Links
  // ----------------------------------------------------
  const navbar = document.querySelector('.navbar-luxe');
  const backToTopBtn = document.getElementById('backToTopBtn');

  window.addEventListener('scroll', function () {
    if (window.scrollY > 50) {
      navbar?.classList.add('scrolled');
      backToTopBtn?.classList.add('show');
    } else {
      navbar?.classList.remove('scrolled');
      backToTopBtn?.classList.remove('show');
    }
  });

  backToTopBtn?.addEventListener('click', function () {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });

  // ----------------------------------------------------
  // 2. Solar ROI & Savings Calculator Engine
  // ----------------------------------------------------
  const monthlyBillInput = document.getElementById('monthlyBillInput');
  const monthlyBillVal = document.getElementById('monthlyBillVal');
  const roofAreaInput = document.getElementById('roofAreaInput');
  const roofAreaVal = document.getElementById('roofAreaVal');
  const includeBatteryToggle = document.getElementById('includeBatteryToggle');
  const propertyTypeRadios = document.querySelectorAll('input[name="propertyType"]');

  // Outputs
  const calcSystemKw = document.getElementById('calcSystemKw');
  const calcPanelsCount = document.getElementById('calcPanelsCount');
  const calcMonthlySavings = document.getElementById('calcMonthlySavings');
  const calc25YrSavings = document.getElementById('calc25YrSavings');
  const calcTaxCredit = document.getElementById('calcTaxCredit');
  const calcPaybackYrs = document.getElementById('calcPaybackYrs');
  const calcCo2Tons = document.getElementById('calcCo2Tons');
  const calcTreesPlanted = document.getElementById('calcTreesPlanted');

  function calculateSolarROI() {
    if (!monthlyBillInput || !roofAreaInput) return;

    const monthlyBill = parseFloat(monthlyBillInput.value) || 350;
    const roofArea = parseFloat(roofAreaInput.value) || 1200;
    const hasBattery = includeBatteryToggle ? includeBatteryToggle.checked : false;

    let propertyMultiplier = 1.0;
    propertyTypeRadios.forEach(radio => {
      if (radio.checked && radio.value === 'commercial') {
        propertyMultiplier = 1.35;
      }
    });

    // Update slider display text
    if (monthlyBillVal) monthlyBillVal.textContent = `$${monthlyBill.toLocaleString()}`;
    if (roofAreaVal) roofAreaVal.textContent = `${roofArea.toLocaleString()} sq ft`;

    // Calculation constants (Industry standard math)
    const avgRatePerKwh = 0.16; // $0.16/kWh avg cost
    const monthlyKwh = monthlyBill / avgRatePerKwh;
    const annualKwh = monthlyKwh * 12;

    // Recommended Kw: ~1.3 kWh generated per Watt annually in ideal solar zone
    let recommendedKw = (annualKwh / 1350) * propertyMultiplier;
    
    // Cap system size based on available roof area (~100 sq ft per 1.5 kW)
    const maxRoofKw = (roofArea / 100) * 1.5;
    if (recommendedKw > maxRoofKw) {
      recommendedKw = maxRoofKw;
    }
    
    recommendedKw = Math.max(3.5, Math.round(recommendedKw * 10) / 10);

    // Number of 400W Tier-1 Mono-PERC panels
    const panelCount = Math.ceil((recommendedKw * 1000) / 400);

    // System Gross Cost (~$2.80 per Watt base)
    let grossCost = recommendedKw * 1000 * 2.80;
    if (hasBattery) {
      grossCost += 12500; // Add 13.5kWh Smart Battery Bank
    }

    // 30% Federal Investment Tax Credit (ITC)
    const taxCredit = grossCost * 0.30;
    const netCost = grossCost - taxCredit;

    // Annual electricity savings (est. 92% offset + 3% rate escalation)
    const annualSavings = (monthlyBill * 12 * 0.92);
    const monthlySavings = Math.round(annualSavings / 12);
    
    // 25-Year Cumulative Savings (with 3% grid rate escalation)
    let cumulativeSavings = 0;
    let currentAnnualSavings = annualSavings;
    for (let yr = 1; yr <= 25; yr++) {
      cumulativeSavings += currentAnnualSavings;
      currentAnnualSavings *= 1.03; // 3% annual utility rate increase
    }
    const net25YrSavings = Math.round(cumulativeSavings - netCost);

    // Simple Payback period
    const paybackYears = (netCost / annualSavings).toFixed(1);

    // Environmental metrics
    const co2SavedTons = (recommendedKw * 1.35).toFixed(1);
    const treesEquivalent = Math.round(co2SavedTons * 42);

    // Update DOM UI elements smoothly
    if (calcSystemKw) calcSystemKw.textContent = `${recommendedKw} kW`;
    if (calcPanelsCount) calcPanelsCount.textContent = `${panelCount} Panels`;
    if (calcMonthlySavings) calcMonthlySavings.textContent = `$${monthlySavings.toLocaleString()}/mo`;
    if (calc25YrSavings) calc25YrSavings.textContent = `$${net25YrSavings.toLocaleString()}`;
    if (calcTaxCredit) calcTaxCredit.textContent = `$${Math.round(taxCredit).toLocaleString()}`;
    if (calcPaybackYrs) calcPaybackYrs.textContent = `${paybackYears} Years`;
    if (calcCo2Tons) calcCo2Tons.textContent = `${co2SavedTons} Tons`;
    if (calcTreesPlanted) calcTreesPlanted.textContent = `${treesEquivalent.toLocaleString()} Trees`;
  }

  // Add event listeners for calculator inputs
  monthlyBillInput?.addEventListener('input', calculateSolarROI);
  roofAreaInput?.addEventListener('input', calculateSolarROI);
  includeBatteryToggle?.addEventListener('change', calculateSolarROI);
  propertyTypeRadios.forEach(radio => radio.addEventListener('change', calculateSolarROI));

  // Run initial calculation
  calculateSolarROI();

  // ----------------------------------------------------
  // 3. Project Portfolio Filter System
  // ----------------------------------------------------
  const filterBtns = document.querySelectorAll('.portfolio-filter-btn');
  const projectItems = document.querySelectorAll('.project-item');

  filterBtns.forEach(btn => {
    btn.addEventListener('click', function () {
      filterBtns.forEach(b => b.classList.remove('active'));
      this.classList.add('active');

      const filterValue = this.getAttribute('data-filter');

      projectItems.forEach(item => {
        if (filterValue === 'all' || item.classList.contains(filterValue)) {
          item.style.display = 'block';
          setTimeout(() => {
            item.style.opacity = '1';
            item.style.transform = 'scale(1)';
          }, 50);
        } else {
          item.style.opacity = '0';
          item.style.transform = 'scale(0.9)';
          setTimeout(() => {
            item.style.display = 'none';
          }, 300);
        }
      });
    });
  });

  // ----------------------------------------------------
  // 4. Animated Number Counters
  // ----------------------------------------------------
  const counterElements = document.querySelectorAll('.counter-value');
  let countersAnimated = false;

  function animateCounters() {
    if (countersAnimated) return;

    counterElements.forEach(counter => {
      const rect = counter.getBoundingClientRect();
      if (rect.top < window.innerHeight && rect.bottom >= 0) {
        countersAnimated = true;
        const target = parseFloat(counter.getAttribute('data-target'));
        const prefix = counter.getAttribute('data-prefix') || '';
        const suffix = counter.getAttribute('data-suffix') || '';
        const duration = 2000;
        const startTime = performance.now();

        function updateNumber(currentTime) {
          const elapsedTime = currentTime - startTime;
          const progress = Math.min(elapsedTime / duration, 1);
          // Ease-out quad
          const easeProgress = 1 - (1 - progress) * (1 - progress);
          const currentValue = Math.floor(easeProgress * target);

          counter.textContent = prefix + currentValue.toLocaleString() + suffix;

          if (progress < 1) {
            requestAnimationFrame(updateNumber);
          } else {
            counter.textContent = prefix + target.toLocaleString() + suffix;
          }
        }

        requestAnimationFrame(updateNumber);
      }
    });
  }

  window.addEventListener('scroll', animateCounters);
  animateCounters(); // Initial check

  // ----------------------------------------------------
  // 5. Government Incentive State Selector
  // ----------------------------------------------------
  const stateSelector = document.getElementById('stateSelector');
  const stateBonusBadge = document.getElementById('stateBonusBadge');
  const stateDescText = document.getElementById('stateDescText');

  const stateIncentives = {
    federal: { badge: '30% Federal ITC Tax Credit', desc: 'Direct 30% credit on total solar & storage installation cost against federal taxes.' },
    california: { badge: '30% Federal + SGIP Storage Rebate', desc: 'Up to $1,000/kWh rebate for battery storage systems under Self-Generation Incentive Program (SGIP).' },
    texas: { badge: '30% Federal + Property Tax Exemption', desc: '100% property tax exemption on value added by solar equipment + local utility rebate up to $2,500.' },
    florida: { badge: '30% Federal + 0% Sales Tax', desc: '100% sales tax exemption on solar systems + 100% property tax abatement.' },
    newyork: { badge: '30% Fed + $5,000 NY State Credit', desc: '25% NY State tax credit (up to $5,000) + Megawatt Block Solar Rebates.' }
  };

  stateSelector?.addEventListener('change', function () {
    const selected = stateIncentives[this.value] || stateIncentives.federal;
    if (stateBonusBadge) stateBonusBadge.textContent = selected.badge;
    if (stateDescText) stateDescText.textContent = selected.desc;
  });

  // ----------------------------------------------------
  // 6. Contact Form Interactive Submit Simulation
  // ----------------------------------------------------
  const consultationForm = document.getElementById('consultationForm');
  const formSuccessAlert = document.getElementById('formSuccessAlert');

  consultationForm?.addEventListener('submit', function (e) {
    e.preventDefault();
    const submitBtn = consultationForm.querySelector('button[type="submit"]');
    
    if (submitBtn) {
      submitBtn.disabled = true;
      submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status"></span> Processing Audit Request...';
    }

    setTimeout(() => {
      if (submitBtn) {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i> Audit Request Submitted!';
        submitBtn.classList.remove('btn-solar-gold');
        submitBtn.classList.add('btn-solar-emerald');
      }

      if (formSuccessAlert) {
        formSuccessAlert.classList.remove('d-none');
      }

      consultationForm.reset();
    }, 1500);
  });
});
