import { ValidationHelpers, HelpTooltip, __, sprintf, _n } from '@vareoncalc/calculator-base';
import { initCompactTwoStep } from '../utils/compact-two-step.js';

/**
 * Age Calculator - "Life Dashboard" Layout
 * Two-panel studio design: Timeline (left) -> Life Stats (right)
 * Precision mode: includes time of birth for accurate hour calculations
 */

export function mount(container) {
  // Get today's date and time for defaults
  const today = new Date();
  const todayStr = today.toISOString().split('T')[0];
  const nowTimeStr = today.toTimeString().slice(0, 5); // HH:MM format

  // Get end of year date
  const endOfYear = new Date(today.getFullYear(), 11, 31);
  const endOfYearStr = endOfYear.toISOString().split('T')[0];

  // Build the Life Dashboard in compact two-step layout
  container.innerHTML = `
    <div class="vareoncalc-two-step" data-two-step data-two-step-mode="blind">
      <div class="vareoncalc-two-step__step vareoncalc-two-step__step--inputs" data-two-step-step="inputs">
        <div class="vareoncalc-two-step__inputs-body">
          <div class="vareoncalc-panel-input vareoncalc-age-timeline">

            <div class="vareoncalc-section age-section age-section--birth">
              <div class="vareoncalc-section__header">
                <div class="vareoncalc-section__title">${__('Birth Details', 'vareon-calculator-suite-lite')}</div>
              </div>
              <!-- Row 1: Birth Date + Time -->
              <div class="vareoncalc-field-row age-date-row">
                <div class="vareoncalc-field">
                  <label for="birth-date">${__('Date of Birth', 'vareon-calculator-suite-lite')}</label>
                  <input type="date" id="birth-date" max="${todayStr}">
                </div>
                <div class="vareoncalc-field vareoncalc-field--time">
                  <label for="birth-time">${__('Time of Birth', 'vareon-calculator-suite-lite')}</label>
                  <input type="time" id="birth-time" placeholder="12:00">
                </div>
              </div>
            </div>

            <div class="age-target-group">
              <div class="vareoncalc-section age-section age-section--target">
                <div class="vareoncalc-section__header">
                  <div class="vareoncalc-section__title">${__('Target Date', 'vareon-calculator-suite-lite')}</div>
                </div>
                <!-- Row 2: As Of Date + Time -->
                <div class="vareoncalc-field-row age-date-row">
                  <div class="vareoncalc-field">
                    <label for="as-of-date">${__('Target Date', 'vareon-calculator-suite-lite')}</label>
                    <input type="date" id="as-of-date" value="${todayStr}">
                  </div>
                  <div class="vareoncalc-field vareoncalc-field--time">
                    <label for="as-of-time">${__('Time', 'vareon-calculator-suite-lite')} <span class="age-optional">(${__('optional', 'vareon-calculator-suite-lite')})</span></label>
                    <input type="time" id="as-of-time" value="${nowTimeStr}">
                  </div>
                </div>
              </div>

              <div class="vareoncalc-section age-section age-section--presets">
                <div class="vareoncalc-section__header">
                  <div class="vareoncalc-section__title">${__('Quick Presets', 'vareon-calculator-suite-lite')}</div>
                </div>
                <div class="age-presets">
                  <label class="age-presets-label">${__('Quick Presets', 'vareon-calculator-suite-lite')}</label>
                  <div class="age-presets-grid">
                    <button type="button" class="age-preset-btn" data-preset="today">${__('Today', 'vareon-calculator-suite-lite')}</button>
                    <button type="button" class="age-preset-btn" data-preset="end-of-year">${__('End of Year', 'vareon-calculator-suite-lite')}</button>
                    <button type="button" class="age-preset-btn" data-preset="next-birthday">${__('Next Birthday', 'vareon-calculator-suite-lite')}</button>
                  </div>
                </div>
              </div>
            </div>
            
            <button type="button" class="vareoncalc-btn" id="calc-btn" data-two-step-next>${__('Calculate Age', 'vareon-calculator-suite-lite')}</button>
          </div>
        </div>
      </div>
      
      <div class="vareoncalc-two-step__step vareoncalc-two-step__step--results" data-two-step-step="results" aria-hidden="true">
        <div class="vareoncalc-two-step__results">
          <div class="vareoncalc-panel-result vareoncalc-age-lifestats vareoncalc-age-lifestats--placeholder" id="result-panel">
            <div class="placeholder-icon">&#127874;</div>
            <div class="placeholder-text">${__('Enter your birth date to see your life dashboard', 'vareon-calculator-suite-lite')}</div>
          </div>
        </div>
      </div>
    </div>
  `;
  HelpTooltip.apply(container);

  const btn = container.querySelector('#calc-btn');
  const resultPanel = container.querySelector('#result-panel');
  const birthDateInput = container.querySelector('#birth-date');
  const birthTimeInput = container.querySelector('#birth-time');
  const asOfDateInput = container.querySelector('#as-of-date');
  const asOfTimeInput = container.querySelector('#as-of-time');
  const presetBtns = container.querySelectorAll('.age-preset-btn');
  let twoStepInstance = null;
  const forEachTwoStepInstance = (handler) => {
    if (!twoStepInstance) {
      return;
    }
    if (Array.isArray(twoStepInstance)) {
      twoStepInstance.forEach(instance => {
        if (instance) {
          handler(instance);
        }
      });
      return;
    }
    handler(twoStepInstance);
  };
  const showResultsStep = () => {
    forEachTwoStepInstance((instance) => {
      if (typeof instance.setStep === 'function') {
        instance.setStep('results');
      }
      if (typeof instance.setDrawerOpen === 'function') {
        instance.setDrawerOpen(false);
      }
      if (typeof instance.refreshLayout === 'function') {
        instance.refreshLayout();
      }
    });
  };
  const refreshTwoStepLayout = () => {
    forEachTwoStepInstance((instance) => {
      if (typeof instance.refreshLayout === 'function') {
        instance.refreshLayout();
      }
    });
  };
  const canProceed = () => {
    const birthDateStr = birthDateInput.value;
    const asOfDateStr = asOfDateInput.value;
    if (!birthDateStr || !asOfDateStr) {
      return false;
    }
    const birthTimeStr = birthTimeInput.value || '00:00';
    const asOfTimeStr = asOfTimeInput.value || '00:00';
    const [birthHours, birthMinutes] = birthTimeStr.split(':').map(Number);
    const [asOfHours, asOfMinutes] = asOfTimeStr.split(':').map(Number);
    const birthDate = new Date(birthDateStr);
    const asOfDate = new Date(asOfDateStr);
    if (Number.isNaN(birthDate.getTime()) || Number.isNaN(asOfDate.getTime())) {
      return false;
    }
    return true;
  };
  // Handle preset buttons
  presetBtns.forEach(presetBtn => {
    presetBtn.addEventListener('click', () => {
      const preset = presetBtn.dataset.preset;
      const birthDateVal = birthDateInput.value;

      if (preset === 'today') {
        asOfDateInput.value = todayStr;
        asOfTimeInput.value = nowTimeStr;
      } else if (preset === 'end-of-year') {
        asOfDateInput.value = endOfYearStr;
        asOfTimeInput.value = '23:59';
      } else if (preset === 'next-birthday' && birthDateVal) {
        const birthDate = new Date(birthDateVal);
        const nextBday = new Date(today.getFullYear(), birthDate.getMonth(), birthDate.getDate());
        if (nextBday <= today) {
          nextBday.setFullYear(nextBday.getFullYear() + 1);
        }
        asOfDateInput.value = nextBday.toISOString().split('T')[0];
        // Keep the birth time for next birthday preset if available
        if (birthTimeInput.value) {
          asOfTimeInput.value = birthTimeInput.value;
        }
      }
    });
  });

  // Render Life Stats panel
  const STAT_ICON_CALENDAR = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
  const STAT_ICON_GRID = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg>';
  const STAT_ICON_DAY = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><path d="m9 16 2 2 4-4"/></svg>';
  const STAT_ICON_CLOCK = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';

  function renderLifeStats(data) {
    resultPanel.className = 'vareoncalc-panel-result vareoncalc-age-lifestats';

    const ringRadius = 50;
    const ringCircumference = 2 * Math.PI * ringRadius;
    const progressRatio = Math.max(0, Math.min(1, data.yearProgressPercent / 100));
    const targetOffset = ((1 - progressRatio) * ringCircumference).toFixed(2);

    resultPanel.innerHTML = `
      <div class="lifestats-headline">
        <div class="lifestats-years" data-countup="${data.years}">${data.years}</div>
        <div class="lifestats-years-label">${__('Years', 'vareon-calculator-suite-lite')}</div>

        <div class="lifestats-ring-wrap">
          <div class="lifestats-ring">
            <svg viewBox="0 0 120 120" aria-hidden="true" focusable="false">
              <circle class="lifestats-ring__track" cx="60" cy="60" r="${ringRadius}"></circle>
              <circle
                class="lifestats-ring__progress"
                cx="60" cy="60" r="${ringRadius}"
                stroke-dasharray="${ringCircumference.toFixed(2)}"
                stroke-dashoffset="${ringCircumference.toFixed(2)}"
                data-target-offset="${targetOffset}"
              ></circle>
            </svg>
            <div class="lifestats-ring__center">
              <span class="lifestats-ring__line"><span class="subage-value" data-countup="${data.months}">${data.months}</span> ${_n('month', 'months', data.months, 'vareon-calculator-suite-lite')}</span>
              <span class="lifestats-ring__line"><span class="subage-value" data-countup="${data.days}">${data.days}</span> ${_n('day', 'days', data.days, 'vareon-calculator-suite-lite')}</span>
            </div>
          </div>
        </div>

        <div class="lifestats-since">${__('Since Birth:', 'vareon-calculator-suite-lite')} <strong>${data.birthYear}</strong></div>
      </div>

      <div class="lifestats-grid">
        <div class="lifestats-stat">
          <div class="stat-icon-wrap">${STAT_ICON_CALENDAR}</div>
          <div class="stat-value" data-countup="${data.totalMonths}" data-format="locale">${data.totalMonths.toLocaleString()}</div>
          <div class="stat-label">${__('Total Months', 'vareon-calculator-suite-lite')}</div>
        </div>
        <div class="lifestats-stat">
          <div class="stat-icon-wrap">${STAT_ICON_GRID}</div>
          <div class="stat-value" data-countup="${data.totalWeeks}" data-format="locale">${data.totalWeeks.toLocaleString()}</div>
          <div class="stat-label">${__('Total Weeks', 'vareon-calculator-suite-lite')}</div>
        </div>
        <div class="lifestats-stat">
          <div class="stat-icon-wrap">${STAT_ICON_DAY}</div>
          <div class="stat-value" data-countup="${data.totalDays}" data-format="locale">${data.totalDays.toLocaleString()}</div>
          <div class="stat-label">${__('Total Days', 'vareon-calculator-suite-lite')}</div>
        </div>
        <div class="lifestats-stat">
          <div class="stat-icon-wrap">${STAT_ICON_CLOCK}</div>
          <div class="stat-value" data-countup="${data.totalHours}" data-format="locale">${data.totalHours.toLocaleString()}</div>
          <div class="stat-label">${__('Total Hours', 'vareon-calculator-suite-lite')}</div>
        </div>
      </div>

      ${data.milestoneHtml}

      ${data.nextBirthdayHtml}

      <div class="age-back-wrap">
        <button type="button" class="age-back-handle" id="age-change-dates-btn">
          <span>${__('Change dates', 'vareon-calculator-suite-lite')}</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m18 15-6-6-6 6"/></svg>
        </button>
      </div>
    `;

    const changeDatesBtn = resultPanel.querySelector('#age-change-dates-btn');
    if (changeDatesBtn) {
      changeDatesBtn.addEventListener('click', () => {
        forEachTwoStepInstance((instance) => {
          if (typeof instance.setStep === 'function') {
            instance.setStep('inputs');
          }
        });
      });
    }

    setTimeout(() => {
      runAnimations(resultPanel);
      HelpTooltip.apply(resultPanel);
    }, 50);
  }

  function runAnimations(panel) {
    const fills = panel.querySelectorAll('.milestone-progress-fill');
    fills.forEach(fill => {
      if (fill.dataset.targetWidth) {
        fill.style.width = fill.dataset.targetWidth;
      }
    });

    const ringProgress = panel.querySelector('.lifestats-ring__progress');
    if (ringProgress) {
      const target = ringProgress.getAttribute('data-target-offset');
      requestAnimationFrame(() => {
        ringProgress.style.strokeDashoffset = target || '0';
      });
    }

    const counters = panel.querySelectorAll('[data-countup]');
    const duration = 1200;

    counters.forEach(counter => {
      const target = parseFloat(counter.dataset.countup);
      if (isNaN(target) || target === 0) return;

      const formatLocale = counter.dataset.format === 'locale';
      const start = 0;
      const startTime = performance.now();

      const updateCount = (currentTime) => {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        const easeOut = 1 - Math.pow(1 - progress, 4);
        const current = start + (target - start) * easeOut;

        counter.textContent = formatLocale ? Math.floor(current).toLocaleString() : Math.floor(current);

        if (progress < 1) {
          requestAnimationFrame(updateCount);
        } else {
          counter.textContent = formatLocale ? target.toLocaleString() : target;
        }
      };

      requestAnimationFrame(updateCount);
    });
  }

  function calculate(event = null) {
    ValidationHelpers.clearAllErrors(container);
    const invalidInputs = [];
    const messages = [];
    const recordInvalid = (input, message, options = {}) => {
      if (!input) {
        return;
      }
      ValidationHelpers.markInvalid(input, options);
      invalidInputs.push(input);
      if (message) {
        messages.push(message);
      }
    };

    const birthDateStr = birthDateInput.value;
    const birthTimeStr = birthTimeInput.value || '00:00';
    const asOfDateStr = asOfDateInput.value;
    const asOfTimeStr = asOfTimeInput.value || '00:00';

    if (!birthDateStr || !asOfDateStr) {
      if (!birthDateStr) {
        recordInvalid(birthDateInput, __('Please select both dates.', 'vareon-calculator-suite-lite'));
      }
      if (!asOfDateStr) {
        recordInvalid(asOfDateInput, null);
      }
    }

    if (invalidInputs.length > 0) {
      const message = messages.length === 1
        ? messages[0]
        : __('Please fix the highlighted fields.', 'vareon-calculator-suite-lite');
      ValidationHelpers.showToast(container, message);
      if (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
      return;
    }

    // Parse birth time
    const [birthHours, birthMinutes] = birthTimeStr.split(':').map(Number);
    const birthDate = new Date(birthDateStr);
    birthDate.setHours(birthHours, birthMinutes, 0, 0);

    // Parse as-of time
    const [asOfHours, asOfMinutes] = asOfTimeStr.split(':').map(Number);
    const asOfDate = new Date(asOfDateStr);
    asOfDate.setHours(asOfHours, asOfMinutes, 0, 0);

    if (birthDate > asOfDate) {
      const validator = () => {
        const birthRaw = birthDateInput.value;
        const asOfRaw = asOfDateInput.value;
        if (!birthRaw || !asOfRaw) {
          return false;
        }
        const [bHours, bMinutes] = (birthTimeInput.value || '00:00').split(':').map(Number);
        const [aHours, aMinutes] = (asOfTimeInput.value || '00:00').split(':').map(Number);
        const birth = new Date(birthRaw);
        const asOf = new Date(asOfRaw);
        birth.setHours(bHours, bMinutes, 0, 0);
        asOf.setHours(aHours, aMinutes, 0, 0);
        return birth <= asOf;
      };
      ValidationHelpers.markInvalid(birthDateInput, { validator });
      ValidationHelpers.markInvalid(asOfDateInput, { validator });
      ValidationHelpers.showToast(container, __('Birth date cannot be after the "as of" date.', 'vareon-calculator-suite-lite'));
      if (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
      return;
    }

    // Calculate age (date-based for years/months/days)
    let years = asOfDate.getFullYear() - birthDate.getFullYear();
    let months = asOfDate.getMonth() - birthDate.getMonth();
    let days = asOfDate.getDate() - birthDate.getDate();

    // Adjust for time-of-day (if as-of time is before birth time on same day of month)
    const asOfDayMinutes = asOfHours * 60 + asOfMinutes;
    const birthDayMinutes = birthHours * 60 + birthMinutes;
    if (asOfDayMinutes < birthDayMinutes && days <= 0) {
      days--;
    }

    // Fix: handle negative days by borrowing from previous month
    if (days < 0) {
      months--;
      const prevMonthLastDay = new Date(asOfDate.getFullYear(), asOfDate.getMonth(), 0).getDate();
      days += prevMonthLastDay;
    }

    // Fix: handle negative months by borrowing from year
    if (months < 0) {
      years--;
      months += 12;
    }

    // Safety: check if birth date is in the future
    if (years < 0) {
      const validator = () => {
        const birthRaw = birthDateInput.value;
        const asOfRaw = asOfDateInput.value;
        if (!birthRaw || !asOfRaw) {
          return false;
        }
        const [bHours, bMinutes] = (birthTimeInput.value || '00:00').split(':').map(Number);
        const [aHours, aMinutes] = (asOfTimeInput.value || '00:00').split(':').map(Number);
        const birth = new Date(birthRaw);
        const asOf = new Date(asOfRaw);
        birth.setHours(bHours, bMinutes, 0, 0);
        asOf.setHours(aHours, aMinutes, 0, 0);
        return birth <= asOf;
      };
      ValidationHelpers.markInvalid(birthDateInput, { validator });
      ValidationHelpers.showToast(container, __('Birth date cannot be in the future.', 'vareon-calculator-suite-lite'));
      return;
    }

    // Calculate precise totals using milliseconds
    const diffTime = Math.abs(asOfDate - birthDate);
    const totalDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    const totalWeeks = Math.floor(totalDays / 7);
    const totalMonths = years * 12 + months;

    // Precise hours calculation (includes partial day from time inputs)
    const totalHours = Math.floor(diffTime / (1000 * 60 * 60));
    const totalMinutes = Math.floor(diffTime / (1000 * 60));

    // Calculate total days alive for the milestone
    const daysAlive = totalDays;
    const milestoneStep = 1000;
    const nextMilestoneVal = Math.ceil((daysAlive + 1) / milestoneStep) * milestoneStep;
    const daysToMilestone = nextMilestoneVal - daysAlive;
    const milestoneDate = new Date(asOfDate);
    milestoneDate.setDate(asOfDate.getDate() + daysToMilestone);

    // Calculate next birthday
    const nextBirthday = new Date(asOfDate.getFullYear(), birthDate.getMonth(), birthDate.getDate());
    nextBirthday.setHours(birthHours, birthMinutes, 0, 0);
    if (nextBirthday <= asOfDate) {
      nextBirthday.setFullYear(nextBirthday.getFullYear() + 1);
    }
    const daysToNextBirthday = Math.floor((nextBirthday - asOfDate) / (1000 * 60 * 60 * 24));
    const nextBirthdayDayName = nextBirthday.toLocaleDateString('default', { weekday: 'long' });

    // Calculate progress for next age
    const lastBirthday = new Date(nextBirthday);
    lastBirthday.setFullYear(lastBirthday.getFullYear() - 1);
    const totalDaysBetweenBirthdays = Math.floor((nextBirthday - lastBirthday) / (1000 * 60 * 60 * 24));
    let yearProgressPercent = 0;
    if (totalDaysBetweenBirthdays > 0) {
      yearProgressPercent = Math.max(0, Math.min(100, ((totalDaysBetweenBirthdays - daysToNextBirthday) / totalDaysBetweenBirthdays) * 100));
    }

    // Calculate progress for 1000th day milestone
    const prevMilestoneVal = nextMilestoneVal - milestoneStep;
    const daysSincePrevMilestone = daysAlive - prevMilestoneVal;
    let milestoneProgressPercent = 0;
    if (milestoneStep > 0) {
      milestoneProgressPercent = Math.max(0, Math.min(100, (daysSincePrevMilestone / milestoneStep) * 100));
    }

    const milestoneHtml = `
      <div class="age-milestone-card">
        <div class="age-milestone-header">
          <span class="age-milestone-title">${sprintf(__('Next %s Day:', 'vareon-calculator-suite-lite'), nextMilestoneVal.toLocaleString())}</span>
        </div>
        <div class="age-milestone-content">
          ${__('You turn', 'vareon-calculator-suite-lite')} <strong class="milestone-highlight">${nextMilestoneVal.toLocaleString()}</strong> ${__('days old on', 'vareon-calculator-suite-lite')}
          <span class="age-milestone-date">${milestoneDate.toLocaleDateString()}</span>
        </div>
        <div class="age-milestone-bar-wrap">
          <div class="milestone-progress-container">
            <div class="milestone-progress-track">
              <div class="milestone-progress-fill" style="width: 0%" data-target-width="${milestoneProgressPercent}%"></div>
            </div>
          </div>
          <span class="age-milestone-trophy">&#127942;</span>
        </div>
      </div>
    `;

    let nextBirthdayHtml = '';
    if (daysToNextBirthday === 0) {
      nextBirthdayHtml = `
        <div class="lifestats-celebration lifestats-celebration--today">
          <span class="celebration-icon">&#127881;</span>
          <div class="celebration-text">${__('Happy Birthday! Today is your special day!', 'vareon-calculator-suite-lite')}</div>
        </div>
      `;
    } else {
      nextBirthdayHtml = `
        <div class="lifestats-celebration">
          <span class="celebration-icon">&#127874;</span>
          <div class="celebration-text">
            <div class="age-next-bday-label">${__('Your next birthday is in', 'vareon-calculator-suite-lite')}</div>
            <div class="age-next-bday-count"><span class="age-next-bday-number" data-countup="${daysToNextBirthday}">${daysToNextBirthday}</span> <span class="age-next-bday-unit">${__('Days', 'vareon-calculator-suite-lite')}</span></div>
            <div class="age-next-bday-dayname">${nextBirthdayDayName}</div>
          </div>
        </div>
      `;
    }

    // Render the Life Stats panel
    renderLifeStats({
      years,
      months,
      days,
      totalMonths,
      totalWeeks,
      totalDays,
      totalHours,
      milestoneHtml,
      nextBirthdayHtml,
      yearProgressPercent,
      birthYear: birthDate.getFullYear()
    });
    showResultsStep();
    refreshTwoStepLayout();
  }

  btn.addEventListener('click', (event) => calculate(event));

  twoStepInstance = initCompactTwoStep(container, { canProceed });
  if (twoStepInstance && typeof twoStepInstance.refreshLayout === 'function') {
    twoStepInstance.refreshLayout();
  }
}

