import { renderHealthTableHTML } from './healthTableV2.js';
import { getContent, ORDERED_SECTIONS } from './contentProvider.js';

function renderForecastHTML(data) {
    if (!data.items || data.items.length === 0) return '<div class="narr">Нет данных прогноза.</div>';

    return data.items.map(item => {
        const desc = item.text || {};
        let contentHTML = '';
        if (desc.positive) contentHTML += `<div class="program-desc" style="margin-bottom:15px;"><strong style="color:#C6FF00; display:block; margin-bottom:5px;">ПЛЮСОВОЕ ПРОЯВЛЕНИЕ:</strong>${desc.positive}</div>`;
        if (desc.negative) contentHTML += `<div class="program-desc" style="margin-bottom:15px;"><strong style="color:#ff4d4d; display:block; margin-bottom:5px;">МИНУСОВОЕ ПРОЯВЛЕНИЕ:</strong>${desc.negative}</div>`;
        if (desc.advice) contentHTML += `<div class="program-lesson" style="margin-top:15px; border-top:1px dashed rgba(80, 227, 194, 0.3); padding-top:10px;"><span style="color:#50E3C2; font-weight:bold;">СОВЕТ:</span> ${desc.advice}</div>`;
        if (!contentHTML) contentHTML = '<div class="narr">Описание для этого года отсутствует в базе.</div>';
        const headerTitle = desc.title ? desc.title.toUpperCase() : item.name.toUpperCase();

        return `
            <div class="program-box" style="border-color: #50E3C2; margin-bottom: 40px;">
                <div class="program-header" style="background: rgba(80, 227, 194, 0.1);">
                    <span class="program-badge" style="background: #50E3C2; color:#000;">${item.year}</span>
                    <span class="program-title" style="color: #50E3C2;">ЭНЕРГИЯ ГОДА: ${item.val}</span>
                </div>
                <div class="program-nums" style="color:#fff; margin-bottom:15px; font-size:1.1em; letter-spacing:1px;">${headerTitle}</div>
                ${contentHTML}
            </div>
        `;
    }).join('');
}

function renderProgramHTML(data) {
    if(data.error) return `<div class="narr">${data.error}</div>`;
    
    // Скрываем блок программы, если нет текста (из предыдущего шага)
    if (!data.text) return '';

    return `
        <div class="program-box">
            <div class="program-header">
                <span class="program-badge">ПРОГРАММА</span>
                <span class="program-title">${data.programTitle || '...'}</span>
            </div>
            <div class="program-nums">КОД: ${data.codes.join(' — ')}</div>
            <div class="program-desc">${data.text}</div>
            <div class="program-lesson" style="margin-top:10px; border-top:1px dashed rgba(212,175,55,0.3); padding-top:10px;">
                <span style="color:var(--accent); font-weight:bold;">СОВЕТ:</span> ${data.advice}
            </div>
        </div>
    `;
}

