/* ============================================================
   ICPA経営健康診断 - フロントエンド
   ============================================================ */

(function() {
    'use strict';

    const QUESTIONS_DATA = window.ICPA_SHINDAN_QUESTIONS || {};

    // flatQuestionsは会社情報入力後に構築（規模別分岐があるため）
    let flatQuestions = [];
    const sectionOrder = ['infection', 'hygiene', 'stresscheck', 'nutrition', 'kenkokeiei', 'harassment'];

    // 規模文字列から従業員数の最小値を取得する
    // 「1〜9名」→1、「50〜99名」→50、「300名以上」→300
    function parseSizeMin(sizeStr) {
        if (!sizeStr) return 0;
        const match = sizeStr.match(/(\d+)/);
        return match ? parseInt(match[1], 10) : 0;
    }

    // 会社情報を元にflatQuestionsを構築（規模別分岐対応）
    function buildQuestions() {
        flatQuestions = [];
        const sizeMin = parseSizeMin(company.size);

        sectionOrder.forEach(function(key) {
            if (!QUESTIONS_DATA[key]) return;
            QUESTIONS_DATA[key].questions.forEach(function(q, idx) {
                // 規模別分岐：size_thresholdが設定されており、自社規模が閾値以上ならq_largeを使う
                let useText = q.q;
                let useOptions = q.options;

                if (q.size_threshold && q.q_large && q.options_large) {
                    if (sizeMin >= q.size_threshold) {
                        useText = q.q_large;
                        useOptions = q.options_large;
                    }
                }

                flatQuestions.push({
                    section: key,
                    sectionTitle: QUESTIONS_DATA[key].title,
                    indexInSection: idx,
                    q: useText,
                    options: useOptions,
                });
            });
        });
    }

    let TOTAL = 0; // buildQuestions後に再代入

    // 状態
    let currentIdx = 0;
    const answers = []; // {section, score}
    const company = { industry: '', size: '' };

    // DOM
    const $intro = document.getElementById('sh-intro');
    const $company = document.getElementById('sh-company');
    const $quiz = document.getElementById('sh-quiz');
    const $calc = document.getElementById('sh-calculating');

    const $startBtn = document.getElementById('sh-start');
    const $companyNext = document.getElementById('sh-company-next');
    const $progressFill = document.getElementById('sh-progress-fill');
    const $progressCurrent = document.getElementById('sh-progress-current');
    const $sectionEyebrow = document.getElementById('sh-section-eyebrow');
    const $sectionTitle = document.getElementById('sh-section-title');
    const $sectionIcon = document.getElementById('sh-section-icon');
    const $questionNum = document.getElementById('sh-question-num');
    const $questionText = document.getElementById('sh-question-text');
    const $options = document.getElementById('sh-options');
    const $back = document.getElementById('sh-back');
    const $calcText = document.getElementById('sh-calc-text');

    // セクション別アイコン
    const SECTION_ICONS = {
        'infection': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/></svg>',
        'hygiene': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 8h14l-1 12a2 2 0 01-2 2H8a2 2 0 01-2-2L5 8z"/><path d="M9 8V5a3 3 0 016 0v3"/></svg>',
        'stresscheck': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h4l2-5 4 10 2-5h6"/></svg>',
        'nutrition': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2C8 6 6 9 6 13a6 6 0 0012 0c0-4-2-7-6-11z"/></svg>',
        'kenkokeiei': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18M5 21V10l7-7 7 7v11"/></svg>',
        'harassment': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8 14s1.5-2 4-2 4 2 4 2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>',
    };

    // 初期化
    function init() {
        $startBtn.addEventListener('click', function() {
            $intro.hidden = true;
            $company.hidden = false;
            window.scrollTo(0, 0);
        });

        // 会社情報の選択
        document.querySelectorAll('.sh-form-option').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const field = btn.getAttribute('data-field');
                const value = btn.getAttribute('data-value');
                company[field] = value;

                // 同じfieldの他ボタンの選択を解除
                document.querySelectorAll('.sh-form-option[data-field="' + field + '"]').forEach(function(b) {
                    b.classList.remove('sh-form-option-selected');
                });
                btn.classList.add('sh-form-option-selected');

                // 両方選択されたら次へボタン有効化
                if (company.industry && company.size) {
                    $companyNext.disabled = false;
                }
            });
        });

        $companyNext.addEventListener('click', startQuiz);
        $back.addEventListener('click', goBack);
    }

    function startQuiz() {
        // 会社規模を踏まえて質問配列を構築
        buildQuestions();
        TOTAL = flatQuestions.length;

        $company.hidden = true;
        $quiz.hidden = false;
        currentIdx = 0;
        answers.length = 0;
        renderQuestion();
        window.scrollTo(0, 0);
    }

    function renderQuestion() {
        const q = flatQuestions[currentIdx];
        if (!q) return;

        $sectionEyebrow.textContent = '— ' + String(currentIdx + 1).padStart(2, '0') + ' / ' + String(TOTAL).padStart(2, '0') + ' —';
        $sectionTitle.textContent = q.sectionTitle;
        $sectionIcon.innerHTML = SECTION_ICONS[q.section] || '';
        $sectionIcon.className = 'sh-section-icon sh-icon-' + q.section;

        const progressPct = (currentIdx / TOTAL) * 100;
        $progressFill.style.width = progressPct + '%';
        $progressCurrent.textContent = currentIdx + 1;

        $questionNum.textContent = 'Q' + String(currentIdx + 1).padStart(2, '0');
        $questionText.textContent = q.q;

        $options.innerHTML = '';
        q.options.forEach(function(opt, optIdx) {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'sh-option';

            const isSelected = answers[currentIdx] && answers[currentIdx].optIdx === optIdx;
            if (isSelected) btn.classList.add('sh-option-selected');

            btn.innerHTML =
                '<span class="sh-option-mark"></span>' +
                '<span class="sh-option-text">' + escapeHtml(opt.text) + '</span>';

            btn.addEventListener('click', function() {
                selectOption(optIdx);
            });
            $options.appendChild(btn);
        });

        $back.disabled = currentIdx === 0;
    }

    function selectOption(optIdx) {
        const q = flatQuestions[currentIdx];
        const score = q.options[optIdx].score;

        answers[currentIdx] = {
            section: q.section,
            optIdx: optIdx,
            score: score,
        };

        renderQuestion();

        setTimeout(function() {
            if (currentIdx < TOTAL - 1) {
                currentIdx++;
                renderQuestion();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            } else {
                finish();
            }
        }, 280);
    }

    function goBack() {
        if (currentIdx > 0) {
            currentIdx--;
            renderQuestion();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    function finish() {
        $quiz.hidden = true;
        $calc.hidden = false;
        window.scrollTo(0, 0);

        // セクション別スコア集計
        const sectionScores = {};
        const sectionCounts = {};

        sectionOrder.forEach(function(key) {
            sectionScores[key] = 0;
            sectionCounts[key] = 0;
        });

        answers.forEach(function(a) {
            if (!a) return;
            sectionScores[a.section] += a.score;
            sectionCounts[a.section]++;
        });

        // 平均化
        const finalScores = {};
        sectionOrder.forEach(function(key) {
            if (sectionCounts[key] > 0) {
                finalScores[key] = Math.round(sectionScores[key] / sectionCounts[key]);
            } else {
                finalScores[key] = 0;
            }
        });

        // 総合スコア
        let total = 0;
        let cnt = 0;
        sectionOrder.forEach(function(key) {
            total += finalScores[key];
            cnt++;
        });
        const totalScore = Math.round(total / cnt);

        // AI診断にデータ送信
        callAIAdvice(finalScores, totalScore);
    }

    async function callAIAdvice(scores, totalScore) {
        // 計算中メッセージのローテーション
        const messages = [
            '回答を分析しています…',
            '業種別の傾向を確認しています…',
            'AIがアドバイスを生成しています…',
            'もう少しお待ちください…',
        ];
        let msgIdx = 0;
        const msgInterval = setInterval(function() {
            msgIdx = (msgIdx + 1) % messages.length;
            $calcText.textContent = messages[msgIdx];
        }, 2500);

        try {
            const response = await fetch('shindan-api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    industry: company.industry,
                    size: company.size,
                    scores: scores,
                    totalScore: totalScore,
                }),
            });

            const data = await response.json();
            clearInterval(msgInterval);

            if (!data.ok) {
                // AIアドバイス生成失敗時はフォールバック
                console.error('AI advice error:', data.error);
                showResultFallback(scores, totalScore);
                return;
            }

            // 結果ページに遷移（パラメータでデータ渡し）
            sessionStorage.setItem('icpa_shindan_result', JSON.stringify({
                industry: company.industry,
                size: company.size,
                scores: scores,
                totalScore: totalScore,
                advice: data.advice,
                timestamp: Date.now(),
            }));

            window.location.href = 'shindan-result.php';

        } catch (err) {
            clearInterval(msgInterval);
            console.error('Network error:', err);
            showResultFallback(scores, totalScore);
        }
    }

    function showResultFallback(scores, totalScore) {
        // AI失敗時：シンプルな結果のみ表示
        sessionStorage.setItem('icpa_shindan_result', JSON.stringify({
            industry: company.industry,
            size: company.size,
            scores: scores,
            totalScore: totalScore,
            advice: null, // AI失敗を示す
            timestamp: Date.now(),
        }));
        window.location.href = 'shindan-result.php';
    }

    function escapeHtml(s) {
        return String(s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
