// wp-content/plugins/multiweather/js/tide.js

// Track last angle per card so we don't spin backwards
let mwTidePrevAngles = {};

document.addEventListener('DOMContentLoaded', () => {
  if (!window.mwTideData || !Array.isArray(window.mwTideData)) {
    console.log('⛔ mwTideData missing or not an array');
    return;
  }

  window.mwTideData.forEach(card => {
    const selector = card.selector;
    const root = document.querySelector(selector);

    if (!root) {
      console.log('⛔ No card root for selector', selector);
      return;
    }

    // Safely coerce percent
    const percentRaw = card.percentBetweenTides;
    const percent = Number(percentRaw);

    if (Number.isNaN(percent)) {
      console.log('⛔ Bad percentBetweenTides for', selector, percentRaw);
      return;
    }

    const trend = card.trend || '';

    // These three are per-card selectors, relative to the root
    const dial = root.querySelector(card.dialClass);
    const tideHeightEl = root.querySelector(card.heightClass);
    const trendEl = root.querySelector(card.trendClass);

    // Base angle: Rising = 180 → 0, Falling = 180 → 360
    let baseAngle =
      trend === 'Rising'
        ? 180 - 180 * percent   // bottom → top
        : 180 + 180 * percent;  // top → bottom

    const id = selector;

    if (!(id in mwTidePrevAngles)) {
      mwTidePrevAngles[id] = baseAngle;
    }

    let prev = mwTidePrevAngles[id];
    let adjusted = baseAngle;

    // Prevent backwards jumps – add 360 until it's ahead of last
    while (adjusted < prev) {
      adjusted += 360;
    }

    mwTidePrevAngles[id] = adjusted;
    const displayAngle = adjusted % 360;

    if (dial) {
      dial.style.transform = `rotate(${displayAngle}deg)`;
      dial.style.transformOrigin = 'top center';
    }

    if (tideHeightEl && card.currentHeight !== null && card.currentHeight !== undefined) {
      tideHeightEl.textContent = `${card.currentHeight} m`;
    }

    if (trendEl && trend) {
      trendEl.textContent = trend;
    }

    console.log(
      `🌀 ${selector} trend=${trend} percent=${percent.toFixed(3)} angle=${displayAngle.toFixed(1)}`
    );
  });
});
