
function updateKA1Content() {
    const content = document.getElementById('hypstart-content');
    if (!content) return;
    sessionStorage.setItem('REV_FLOW_TYPE', 'KA');

    const d = syncKA1DataFromPage();
    const dataHash = JSON.stringify(d);

    const activeEl = document.activeElement;
    if (content.contains(activeEl) && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'SELECT')) {
        return;
    }

    if (content.dataset.lastHtml === 'ka1' && !window.FORCE_REFRESH_KA1 && content.dataset.lastDataHash === dataHash) {
        return;
    }

    window.FORCE_REFRESH_KA1 = false;
    content.dataset.lastDataHash = dataHash;

    try {
        content.innerHTML = `
            <div class="ka-theme prominence-container" style="padding: 15px; background: #f8fafc; height: 100%; display: flex; flex-direction: column;">
                <div class="dt-header" style="margin-bottom: 15px; padding: 20px; background: white; border-bottom: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.03);">
                    <div class="dt-page-id">KRONER ARTER HASTALIÄI Ä°ZLEMÄ°</div>
                    <h2 style="margin:0; font-size: 18px;"><i class="fa fa-heartbeat" style="color: #be123c; margin-right: 8px;"></i>ANAMNEZ & Ä°ZLEM</h2>
                </div>

                <div style="flex: 1; overflow-y: auto;">
                    <div style="background: #ffffff; border: 1px solid rgba(190, 18, 60, 0.15); border-radius: 16px; padding: 15px; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(190, 18, 60, 0.05);">
                        <div style="font-size: 11px; font-weight: 800; color: #881337; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
                            <i class="fa fa-stethoscope"></i>FÄ°ZÄ°K MUAYENE
                        </div>
                        <!-- Vital Signs -->
                        <div style="background: #fff1f2; border: 1.5px solid #ffe4e6; border-radius: 20px; display: flex; align-items: center; padding: 4px;">
                            <div style="flex: 1; padding: 10px; border-right: 1.5px solid #ffe4e6; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #be123c; opacity: 0.7; text-transform: uppercase;">SÄ°STOLÄ°K</div>
                                <input type="number" id="ka-sys" value="${d.sistolik}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:18px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                            <div style="flex: 1; padding: 10px; border-right: 1.5px solid #ffe4e6; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #be123c; opacity: 0.7; text-transform: uppercase;">DÄ°YASTOLÄ°K</div>
                                <input type="number" id="ka-dia" value="${d.diyastolik}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:18px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                            <div style="flex: 1; padding: 10px; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #be123c; opacity: 0.7; text-transform: uppercase;">NABIZ</div>
                                <input type="number" id="ka-nab" value="${d.nabiz}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:18px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                        </div>

                        <!-- Physical -->
                        <div style="margin-top: 15px; background: #ffffff; border: 1.5px solid #edf2f7; border-radius: 20px; display: flex; align-items: center; padding: 4px;">
                            <div style="flex: 1; padding: 10px; border-right: 1.5px solid #f1f5f9; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #94a3b8; text-transform: uppercase;">BOY (cm)</div>
                                <input type="number" id="ka-boy" value="${d.boy}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:15px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                            <div style="flex: 1; padding: 10px; border-right: 1.5px solid #f1f5f9; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #94a3b8; text-transform: uppercase;">KÄ°LO (kg)</div>
                                <input type="number" id="ka-kilo" value="${d.kilo}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:15px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                            <div style="flex: 1; padding: 10px; text-align: center;">
                                <div style="font-size: 7px; font-weight: 800; color: #94a3b8; text-transform: uppercase;">BEL (cm)</div>
                                <input type="number" id="ka-bel" value="${d.bel}" style="width: 100%; border:none; text-align:center; font-weight:900; font-size:15px; color:#1e293b; background:transparent; outline:none;">
                            </div>
                        </div>

                        <!-- BMI -->
                        <div style="margin-top: 20px; padding: 18px; background: #ffffff; border-radius: 20px; border: 1px solid #edf2f7; box-shadow: 0 10px 30px rgba(0,0,0,0.04);">
                            <div style="display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 12px;">
                                <div>
                                    <div style="font-size: 8px; font-weight: 800; color: #94a3b8; letter-spacing: 1px; text-transform: uppercase; margin-bottom: 4px;">VÃœCUT KÄ°TLE Ä°NDEKSÄ°</div>
                                    <div id="ka-bmi-label" style="font-size: 13px; font-weight: 800; color: #f59e0b;">--</div>
                                </div>
                                <div style="text-align: right;">
                                    <span id="ka-bmi-val" style="font-size: 26px; font-weight: 900; color: #1e293b; line-height: 1;">--</span>
                                    <span style="font-size: 10px; font-weight: 700; color: #94a3b8; margin-left: 2px;">kg/mÂ²</span>
                                </div>
                            </div>
                            <div style="height: 10px; background: #f1f5f9; border-radius: 10px; position: relative; display: flex; gap: 2px; padding: 2px;">
                                <div style="flex: 18.5; background: #3b82f6; border-radius: 6px 0 0 6px; opacity: 0.15;" id="ka-bmi-seg-1"></div>
                                <div style="flex: 6.5; background: #10b981; opacity: 0.15;" id="ka-bmi-seg-2"></div>
                                <div style="flex: 5; background: #f59e0b; opacity: 0.15;" id="ka-bmi-seg-3"></div>
                                <div style="flex: 10; background: #ef4444; border-radius: 0 6px 6px 0; opacity: 0.15;" id="ka-bmi-seg-4"></div>
                                <div id="ka-bmi-dot" style="position: absolute; top: -3px; left: calc(0% - 8px); width: 16px; height: 16px; background: #fff; border: 3px solid #f59e0b; border-radius: 50%; box-shadow: 0 4px 10px rgba(245,158,11,0.4); transition: all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1); z-index: 2;"></div>
                            </div>
                            <div id="ka-bmi-advice" style="margin-top: 12px; font-size: 10px; font-weight: 700; color: #64748b; text-align: center;"></div>
                        </div>
                    </div>

                    <div style="background: #ffffff; border: 1px solid rgba(190, 18, 60, 0.15); border-radius: 16px; padding: 15px; margin-bottom: 15px; box-shadow: 0 4px 15px rgba(190, 18, 60, 0.05);">
                        <div style="font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
                            <i class="fa fa-walking"></i>YAÅAM TARZI
                        </div>
                        <div class="p-field-group" style="margin-bottom: 18px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                <div style="font-size: 8px; font-weight: 800; color: #64748b; text-transform: uppercase;"><i class="fa fa-smoking" style="color:#ef4444; margin-right:4px;"></i>TÃœTÃœN KULLANIMI</div>
                            </div>
                            <select id="ka-sigara" style="width: 100%; padding: 12px; border-radius: 12px; border: 2px solid #f1f5f9; background: #f8fafc; font-size: 12px; font-weight: 800; outline: none;">
                                <option value="SeÃ§iniz" ${d.sigara === 'SeÃ§iniz' ? 'selected' : ''}>SeÃ§iniz</option>
                                <option value="HiÃ§ kullanmamÄ±ÅŸ" ${d.sigara === 'HiÃ§ kullanmamÄ±ÅŸ' ? 'selected' : ''}>HiÃ§ kullanmamÄ±ÅŸ</option>
                                <option value="Her gÃ¼n dÃ¼zenli iÃ§iyor" ${d.sigara === 'Her gÃ¼n dÃ¼zenli iÃ§iyor' ? 'selected' : ''}>Her gÃ¼n dÃ¼zenli iÃ§iyor</option>
                                <option value="Ara sÄ±ra iÃ§iyor" ${d.sigara === 'Ara sÄ±ra iÃ§iyor' ? 'selected' : ''}>Ara sÄ±ra iÃ§iyor</option>
                                <option value="Eski kullanÄ±cÄ± / bÄ±raktÄ±" ${d.sigara === 'Eski kullanÄ±cÄ± / bÄ±raktÄ±' ? 'selected' : ''}>Eski kullanÄ±cÄ± / bÄ±raktÄ±</option>
                            </select>
                        </div>
                        <div class="p-field-group">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                <div style="font-size: 8px; font-weight: 800; color: #64748b; text-transform: uppercase;"><i class="fa fa-running" style="color:#10b981; margin-right:4px;"></i>EGZERSÄ°Z</div>
                            </div>
                            <select id="ka-egzersiz" style="width: 100%; padding: 12px; border-radius: 12px; border: 2px solid #f1f5f9; background: #f8fafc; font-size: 11px; font-weight: 800; outline: none;">
                                <option value="SeÃ§iniz" ${d.egzersiz === 'SeÃ§iniz' ? 'selected' : ''}>SeÃ§iniz</option>
                                <option value="HaftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli fiziksel aktivite" ${d.egzersiz === 'HaftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli fiziksel aktivite' ? 'selected' : ''}>HaftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli fiziksel aktivite</option>
                                <option value="HaftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite" ${d.egzersiz === 'HaftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite' ? 'selected' : ''}>HaftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite</option>
                                <option value="Hem haftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli, hem de haftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite" ${d.egzersiz === 'Hem haftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli, hem de haftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite' ? 'selected' : ''}>Hem haftanÄ±n 3 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 25 dakika yÃ¼ksek ÅŸiddetli, hem de haftanÄ±n 5 gÃ¼nÃ¼ veya daha fazla gÃ¼nde en az 30 dakika orta ÅŸiddetli fiziksel aktivite</option>
                                <option value="HaftanÄ±n 3-5 gÃ¼nÃ¼ gÃ¼nde 30-40 dakika dÃ¼ÅŸÃ¼k/orta ÅŸiddette aerobik egzersiz" ${d.egzersiz === 'HaftanÄ±n 3-5 gÃ¼nÃ¼ gÃ¼nde 30-40 dakika dÃ¼ÅŸÃ¼k/orta ÅŸiddette aerobik egzersiz' ? 'selected' : ''}>HaftanÄ±n 3-5 gÃ¼nÃ¼ gÃ¼nde 30-40 dakika dÃ¼ÅŸÃ¼k/orta ÅŸiddette aerobik egzersiz</option>
                                <option value="Yetersiz (ilk 3 seÃ§enekten az)" ${d.egzersiz === 'Yetersiz (ilk 3 seÃ§enekten az)' ? 'selected' : ''}>Yetersiz (ilk 3 seÃ§enekten az)</option>
                                <option value="YapmÄ±yor" ${d.egzersiz === 'YapmÄ±yor' ? 'selected' : ''}>YapmÄ±yor</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="p-actions" style="display: flex; flex-direction: column; gap: 8px; margin-top: auto; padding-top: 10px;">
                    <button class="p-btn" id="ka1-next-btn" style="background: #be123c; color: #fff; width: 100%; font-size: 16px; font-weight: 800; padding: 14px; border-radius: 14px; box-shadow: 0 4px 12px rgba(190,18,60,0.25); border: none; cursor: pointer;">Ä°LERLE <i class="fa fa-arrow-right"></i></button>
                    <button class="p-btn" id="ka1-cancel-btn" style="background: transparent; color: #94a3b8; border: 1.5px solid #f1f5f9; width: 100%; font-size: 11px; font-weight: 700; padding: 10px; border-radius: 12px; cursor: pointer;">Ä°zlemi Ä°ptal Et</button>
                </div>
            </div>
        `;
        content.dataset.lastHtml = 'ka1';
        bindKA1Events();
    } catch (e) {
        console.error("KA1 Error:", e);
    }
}

