(function () {
  'use strict';

  const STORAGE_KEY = 'brl_calculette_irrigation_posts_v2';
  const cfg = window.BRLCalculetteIrrigation || {};

  function numberValue(el) {
    if (!el) return 0;
    const raw = String(el.value || '').replace(',', '.');
    const value = parseFloat(raw);
    return Number.isFinite(value) ? value : 0;
  }

  function round(value, digits) {
    if (!Number.isFinite(value)) return null;
    const factor = Math.pow(10, digits || 2);
    return Math.round(value * factor) / factor;
  }

  function fmt(value, digits) {
    const rounded = round(value, digits);
    return rounded === null ? '-' : rounded.toLocaleString('fr-FR', { maximumFractionDigits: digits || 2 });
  }

  function hoursToLabel(decimalHours) {
    if (!Number.isFinite(decimalHours) || decimalHours < 0) return '-';
    const totalMinutes = Math.round(decimalHours * 60);
    const h = Math.floor(totalMinutes / 60);
    const m = totalMinutes % 60;
    return h + ' h ' + String(m).padStart(2, '0') + ' min';
  }

  function uid() {
    return 'poste-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
  }

  function init(root) {
    const fields = {
      select: root.querySelector('[data-field="postSelect"]'),
      name: root.querySelector('[data-field="name"]'),
      distRow: root.querySelector('[data-field="distRow"]'),
      distBetweenRows: root.querySelector('[data-field="distBetweenRows"]'),
      rampCount: root.querySelector('[data-field="rampCount"]'),
      emitterFlow: root.querySelector('[data-field="emitterFlow"]'),
      surface: root.querySelector('[data-field="surface"]')
    };
    const conversions = {
      dose: root.querySelector('[data-convert="dose"]'),
      timeHours: root.querySelector('[data-convert="timeHours"]'),
      timeMinutes: root.querySelector('[data-convert="timeMinutes"]'),
      volume: root.querySelector('[data-convert="volume"]')
    };
    const results = {};
    root.querySelectorAll('[data-result]').forEach(el => { results[el.dataset.result] = el; });

    let posts = loadLocal();
    let selectedId = posts[0] ? posts[0].id : null;

    function setStatus(message) {
      if (results.status) results.status.textContent = message || '';
    }

    function loadLocal() {
      try {
        const data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
        return Array.isArray(data) ? data : [];
      } catch (e) {
        return [];
      }
    }

    function saveLocal() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
      if (cfg.isLoggedIn && cfg.ajaxUrl) {
        const body = new URLSearchParams({ action: 'brl_ci_save_posts', nonce: cfg.nonce || '', posts: JSON.stringify(posts) });
        fetch(cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body })
          .catch(() => {});
      }
    }

    function loadRemote() {
      if (!cfg.isLoggedIn || !cfg.ajaxUrl) return Promise.resolve();
      const body = new URLSearchParams({ action: 'brl_ci_load_posts', nonce: cfg.nonce || '' });
      return fetch(cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body })
        .then(r => r.json())
        .then(json => {
          if (json && json.success && Array.isArray(json.data.posts) && json.data.posts.length) {
            posts = json.data.posts.map(p => Object.assign({ rampCount: 1 }, p));
            localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
            selectedId = posts[0].id;
          }
        })
        .catch(() => {});
    }

    function currentPostFromFields() {
      return {
        id: selectedId || uid(),
        name: fields.name.value.trim() || 'Poste sans nom',
        distRow: numberValue(fields.distRow),
        distBetweenRows: numberValue(fields.distBetweenRows),
        rampCount: Math.max(1, Math.round(numberValue(fields.rampCount) || 1)),
        emitterFlow: numberValue(fields.emitterFlow),
        surface: numberValue(fields.surface)
      };
    }

    function applyPost(post) {
      selectedId = post ? post.id : null;
      fields.name.value = post ? post.name : '';
      fields.distRow.value = post ? post.distRow : '';
      fields.distBetweenRows.value = post ? post.distBetweenRows : '';
      fields.rampCount.value = post ? (post.rampCount || 1) : '';
      fields.emitterFlow.value = post ? post.emitterFlow : '';
      fields.surface.value = post ? post.surface : '';
      renderSelect();
      calculate();
    }

    function renderSelect() {
      fields.select.innerHTML = '';
      if (!posts.length) {
        const opt = document.createElement('option');
        opt.value = '';
        opt.textContent = 'Aucun poste sauvegardé';
        fields.select.appendChild(opt);
        return;
      }
      posts.forEach(post => {
        const opt = document.createElement('option');
        opt.value = post.id;
        opt.textContent = post.name || 'Poste sans nom';
        opt.selected = post.id === selectedId;
        fields.select.appendChild(opt);
      });
    }

    function calculate() {
      const p = currentPostFromFields();
      const mesh = (p.distRow * p.distBetweenRows) / (p.rampCount || 1);
      const rainfall = mesh > 0 ? p.emitterFlow / mesh : null;
      const stationFlow = rainfall !== null ? rainfall * p.surface / 1000 : null;

      results.mesh.textContent = fmt(mesh, 2);
      results.rainfall.textContent = fmt(rainfall, 3);
      results.stationFlow.textContent = fmt(stationFlow, 3);

      const dose = numberValue(conversions.dose);
      const volume = numberValue(conversions.volume);
      const timeDecimal = numberValue(conversions.timeHours) + (numberValue(conversions.timeMinutes) / 60);

      results.doseToTime.textContent = rainfall ? hoursToLabel(dose / rainfall) : '-';
      results.doseToVolume.textContent = p.surface ? fmt((dose / 1000) * p.surface, 2) : '-';
      results.timeToDose.textContent = rainfall ? fmt(rainfall * timeDecimal, 2) : '-';
      results.timeToVolume.textContent = stationFlow ? fmt(stationFlow * timeDecimal, 2) : '-';
      results.volumeToDose.textContent = p.surface ? fmt((volume / p.surface) * 1000, 2) : '-';
      results.volumeToTime.textContent = stationFlow ? hoursToLabel(volume / stationFlow) : '-';
    }

    root.addEventListener('input', calculate);

    fields.select.addEventListener('change', function () {
      const post = posts.find(item => item.id === this.value);
      if (post) applyPost(post);
    });

    root.querySelector('[data-action="new-post"]').addEventListener('click', function () {
      selectedId = null;
      applyPost(null);
      setStatus('Nouveau poste prêt à être renseigné.');
    });

    root.querySelector('[data-action="save-post"]').addEventListener('click', function () {
      const post = currentPostFromFields();
      const index = posts.findIndex(item => item.id === post.id);
      if (index >= 0) posts[index] = post;
      else posts.push(post);
      selectedId = post.id;
      saveLocal();
      renderSelect();
      setStatus('Poste sauvegardé.');
    });

    root.querySelector('[data-action="delete-post"]').addEventListener('click', function () {
      if (!selectedId) return;
      posts = posts.filter(item => item.id !== selectedId);
      selectedId = posts[0] ? posts[0].id : null;
      saveLocal();
      applyPost(posts[0] || null);
      setStatus('Poste supprimé.');
    });

    root.querySelectorAll('[data-tab]').forEach(btn => {
      btn.addEventListener('click', function () {
        root.querySelectorAll('[data-tab]').forEach(item => item.classList.remove('active'));
        root.querySelectorAll('[data-panel]').forEach(item => item.classList.remove('active'));
        this.classList.add('active');
        root.querySelector('[data-panel="' + this.dataset.tab + '"]').classList.add('active');
      });
    });

    loadRemote().then(function () {
      renderSelect();
      applyPost(posts[0] || null);
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('[data-brl-calculette-irrigation]').forEach(init);
  });
})();
