// web_pages.h
#pragma once
#include <Arduino.h>

// Главная страница
const char MAIN_PAGE[] PROGMEM = R"=====(
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Стабилизатор</title>
<style>
body{font-family:Arial,sans-serif;background:#121212;color:#eee;margin:0;padding:10px}
.c{max-width:800px;margin:0 auto}h1,h2{text-align:center}
.d{background:#1e1e1e;border-radius:10px;padding:15px;margin:10px 0}
.g{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.v{font-size:1.2em;color:#4CAF50}.a{color:#ff5555}.n{margin:20px 0}
.b{background:#4CAF50;border:0;padding:8px 15px;border-radius:5px;cursor:pointer;min-width:120px;color:#fff;text-decoration:none}
.b:hover{background:#45a049}
.no-data{color:#ff5555}
@media (max-width:600px){.c{max-width:100%;padding:0 10px}}
</style>
 <link rel="icon" href="https://www.samovar-tool.ru/doc/device/img/drex_tehn_custom.png" type="image/png">
<script>
let lastUpdateTime = 0;
function updateDataStatus() {
    const now = Date.now();
    const elements = document.querySelectorAll('.v');
    elements.forEach(el => {
        if (now - lastUpdateTime > 10000) {
            el.innerText = "???";
            el.classList.add('no-data');
        } else {
            el.classList.remove('no-data');
        }
    });
}
function updatePower(value) {
    document.getElementById('powerInput').value = value;
    document.getElementById('powerRange').value = value;
    fetch('/set_power', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'power=' + encodeURIComponent(value)
    });
}
function toggleBoost() {
    fetch('/set_boost', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'boost=' + (document.getElementById('boost').checked ? '1' : '0')
    });
}
function toggleHeat() {
    fetch('/set_heat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'heat=' + (document.getElementById('heat').checked ? '1' : '0')
    });
}
function toggleRegulator() {
    fetch('/set_regulator', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'regulator=' + (document.getElementById('regulator').checked ? '1' : '0')
    });
}
function updateData() {
    fetch('/get_data')
    .then(response => {
        if (!response.ok) throw new Error('Network error');
        return response.json();
    })
    .then(data => {
        lastUpdateTime = Date.now();
        document.getElementById('voltage').innerText = data.voltage.toFixed(1) + " V";
        document.getElementById('current').innerText = data.current.toFixed(2) + " A";
        document.getElementById('power').innerText = data.power + " Вт";
        document.getElementById('powerSetpoint').innerText = data.powerSetpoint + " Вт";
        document.getElementById('maxPower').innerText = data.maxPower + " Вт";
        document.getElementById('PowerLevel').innerText = data.PowerLevel + " (из " + data.MaxPowerLevel + ")";
        document.getElementById('energy').innerText = data.energy.toFixed(3) + " кВт·ч";
        document.getElementById('boost').checked = data.boostMode;
        document.getElementById('heat').checked = data.heatEnabled;
        document.getElementById('insufficientVoltage').style.display = data.insufficientVoltage ? 'block' : 'none';
        document.getElementById('powerRange').max = data.maxPower;
        document.getElementById('maxPowerValue').innerText = data.maxPower + " Вт";
        document.getElementById('regulator').checked = data.regulator;
        
        let modeText = "";
        switch(data.mode) {
            case 0: modeText = "ШИМ"; break;
            case 1: modeText = "сортировка полуволн"; break;
            case 2: modeText = "фазовое регулирование"; break;
        }
        document.getElementById('modeText').innerText = modeText;
        
        document.getElementById('stabilizeModeText').innerText = data.stabilizeMode == 0 ? "Мощность" : "Напряжение";
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}
setInterval(updateDataStatus, 1000);
setInterval(updateData, 2000);
updateData();
</script>
</head>
<body>
<div class=c>
<h1>Стабилизатор мощности</h1>
<div class=d>
<label><input type='checkbox' id='regulator' onchange='toggleRegulator()'> Регулятор: <span id="modeText"></span>, стабилизация: <span id="stabilizeModeText"></span></label>
<p>Напряжение: <span id="voltage" class=v>---</span>, Ток: <span id="current" class=v>---</span></p>
<p>Мощность: <span id="power" class=v>---</span>. Целевая: <span id="powerSetpoint" class=v>---</span></p>
<p>MAX: <span id="maxPower" class=v>---</span> 
<p>Степень открытия симистора: <span id="PowerLevel" class=v>---</span></p>
<p>Счетчик: <span id="energy" class=v>---</span></p>
<form id="powerForm" method="POST" action="/set_power">
Установка мощности (Вт):
<input type="number" id="powerInput" name="power" min="0" max="10000" onchange="updatePower(this.value)">
</form>
0 <input type="range" id="powerRange" min="0" max="10000" oninput="updatePower(this.value)" onchange="updatePower(this.value)"> <span id="maxPowerValue" class=v>---</span><br><br>
<label>Режим разгона: <input type='checkbox' id='boost' onchange='toggleBoost()'></label><br><br>
<label>Включить нагрев: <input type='checkbox' id='heat' onchange='toggleHeat()'></label><br><br>
<a href='/setup_wifi' class='b'>Настройки</a> <br>
<p id="insufficientVoltage" style="color:red; display:none;">Недостаточное напряжение.</p>
</div>
</body>
</html>
)=====";

// Страница настроек
const char SETTINGS_PAGE[] PROGMEM = R"=====(
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Настройки</title>
<style>
body{font-family:Arial,sans-serif;background:#121212;color:#eee;margin:0;padding:10px}
.c{max-width:800px;margin:0 auto}
h1,h2{text-align:center;color:#4CAF50}
.d{background:#1e1e1e;border-radius:10px;padding:15px;margin:10px 0}
.g{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.v{font-size:1.2em;color:#4CAF50}.a{color:#ff5555}.n{margin:20px 0}
.b{background:#4CAF50;border:0;padding:8px 15px;border-radius:5px;cursor:pointer;min-width:120px;color:#fff;text-decoration:none}
.b:hover{background:#45a049}
.no-data{color:#ff5555}
label{display:flex;align-items:center;gap:10px;margin-bottom:5px}
input[type="checkbox"], input[type="radio"] {width:auto;margin:0}
input:not([type="checkbox"]):not([type="radio"]), select{width:100%;padding:10px;box-sizing:border-box;background:#333;color:#eee;border:1px solid #444;border-radius:5px;font-size:16px}
.tab{overflow:hidden;border:1px solid #444;background-color:#1e1e1e;border-radius:5px 5px 0 0}
.tab button{background-color:inherit;float:left;border:none;outline:none;cursor:pointer;padding:14px 16px;transition:0.3s;color:#eee}
.tab button:hover{background-color:#333}
.tab button.active{background-color:#4CAF50}
.tabcontent{display:none;padding:15px;border:1px solid #444;border-top:none;background:#1e1e1e;border-radius:0 0 5px 5px}
.separator{border-top:1px solid #444;margin:20px 0}
@media (max-width:600px){.c{padding:0 10px}}
</style>
<script>
function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
function restartDevice() {
    if (confirm("Вы уверены, что хотите перезагрузить устройство?")) {
        fetch('/restart', { method: 'POST' });
    }
}
window.onload = function() {
    document.getElementById('WiFi').style.display = "block";
    document.getElementsByClassName('tablinks')[0].className += " active";
    var modeSelect = document.querySelector("select[name='mode']");
    if (modeSelect) {
        var currentMode = "%mode%";
        modeSelect.value = currentMode;
    }
    var stabilizeModeSelect = document.querySelector("select[name='stabilize_mode']");
    if (stabilizeModeSelect) {
        stabilizeModeSelect.value = "%stabilize_mode%";
    }
    var filterEnabledCheckbox = document.querySelector("input[name='filter_enabled']");
    if (filterEnabledCheckbox) {
        filterEnabledCheckbox.checked = %filter_enabled%;
    }
};
function toggleReconnection() {
    const reconnectionCheckbox = document.getElementById('mqtt_reconnection');
    const reconnectionValue = reconnectionCheckbox.checked ? "1" : "0";
    fetch('/set_mqtt_reconnection', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'reconnection=' + encodeURIComponent(reconnectionValue)
    });
}
</script>
</head>
<body>
<div class=c>
<h1>Настройки</h1>
<div class=d>
<div class=tab>
<button class="tablinks" onclick="openTab(event, 'WiFi')">Wi-Fi</button>
<button class="tablinks" onclick="openTab(event, 'MQTT')">MQTT</button>
<button class="tablinks" onclick="openTab(event, 'Other')">Прочие</button>
</div>

<div id="WiFi" class="tabcontent">
<form action='/save_wifi' method='POST'>
<div class=form-group>
<label>Режим:</label>
<label><input type='radio' name='mode' value='hotspot' %s1> Точка доступа</label>
<label><input type='radio' name='mode' value='router' %s2> Подключение к роутеру</label>
</div>
<div class=form-group id='wifiCredentials' style='display:%s3;'>
<label>SSID:</label><input type='text' name='ssid' value="%.ssid">
<label>Пароль:</label><input type='text' name='pass' value="%.pass">
</div>
<div class=n>
<button type='submit' class=b>Сохранить настройки Wi-Fi</button>
</div>
</form>
<button class=b onclick="window.location.href='/'">Назад</button>
</div>

<div id="MQTT" class="tabcontent">
<form action='/save_mqtt' method='POST'>
<div class=form-group>
<label>Сервер:</label><input type='text' name='mqtt_server' value="%.mqtt_server">
<label>Порт:</label><input type='number' name='mqtt_port' value="%.mqtt_port">
<label>Пользователь:</label><input type='text' name='mqtt_user' value="%.mqtt_user">
<label>Пароль:</label><input type='text' name='mqtt_password' value="%.mqtt_password">
<label>Топик мощности:</label><input type='text' name='mqtt_topic_power' value="%.mqtt_topic_power">
<label>Топик разгона:</label><input type='text' name='mqtt_topic_boost' value="%.mqtt_topic_boost">
<label>Топик нагрева:</label><input type='text' name='mqtt_topic_heat' value="%.mqtt_topic_heat">
<label>Топик статуса:</label><input type='text' name='mqtt_topic_status' value="%.mqtt_topic_status">
<label>Попытки подключения:</label><input type='number' name='mqtt_attempts' value="%.mqtt_attempts">
<label><input type='checkbox' id='mqtt_reconnection' name='mqtt_reconnection' %mqtt_reconnection_checked onchange='toggleReconnection()'> Переподключение при обрыве</label>
<label>Период публикаций (мс):</label><input type='number' name='mqtt_time_publication' value="%.mqtt_time_publication">
</div>
<div class=n>
<button type='submit' class=b>Сохранить настройки MQTT</button>
</div>
</form>
<button class=b onclick="window.location.href='/'">Назад</button>
</div>

<div id="Other" class="tabcontent">
<form action='/save_mode' method='POST'>
<div class=form-group>
<label>Мощность ТЭНа (Вт):</label><input type='number' name='PMAX' value='%.PMAX'>
</div>
<div class=form-group>
<label>Режим регулирования:</label>
<select name="mode">
<option value="0" %s0>ШИМ</option>
<option value="1" %s1>Сортировка полуволн</option>
<option value="2" %s2>Фазовое регулирование</option>
</select>
</div>
<div class=form-group>
<label>Стабилизировать:</label>
<select name="stabilize_mode">
<option value="0" %stabilize_mode_0>Мощность</option>
<option value="1" %stabilize_mode_1>Напряжение</option>
</select>
</div>
<div class=form-group>
<label>Режим ШИМ</label>
<label>Частота ШИМ (Гц):</label><input type='number' name='pwm_freq' value='%.pwm_freq'>
</div>
<div class=form-group>
<label>Режимы ФР и Сортировки</label>
<label>Период регулирования (с):</label><input type='number' name='time_reg' value='%.time_reg'>
</div>
<div class=form-group>
<label>Коэффициент воздействия (1-10):</label><input type='number' name='k_upr' value='%.k_upr'>
</div>
<div class=form-group>
<label><input type="checkbox" name="filter_enabled" value="1" %filter_enabled_checked> Фильтр значений</label>
</div>
<div class=form-group>
<label>Ф.Р., нижний предел задержки, 0-10000 (мкс):</label><input type='number' name='delay_low' value='%.delay_low'>
</div>
<div class=form-group>
<label>Ф.Р., верхний предел задержки, 0-10000 (мкс):</label><input type='number' name='delay_high' value='%.delay_high'>
</div>
<div class=form-group>
<label>Ф.Р., смещение, +-1500 (мкс):</label><input type='number' name='displace' value='%.displace'>
</div> 
<div class=form-group>
<label><input type="checkbox" name="remember" value="1"> Запомнить в EEPROM</label>
</div>
<div class=n>
<button type='submit' class=b>Применить режим</button>
</div>
</form>
<div class=separator></div>
<form action='/reset_energy' method='POST'>
<button type='submit' class=b>Сброс счетчика энергии</button>
</form>
<div class=separator></div>
<button class=b onclick="restartDevice()">Перезагрузка</button>
<div class=separator></div>
<button class=b onclick="window.location.href='/'">Назад</button>
</div>
</div>
</div>
</body>
</html>
)=====";