function bindKA1Events() {
    const updateKA1BMI = () => {
        const boy = parseFloat(document.getElementById('ka-boy')?.value);
        const kilo = parseFloat(document.getElementById('ka-kilo')?.value);
        const valEl = document.getElementById('ka-bmi-val');
        const dotEl = document.getElementById('ka-bmi-dot');
        const labelEl = document.getElementById('ka-bmi-label');
        const adviceEl = document.getElementById('ka-bmi-advice');

        if (boy > 0 && kilo > 0 && valEl) {
            const heightM = boy / 100;
            const bmi = (kilo / (heightM ** 2)).toFixed(1);
            valEl.innerText = bmi;

            let perc = ((bmi - 15) / (40 - 15)) * 100;
            if (perc > 95) perc = 95; if (perc < 5) perc = 5;
            dotEl.style.left = `calc(${perc}% - 8px)`;

            const maxWeight = (24.9 * (heightM ** 2)).toFixed(1);
            let status = "NORMAL", color = "#10b981", advice = "";

            if (bmi < 18.5) { status = "ZAYIF"; color = "#3b82f6"; }
            else if (bmi < 25) { status = "NORMAL"; color = "#10b981"; advice = "Ä°deal aralÄ±ktasÄ±nÄ±z."; }
            else if (bmi < 30) { status = "FAZLA KÄ°LOLU"; color = "#f59e0b"; advice = `Hedef: ${maxWeight} kg`; }
            else { status = "OBEZ"; color = "#ef4444"; advice = `Hedef: ${maxWeight} kg`; }

            labelEl.innerText = status;
            labelEl.style.color = color;
            dotEl.style.borderColor = color;
            adviceEl.innerText = advice;

            [1, 2, 3, 4].forEach(i => {
                const seg = document.getElementById(`ka-bmi-seg-${i}`);
                if (seg) seg.style.opacity = "0.15";
            });
            let activeSeg = 1;
            if (bmi >= 30) activeSeg = 4;
            else if (bmi >= 25) activeSeg = 3;
            else if (bmi >= 18.5) activeSeg = 2;
            const activeEl = document.getElementById(`ka-bmi-seg-${activeSeg}`);
            if (activeEl) activeEl.style.opacity = "0.8";
        }
    };

    const nextBtn = document.getElementById('ka1-next-btn');
    if (nextBtn) {
        nextBtn.onclick = async () => {
            try {
                console.log("rEvolution: KA1 'Ä°lerle' basÄ±ldÄ±.");
                nextBtn.disabled = true;
                nextBtn.innerHTML = `EÅŸitleniyor... <i class="fa fa-spinner fa-spin"></i>`;

                const getVal = (id) => document.getElementById(id)?.value || "";
                const vals = {
                    sistolik: getVal('ka-sys'),
                    diyastolik: getVal('ka-dia'),
                    nabiz: getVal('ka-nab'),
                    boy: getVal('ka-boy'),
                    kilo: getVal('ka-kilo'),
                    bel: getVal('ka-bel'),
                    sigara: getVal('ka-sigara'),
                    egzersiz: getVal('ka-egzersiz')
                };

                const fill = async (id, val, delay = 200) => {
                    const row = document.querySelector(`hyp-physical-examination-row[chartid="${id}"]`);
                    if (row) {
                        const input = row.querySelector('input');
                        if (input && val) {
                            input.value = val;
                            input.dispatchEvent(new Event('input', { bubbles: true }));
                            input.dispatchEvent(new Event('change', { bubbles: true }));
                        }
                    }
                    await new Promise(r => setTimeout(r, delay));
                };

                await fill('chart-systolic', vals.sistolik);
                await fill('chart-diastolic', vals.diyastolik);
                await fill('chart-pulse', vals.nabiz);
                await fill('chart-height', vals.boy);
                await fill('chart-weight', vals.kilo);
                await fill('chart-waist', vals.bel);

                const setDD = (id, val) => {
                    if (!val || val === 'SeÃ§iniz') return;
                    const dd = document.getElementById(id);
                    if (dd) {
                        const caret = dd.querySelector('.ui-dropdown-trigger');
                        if (caret) {
                            caret.click();
                            setTimeout(() => {
                                const items = Array.from(document.querySelectorAll('.ui-dropdown-item'));
                                const match = items.find(it => it.innerText.includes(val));
                                if (match) match.click();
                            }, 300);
                        }
                    }
                };

                setDD('smokingDropdown', vals.sigara);
                setTimeout(() => setDD('exerciseDropdown', vals.egzersiz), 600);

                setTimeout(() => {
                    console.log("rEvolution: SINA 'Ä°lerle' butonu aranÄ±yor (KA1)...");
                    const allPossibleButtons = Array.from(document.querySelectorAll('button, .ui-button, span.ui-button-text, .ui-clickable'));
                    const ilerle = allPossibleButtons.find(b => {
                        const t = (b.innerText || b.textContent || '').trim();
                        const isÄ°lerle = t === '\u0130lerle' || t === '\u0130\u00b7lerle' || t.toLowerCase() === 'ilerle' || t.toLowerCase() === 'i\u00b7lerle';
                        return isÄ°lerle && !b.closest('.hypstart-panel') && b.offsetParent !== null;
                    });

                    if (ilerle) {
                        console.log("rEvolution: KA1 'Ä°lerle' basÄ±lÄ±yor:", ilerle);
                        (ilerle.closest('button') || ilerle).click();

                        let checkCount = 0;
                        const checkUrl = setInterval(() => {
                            const curUrl = window.location.href.toLowerCase();
                            if (curUrl.includes('/dashboard')) { clearInterval(checkUrl); return; }

                            // Because SÄ°NA KA page URL structure wasn't fully specified by USER, 
                            // we watch for transition away from /anamnez
                            if (curUrl.includes('kah/') && !curUrl.includes('kah/anamnez')) {
                                clearInterval(checkUrl);
                                console.log("rEvolution: KA1'den KA2 sayfasÄ±na otomatik panel geÃ§iÅŸi yapÄ±lÄ±yor.");
                                navigateTo('ka2');
                            }
                            if (++checkCount > 150) {
                                clearInterval(checkUrl);
                                console.warn("rEvolution: KA2 geÃ§iÅŸ zaman aÅŸÄ±mÄ±.", window.location.href);
                                nextBtn.disabled = false;
                                nextBtn.innerHTML = `Ä°LERLE <i class="fa fa-arrow-right"></i>`;
                            }
                        }, 100);
                    } else {
                        console.error("rEvolution: KA1 SINA 'Ä°lerle' butonu bulunamadÄ±!");
                        nextBtn.disabled = false;
                        nextBtn.innerHTML = `Ä°LERLE <i class="fa fa-arrow-right"></i>`;
                    }
                }, 1500);

            } catch (err) {
                console.error("rEvolution KA1 Error:", err);
                nextBtn.disabled = false;
                nextBtn.innerHTML = `HATA! TEKRAR DENE`;
            }
        };
    }

    const cancelBtn = document.getElementById('ka1-cancel-btn');
    if (cancelBtn) {
        cancelBtn.onclick = () => {
            const sinaCancel = Array.from(document.querySelectorAll('button, .ui-button, span.ui-button-text')).find(b =>
                ((b.innerText || '').trim() === 'Ä°zlemi Ä°ptal Et' || (b.innerText || '').trim() === 'TaramayÄ± Ä°ptal Et') && !b.closest('.hypstart-panel')
            );
            if (sinaCancel) {
                (sinaCancel.closest('button') || sinaCancel).click();
                setTimeout(() => {
                    const confirmBtn = Array.from(document.querySelectorAll('.ui-dialog button')).find(b =>
                        (b.innerText || "").trim() === "Ä°zlemi Ä°ptal Et"
                    );
                    if (confirmBtn) (confirmBtn.closest('button') || confirmBtn).click();
                    setTimeout(() => { window.location.href = 'https://hyp.saglik.gov.tr/dashboard'; }, 1000); // Standard fallback
                }, 500);