// === ОБНОВЛЕННАЯ ФУНКЦИЯ КАРТОЧЕК С ЦВЕТАМИ ===
function renderSimpleCard(card, mode) {
    const formatList = (item) => Array.isArray(item) ? item.join('<br>') : (item || 'Нет данных');
    
    let contentHTML = '';

    // 1. ПЛЮС (Лайм)
    if(card.plus) {
        contentHTML += `
        <div class="text-zone" style="margin-bottom:15px;">
            <strong style="color:#C6FF00; display:block; margin-bottom:5px; font-size: 0.9em; letter-spacing: 1px;">ПЛЮСОВОЕ ПРОЯВЛЕНИЕ:</strong>
            <div style="color:#fff; opacity:0.9; line-height: 1.5;">${formatList(card.plus)}</div>
        </div>`;
    }

    // 2. МИНУС (Красный)
    if(card.minus) {
        contentHTML += `
        <div class="text-zone" style="margin-bottom:15px;">
            <strong style="color:#ff4d4d; display:block; margin-bottom:5px; font-size: 0.9em; letter-spacing: 1px;">МИНУСОВОЕ ПРОЯВЛЕНИЕ:</strong>
            <div style="color:#fff; opacity:0.9; line-height: 1.5;">${formatList(card.minus)}</div>
        </div>`;
    }

    // 3. СОВЕТ (Бирюза) - добавляем, так как просил
    if(card.advice) {
        contentHTML += `
        <div class="text-zone" style="margin-top:15px; border-top:1px dashed rgba(80, 227, 194, 0.3); padding-top:15px;">
            <strong style="color:#50E3C2; display:block; margin-bottom:5px; font-size: 0.9em; letter-spacing: 1px;">СОВЕТ:</strong>
            <div style="color:#fff; opacity:0.9; line-height: 1.5;">${formatList(card.advice)}</div>
        </div>`;
    }

    return `
    <div class="arcana-card" style="margin-bottom:30px; background:rgba(255,255,255,0.03); padding:20px; border-radius:16px; border: 1px solid rgba(255,255,255,0.05);">
        <div class="slide-header-block" style="display:flex; align-items:center; gap:15px; margin-bottom:20px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom:15px;">
            <div class="arcana-num-box" style="color:#C6FF00; font-size:24px; font-weight:bold; min-width:40px; text-align:center;">${card.val}</div>
            <div class="h3" style="font-size:18px; font-weight:bold; color:#fff; margin:0; line-height: 1.3;">${card.name.toUpperCase()}</div>
        </div>
        ${contentHTML}
    </div>`;
}

export function updateUI(mode, nodes, meta) {
  const slider = document.getElementById('slidesContainer');
  const tabsBox = document.getElementById('tabsRow');
  if (!slider) return;

  slider.innerHTML = '';
  if(tabsBox) tabsBox.innerHTML = '';

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if(entry.isIntersecting) {
            const key = entry.target.dataset.key;
            if(tabsBox) {
                tabsBox.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
                const activeTab = tabsBox.querySelector(`.tab-item[data-key="${key}"]`);
                if(activeTab) {
                    activeTab.classList.add('active');
                    activeTab.scrollIntoView({ behavior: 'smooth', inline: 'center' });
                }
            }
        }
    });
  }, { root: slider, threshold: 0.5 });

  ORDERED_SECTIONS.forEach(secKey => {
      const content = getContent(secKey, nodes, mode);
      if(!content) return; 

      const tabTitle = (content.sectionTitle || secKey).toUpperCase();
      if(tabsBox) {
          const tDiv = document.createElement('div');
          tDiv.className = 'tab-item'; 
          tDiv.innerText = tabTitle; 
          tDiv.dataset.key = secKey;
          tDiv.onclick = () => document.getElementById(`slide-${secKey}`).scrollIntoView({behavior:'smooth'});
          tabsBox.appendChild(tDiv);
      }

      const slide = document.createElement('div');
      slide.className = 'slide-page';
      slide.id = `slide-${secKey}`;
      slide.dataset.key = secKey;
      observer.observe(slide);

      let innerHTML = `<div class="slide-inner"><div class="zone-title">— ${tabTitle} —</div>`;

      if (content.type === 'forecast') {
          innerHTML += renderForecastHTML(content);
      }
      else if (content.type === 'program') {
          innerHTML += renderProgramHTML(content);
          if (content.cards && content.cards.length > 0) {
              content.cards.forEach(c => {
                  innerHTML += renderSimpleCard(c, mode);
              });
          }
      } 
      else if (content.type === 'simple') {
          content.cards.forEach(c => {
              innerHTML += renderSimpleCard(c, mode);
          });
      }
      else if (secKey === 'health') {
          innerHTML += renderHealthTableHTML(meta.values || {}, mode);
      }

      innerHTML += `</div>`;
      slide.innerHTML = innerHTML;
      slider.appendChild(slide);
  });
}
