<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>設定画面 - PictPostPersonal 2</title>

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Noto+Sans+JP:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- FontAwesome -->
    <link rel="stylesheet" href="{PPP:site_url}/system_resource/vender/fontawesome/css/all.min.css" rel="preload">

    <!-- Dialog CSS -->
    <link href="{PPP:site_url}/system_resource/css/dialog2.css" rel="stylesheet">

    <link href="{PPP:site_url}/system_resource/css/systemheader.css" rel="stylesheet">

    <link rel="stylesheet" href="{PPP:site_url}/system_resource/css/console2_setting.css">

    <script>
        const BASE_URL = "{PPP:base_url}";
    </script>
    <script src="{PPP:site_url}/system_resource/script/dialog2.js" defer></script>
    <script src="{PPP:site_url}/system_resource/script/common2.js" defer></script>
    <script src="{PPP:site_url}/system_resource/script/admin2.js" defer></script>
    <script src="{PPP:site_url}/system_resource/script/console2_common.js" defer></script>

    <style>
        :root {
            --sidebar-width: 0px;
            --sidebar-collapsed-width: 0px;
        }
    </style>
</head>

<body>
    <div class="d-flex">

        <!-- メインコンテンツ -->
        <main id="content">
            <form action="./setting" method="post" enctype="multipart/form-data" autocomplete="off">
                <!-- 基本設定 -->
                <section id="section_basic" class="active">
                    <h2 class="section-title">初期設定</h2>
                    <p class="section-description">サイトの基本情報的な情報を設定します。この設定は後から変更できます。</p>

                    <div class="settings-card">
                        <h3 class="card-title"><i class="bi bi-info-circle"></i> サイト情報</h3>

                        <div class="form-group">
                            <label for="site_title" class="form-label">サイトタイトル</label>
                            <input type="text" class="form-control" id="site_title" name="site_title"
                                value="{PPP SETTING:site_title}" placeholder="サイト名を入力">
                        </div>

                        <div class="form-group">
                            <label for="image_color" class="form-label">サイトイメージカラー</label>
                            <input type="color" class="form-control form-control-color" id="image_color" name="image_color"
                                value="{PPP SETTING:image_color}" title="カラーを選択">
                        </div>

                        <div class="form-group">
                            <label for="index_text" class="form-label">インデックスページ案内文</label>
                            <textarea class="form-control" id="index_text" name="index_text" data-syntax-editor
                                rows="10">{PPP SETTING:index_text}</textarea>
                        </div>

                        <div class="form-group">
                            <label class="form-label">トップページバナー画像</label>
                            <input class="hide" type="hidden" name="use_banner" value="0">
                            <input class="form-check-input hide" type="checkbox" id="use_banner"
                                name="use_banner" value="1" {PPP SETTING C:use_banner}>
                            {PPP IF:settings['use_banner']}
                            <a href="{PPP:site_url}/images/{PPP:settings['banner']}" target="_blank"><span class="file_status" data-target="banner_file">[指定あり]</span></a>
                            {PPP ELSE}
                            <span class="file_status" data-target="banner_file">[指定なし]</span>
                            {PPP ENDIF}
                            <button type="button" class="file_button btn btn-sm btn-primary" data-target="banner_file">参照</button>
                            <button type="button" class="file_clear_button btn btn-sm btn-secondary" data-target="banner">クリア</button>
                            <input type="file" class="form-control hide" id="banner_file" name="banner_file" accept="image/*">
                            <div class="form-text">推奨サイズ: 横幅1200px以上</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">サイトタイトル表示</label>
                            <div class="form-check">
                                <input type="hidden" name="show_title" value="0">
                                <input class="form-check-input" type="checkbox" id="show_title"
                                    name="show_title" value="1" {PPP SETTING C:show_title}>
                                <label class="form-check-label" for="show_title">
                                    タイトルを文字で表示する
                                </label>
                            </div>
                        </div>

                        <div class="form-group">
                            <input class="hide" type="hidden" name="use_ogimage" value="0">
                            <input class="form-check-input hide" type="checkbox" id="use_ogimage"
                                name="use_ogimage" value="1" {PPP SETTING C:use_ogimage}>

                            <label for="ogimage" class="form-label">サイトイメージ画像</label>
                            {PPP IF:settings['use_ogimage']}
                            <a href="{PPP:site_url}/images/{PPP:settings['ogimage']}" target="_blank"><span class="file_status" data-target="ogimage_file">[指定あり]</span></a>
                            {PPP ELSE}
                            <span class="file_status" data-target="ogimage_file">[指定なし]</span>
                            {PPP ENDIF}
                            <button type="button" class="file_button btn btn-sm btn-primary" data-target="ogimage_file">参照</button>
                            <button type="button" class="file_clear_button btn btn-sm btn-secondary" data-target="ogimage">クリア</button>
                            <input type="file" class="form-control hide" id="ogimage_file" name="ogimage_file" accept="image/*">
                            <div class="form-text">推奨サイズ: 1200x630px（PNG、JPG形式）</div>
                        </div>

                        <div class="form-group">
                            <label for="favicon_file" class="form-label">Favicon画像</label>
                            <input class="hide" type="hidden" name="use_favicon" value="0">
                            <input class="form-check-input hide" type="checkbox" id="use_favicon"
                                name="use_favicon" value="1" {PPP SETTING C:use_favicon}>

                            {PPP IF:settings['use_favicon']}
                            <a href="{PPP:site_url}/images/{PPP:settings['favicon']}" target="_blank"><span class="file_status" data-target="favicon_file">[指定あり]</span></a>
                            {PPP ELSE}
                            <span class="file_status" data-target="favicon_file">[指定なし]</span>
                            {PPP ENDIF}
                            <button type="button" class="file_button btn btn-primary btn-sm" data-target="favicon_file">参照</button>
                            <button type="button" class="file_clear_button btn btn-sm btn-secondary" data-target="favicon">クリア</button>
                            <input type="file" class="form-control hide" id="favicon_file" name="favicon_file" accept="image/*">
                            <div class="form-text">推奨サイズ: 32x32px または 64x64px（PNG形式）</div>
                        </div>

                        <h3 class="card-title"><i class="bi bi-person-circle"></i> 作者情報</h3>

                        <div class="form-group">
                            <label for="display_name" class="form-label">サイト作者名</label>
                            <input type="text" class="form-control" id="display_name" name="display_name"
                                value="{PPP SETTING:display_name}" placeholder="作者名を入力">
                        </div>

                        <div class="form-group">
                            <label for="mail_address" class="form-label">メールアドレス</label>
                            <input type="email" class="form-control" id="mail_address" name="mail_address"
                                value="{PPP SETTING:mail_address}" placeholder="example@example.com">
                        </div>

                        <div class="form-group">
                            <label for="icon" class="form-label">ユーザーアイコン</label>
                            <input class="hide" type="hidden" name="use_icon" value="0">
                            <input class="form-check-input hide" type="checkbox" id="use_icon"
                                name="use_icon" value="1" {PPP SETTING C:use_icon}>
                            {PPP IF:settings['use_icon']}
                            <a href="{PPP:site_url}/images/{PPP:settings['icon']}" target="_blank"><span class="file_status" data-target="icon_file">[指定あり]</span></a>
                            {PPP ELSE}
                            <span class="file_status" data-target="icon_file">[指定なし]</span>
                            {PPP ENDIF}
                            <button type="button" class="file_button btn btn-sm btn-primary" data-target="icon_file">参照</button>
                            <button type="button" class="file_clear_button btn btn-sm btn-secondary" data-target="icon">クリア</button>
                            <input type="file" class="form-control hide" id="icon_file" name="icon_file" accept="image/*">
                            <div class="form-text">推奨サイズ: 128x128px以上（正方形）</div>
                        </div>


                    </div>
                    <div class="content-footer">
                        <button type="submit" class="btn btn-primary btn-save" id="saveButton">
                            <i class="bi bi-check-lg"></i> 保存
                        </button>
                    </div>
                </section>

                {PPP:csrf}
            </form>
        </main>
    </div>



    <script>
        // 要素の取得
        var pageTitle = document.getElementById("page-title");

        var titleMap = {
            'basic': '基本設定',
            'index': 'インデックスページ設定',
            'entry': 'エントリーページ設定',
            'nsfw': 'NSFW設定',
            'theme': 'テーマ設定',
            'usercss': 'ユーザーCSS',
            'articles': '記事ページ動作設定',
            'edit': '記事作成設定',
            'custom': 'カスタム動作設定',
            'portal': 'ポータル連携設定',
            'guestmode': 'ゲストモード設定',
            'system': 'システム詳細設定'
        };

        // セクション切り替え関数
        function switchSection(targetKey, clickedLink) {
            var links = document.querySelectorAll(".menu-link");
            var sections = document.querySelectorAll("section");
            var targetId = "section_" + targetKey;

            // メニューのアクティブ状態を更新
            for (var i = 0; i < links.length; i++) {
                links[i].classList.remove("active");
            }
            if (clickedLink) {
                clickedLink.classList.add("active");
            }

            // 全セクション非表示
            for (var j = 0; j < sections.length; j++) {

                sections[j].classList.remove("active");
            }

            // ターゲットを表示
            var targetSection = document.getElementById(targetId);
            if (targetSection) {
                targetSection.classList.add("active");
                if (pageTitle) {
                    pageTitle.textContent = titleMap[targetKey] || '設定';
                }
                window.scrollTo(0, 0);
            }

            // モバイルの場合はメニューを閉じる
            if (window.innerWidth <= 768) {
                ConsoleCommon.closeMobileMenu();
            }
        }

        // 左側メニューの動作設定
        var menuLinks = document.querySelectorAll(".menu-link");
        for (var k = 0; k < menuLinks.length; k++) {

            (function(link) {

                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    var targetKey = link.getAttribute("data-target");
                    if (targetKey) {
                        switchSection(targetKey, link);
                    }
                });
            })(menuLinks[k]);
        }

        // セクションナビゲーターボタンの動作設定
        var navSectionLinks = document.querySelectorAll(".nav-section-link");
        for (var n = 0; n < navSectionLinks.length; n++) {
            (function(button) {
                button.addEventListener("click", function(e) {
                    e.preventDefault();
                    var targetKey = button.getAttribute("data-target");
                    if (targetKey) {
                        // 対応するメニューリンクを取得
                        var menuLink = document.querySelector(".menu-link[data-target='" + targetKey + "']");
                        switchSection(targetKey, menuLink);
                    }
                });
            })(navSectionLinks[n]);
        }

        // テーマメニューの動作設定
        var themeSelecter = document.getElementById("theme");
        if (themeSelecter) {
            themeSelecter.addEventListener("change", function(e) {
                var themeSections = document.querySelectorAll(".theme_section");
                var targetId = "theme_setting_" + e.target.value;

                for (var i = 0; i < themeSections.length; i++) {
                    themeSections[i].classList.remove("active");
                }

                var targetSection = document.getElementById(targetId);
                if (targetSection) {
                    targetSection.classList.add("active");
                }
            });
        }

        // ファイルボタン動作設定
        var fileButtons = document.querySelectorAll('.file_button');
        for (var m = 0; m < fileButtons.length; m++) {
            (function(button) {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    var targetId = button.getAttribute("data-target");
                    var fileInput = document.getElementById(targetId);
                    if (fileInput) {
                        fileInput.click();
                    }
                });
            })(fileButtons[m]);
        }

        // ファイル入力のchangeイベント設定
        var fileInputs = document.querySelectorAll('input[type="file"]');
        for (var o = 0; o < fileInputs.length; o++) {
            (function(fileInput) {
                fileInput.addEventListener('change', function(e) {
                    if (fileInput.files.length > 0) {
                        var targetId = fileInput.id;
                        var fileStatus = document.querySelector('.file_status[data-target="' + targetId + '"]');
                        if (fileStatus) {
                            fileStatus.textContent = "[指定あり]";
                            // 親要素がアンカータグの場合、span要素だけにする
                            if (fileStatus.parentElement && fileStatus.parentElement.tagName.toLowerCase() === 'a') {
                                var parentAnchor = fileStatus.parentElement;
                                parentAnchor.parentNode.replaceChild(fileStatus, parentAnchor);
                            }
                        }
                        // 対応するチェックボックスをチェック
                        var useCheckbox = document.getElementById("use_" + targetId.replace('_file', ''));
                        if (useCheckbox) {
                            useCheckbox.checked = true;
                        }
                    }
                });
            })(fileInputs[o]);
        }

        var fileClearButtons = document.querySelectorAll('.file_clear_button');
        for (var n = 0; n < fileClearButtons.length; n++) {
            (function(button) {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    var targetId = button.getAttribute("data-target");
                    var fileInput = document.getElementById(targetId + "_file");
                    if (fileInput) {
                        fileInput.value = "";
                    }
                    var fileCheck = document.getElementById("use_" + targetId);
                    if (fileCheck) {
                        fileCheck.checked = false;
                    }
                    var fileStatus = document.querySelector('.file_status[data-target="' + targetId + '_file"]');
                    if (fileStatus) {
                        fileStatus.textContent = "[指定なし]";
                        if (fileStatus.parentElement && fileStatus.parentElement.tagName.toLowerCase() === 'a') {
                            var parentAnchor = fileStatus.parentElement;
                            var fragment = document.createDocumentFragment();
                            while (parentAnchor.firstChild) {
                                fragment.appendChild(parentAnchor.firstChild);
                            }
                            parentAnchor.parentNode.replaceChild(fragment, parentAnchor);
                        }
                    }
                });
            })(fileClearButtons[n]);
        }

        // ウィンドウリサイズ時の処理
        window.addEventListener("resize", function() {
            if (window.innerWidth > 768) {
                closeMobileMenu();
            }
        });
    </script>

    <!-- 非同期保存処理 -->
    <script>
        (function() {
            var settingsForm = document.querySelector('form[action="./setting"]');
            var saveButton = document.getElementById('saveButton');

            if (!settingsForm || !saveButton) return;

            // フォーム送信をインターセプト
            settingsForm.addEventListener('submit', function(e) {
                e.preventDefault();
                saveSettings();
            });

            // 非同期保存処理
            async function saveSettings() {
                var dialog = new PppDialog();

                // 保存ボタンをローディング状態に
                saveButton.classList.add('saving');
                var buttonIcon = saveButton.querySelector('i');
                var originalIconClass = buttonIcon ? buttonIcon.className : '';
                if (buttonIcon) {
                    buttonIcon.className = 'bi bi-arrow-repeat';
                }
                saveButton.disabled = true;

                try {
                    var formData = new FormData(settingsForm);

                    //WAF対策のためBASE64エンコード
                    formData.set("index_text", base65Encoding(document.querySelector("#index_text").value ?? ""));

                    var response = await fetch(BASE_URL + '/setting', {
                        method: 'POST',
                        body: formData
                    });

                    var result;
                    try {
                        result = await response.json();
                    } catch (parseError) {
                        throw new Error('サーバーからの応答を解析できませんでした');
                    }

                    if (result.status === 'success') {
                        // 成功ダイアログを表示
                        await dialog.openAlert({
                            title: '保存完了',
                            message: '設定を保存しました。',
                            buttonText: 'OK'
                        });

                        window.location = "./";
                    } else {
                        // エラーダイアログを表示
                        var errorMessage = result.message || '設定の保存に失敗しました。';
                        await dialog.openAlert({
                            title: 'エラー',
                            message: errorMessage,
                            buttonText: '閉じる'
                        });
                    }

                } catch (error) {
                    console.error('Save error:', error);
                    // 通信エラーダイアログを表示
                    await dialog.openAlert({
                        title: 'エラー',
                        message: '通信エラーが発生しました。<br>ネットワーク接続を確認してください。',
                        buttonText: '閉じる'
                    });
                } finally {
                    // ボタンを元に戻す
                    saveButton.classList.remove('saving');
                    if (buttonIcon) {
                        buttonIcon.className = originalIconClass;
                    }
                    saveButton.disabled = false;
                }
            }

            function base65Encoding(str) {
                const utf8Bytes = new TextEncoder().encode(str);
                const base64String = btoa(String.fromCharCode(...utf8Bytes));
                return base64String;
            }

        })();
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            class SyntaxEditor {
                constructor(textarea) {
                    this.textarea = textarea;
                    this.container = null;
                    this.backdrop = null;
                    this.highlights = null;

                    this.init();
                }

                init() {
                    // Create container and backdrop
                    this.container = document.createElement('div');
                    this.container.className = 'syntax-editor-container';

                    this.backdrop = document.createElement('div');
                    this.backdrop.className = 'syntax-backdrop';

                    this.highlights = document.createElement('div');
                    this.highlights.className = 'syntax-highlights';

                    this.backdrop.appendChild(this.highlights);

                    // Style syncing
                    this.syncStyles();

                    // Wrap textarea
                    this.textarea.parentNode.insertBefore(this.container, this.textarea);
                    this.container.appendChild(this.backdrop);
                    this.container.appendChild(this.textarea);

                    // Wrap toggle button
                    this.wrapEnabled = this.textarea.getAttribute('wrap') !== 'off';
                    this.wrapToggle = document.createElement('button');
                    this.wrapToggle.type = 'button';
                    this.wrapToggle.className = 'syntax-wrap-toggle' + (this.wrapEnabled ? ' wrap-on' : '');
                    this.wrapToggle.title = '折り返し切替';
                    this.wrapToggle.innerHTML = '<i class="bi bi-text-wrap"></i>';
                    this.wrapToggle.addEventListener('click', (e) => {
                        e.preventDefault();
                        this.toggleWrap();
                    });
                    this.container.appendChild(this.wrapToggle);

                    // Event listeners
                    this.textarea.addEventListener('input', () => this.update());

                    // Use requestAnimationFrame for smoother scroll sync
                    const syncLoop = () => {
                        this.syncScroll();
                        requestAnimationFrame(syncLoop);
                    };
                    syncLoop();

                    // Initial update
                    this.update();

                    // Window resize might change styles/sizes
                    window.addEventListener('resize', () => {
                        this.syncStyles();
                        this.update();
                    });
                }

                syncStyles() {
                    const style = window.getComputedStyle(this.textarea);

                    const props = [
                        'fontFamily', 'fontSize', 'fontWeight', 'lineHeight',
                        'letterSpacing', 'whiteSpace', 'wordBreak', 'wordWrap',
                        'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
                        'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth',
                        'borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle',
                        'tabSize', 'textIndent', 'textTransform'
                    ];

                    props.forEach(prop => {
                        this.backdrop.style[prop] = style[prop];
                    });

                    // Add buffer to padding-bottom
                    const pb = parseFloat(style.paddingBottom) || 0;
                    this.backdrop.style.paddingBottom = (pb + 50) + 'px';

                    // Specifically sync highlight text styles to match
                    this.highlights.style.fontFamily = style.fontFamily;
                    this.highlights.style.fontSize = style.fontSize;
                    this.highlights.style.lineHeight = style.lineHeight;
                    // Critical for wrap="off" support
                    this.highlights.style.whiteSpace = style.whiteSpace;
                    this.highlights.style.wordWrap = style.wordWrap;
                    this.highlights.style.tabSize = style.tabSize;
                }

                syncScroll() {
                    this.highlights.style.transform = `translate(${-this.textarea.scrollLeft}px, ${-this.textarea.scrollTop}px)`;
                }

                update() {
                    let text = this.textarea.value;
                    const syntaxType = this.textarea.getAttribute('data-syntax-type') || 'default';

                    // HTML escape
                    text = text.replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;');

                    // Apply highlighting based on syntax type
                    if (syntaxType === 'css') {
                        // CSS syntax highlighting
                        // Comments /* ... */
                        text = text.replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="syntax-comment">$1</span>');

                        // Properties (word followed by colon)
                        text = text.replace(/([a-zA-Z-]+)(\s*:)/g, '<span class="syntax-property">$1</span>$2');

                        // Selectors (before { and not inside {})
                        text = text.replace(/^([^{}\/]*?)(\{)/gm, function(match, selector, brace) {
                            return '<span class="syntax-selector">' + selector + '</span>' + brace;
                        });

                        // Values with units (numbers followed by units)
                        text = text.replace(/(\d+)(px|em|rem|%|vh|vw|pt|s|ms)/g, '<span class="syntax-value">$1$2</span>');

                        // Color values
                        text = text.replace(/(#[0-9a-fA-F]{3,6})/g, '<span class="syntax-color">$1</span>');

                        // Strings
                        text = text.replace(/(&quot;[^&]*?&quot;|'[^']*?')/g, '<span class="syntax-string">$1</span>');
                    } else {
                        // Default (PPP template) syntax highlighting
                        text = text.replace(/(&lt;.*?&gt;)/g, '<span class="syntax-tag">$1</span>');
                        text = text.replace(/(\{.*?\})/g, '<span class="syntax-var">$1</span>');
                    }

                    // Handle trailing newlines
                    if (text.endsWith('\n')) {
                        text += '&nbsp;';
                    }

                    this.highlights.innerHTML = text;
                }

                toggleWrap() {
                    this.wrapEnabled = !this.wrapEnabled;
                    if (this.wrapEnabled) {
                        this.textarea.removeAttribute('wrap');
                        this.textarea.style.whiteSpace = 'pre-wrap';
                        this.textarea.style.overflowX = 'auto';
                        this.backdrop.style.whiteSpace = 'pre-wrap';
                        this.backdrop.style.wordWrap = 'break-word';
                        this.highlights.style.whiteSpace = 'pre-wrap';
                        this.highlights.style.wordWrap = 'break-word';
                        this.wrapToggle.classList.add('wrap-on');
                    } else {
                        this.textarea.setAttribute('wrap', 'off');
                        this.textarea.style.whiteSpace = 'pre';
                        this.textarea.style.overflowX = 'scroll';
                        this.backdrop.style.whiteSpace = 'pre';
                        this.backdrop.style.wordWrap = 'normal';
                        this.highlights.style.whiteSpace = 'pre';
                        this.highlights.style.wordWrap = 'normal';
                        this.wrapToggle.classList.remove('wrap-on');
                    }
                    this.syncStyles();
                    this.update();
                }
            }

            // Initialize all editors
            const textareas = document.querySelectorAll('textarea[data-syntax-editor]');
            textareas.forEach(textarea => {
                new SyntaxEditor(textarea);
            });
        });
    </script>

    <!-- アイコン選択ダイアログ スクリプト -->
    <script>
        (function() {
            'use strict';

            // アイコン選択ダイアログの状態管理
            const IconSelector = {
                overlay: null,
                currentRow: null,
                selectedIcon: null,
                selectedFile: null,
                uploadedImageData: null,

                init() {
                    this.overlay = document.getElementById('icon_select_dialog');
                    if (!this.overlay) return;

                    this.bindEvents();
                },

                bindEvents() {
                    // アイコン選択ボタンのクリック
                    document.querySelectorAll('.sns-icon-select-btn').forEach(btn => {
                        btn.addEventListener('click', (e) => {
                            e.preventDefault();
                            this.openDialog(btn.dataset.row);
                        });
                    });

                    // ダイアログ閉じるボタン
                    const closeBtn = document.getElementById('icon-dialog-close');
                    if (closeBtn) {
                        closeBtn.addEventListener('click', () => this.closeDialog());
                    }

                    // オーバーレイクリックで閉じる
                    this.overlay.addEventListener('click', (e) => {
                        if (e.target === this.overlay) {
                            this.closeDialog();
                        }
                    });

                    // ESCキーで閉じる
                    document.addEventListener('keydown', (e) => {
                        if (e.key === 'Escape' && this.overlay.classList.contains('active')) {
                            this.closeDialog();
                        }
                    });

                    // アイコングリッドのクリック
                    document.querySelectorAll('.icon-grid-item').forEach(item => {
                        item.addEventListener('click', () => this.selectIcon(item));
                    });

                    // アップロードゾーン
                    const uploadZone = document.getElementById('icon-upload-zone');
                    const uploadInput = document.getElementById('icon-upload-input');

                    if (uploadZone && uploadInput) {
                        uploadZone.addEventListener('click', () => uploadInput.click());

                        uploadZone.addEventListener('dragover', (e) => {
                            e.preventDefault();
                            uploadZone.classList.add('dragover');
                        });

                        uploadZone.addEventListener('dragleave', () => {
                            uploadZone.classList.remove('dragover');
                        });

                        uploadZone.addEventListener('drop', (e) => {
                            e.preventDefault();
                            uploadZone.classList.remove('dragover');
                            const files = e.dataTransfer.files;
                            if (files.length > 0) {
                                this.handleFileUpload(files[0]);
                            }
                        });

                        uploadInput.addEventListener('change', (e) => {
                            if (e.target.files.length > 0) {
                                this.handleFileUpload(e.target.files[0]);
                            }
                        });
                    }

                    // クリアボタン
                    const clearBtn = document.getElementById('icon-btn-clear');
                    if (clearBtn) {
                        clearBtn.addEventListener('click', () => this.clearSelection());
                    }

                    // 確定ボタン
                    const confirmBtn = document.getElementById('icon-btn-confirm');
                    if (confirmBtn) {
                        confirmBtn.addEventListener('click', () => this.confirmSelection());
                    }
                },

                openDialog(rowIndex) {
                    this.currentRow = rowIndex;
                    this.selectedIcon = null;
                    this.selectedFile = null;
                    this.uploadedImageData = null;

                    // 現在の値を取得
                    const row = document.querySelector(`.sns-link-row[data-row-index="${rowIndex}"]`);
                    if (row) {
                        const currentValue = row.querySelector('.sns-icon-value').value;
                        if (currentValue && currentValue.startsWith('fa-')) {
                            // 既存のアイコンを選択状態にする
                            const iconItem = document.querySelector(`.icon-grid-item[data-icon="${currentValue}"]`);
                            if (iconItem) {
                                this.selectIcon(iconItem);
                            }
                        }
                    }

                    // プレビューをリセット
                    this.updatePreview();

                    // ダイアログを表示
                    this.overlay.classList.add('active');
                    document.body.style.overflow = 'hidden';
                },

                closeDialog() {
                    this.overlay.classList.remove('active');
                    document.body.style.overflow = '';

                    // 選択状態をリセット
                    document.querySelectorAll('.icon-grid-item').forEach(item => {
                        item.classList.remove('selected');
                    });
                },

                selectIcon(item) {
                    // 他の選択を解除
                    document.querySelectorAll('.icon-grid-item').forEach(i => {
                        i.classList.remove('selected');
                    });

                    // 選択状態にする
                    item.classList.add('selected');
                    this.selectedIcon = item.dataset.icon;
                    this.selectedFile = null;
                    this.uploadedImageData = null;

                    this.updatePreview();
                },

                handleFileUpload(file) {
                    // ファイルサイズチェック (2MB)
                    if (file.size > 2 * 1024 * 1024) {
                        alert('ファイルサイズは2MB以下にしてください');
                        return;
                    }

                    // 画像ファイルチェック
                    if (!file.type.startsWith('image/')) {
                        alert('画像ファイルを選択してください');
                        return;
                    }

                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.uploadedImageData = e.target.result;
                        this.selectedFile = file;
                        this.selectedIcon = null;

                        // アイコン選択を解除
                        document.querySelectorAll('.icon-grid-item').forEach(item => {
                            item.classList.remove('selected');
                        });

                        this.updatePreview();
                    };
                    reader.readAsDataURL(file);
                },

                updatePreview() {
                    const previewBox = document.getElementById('icon-preview-box');
                    const previewLabel = document.getElementById('icon-preview-label');

                    if (!previewBox || !previewLabel) return;

                    if (this.selectedIcon) {
                        previewBox.innerHTML = `<i class="${this.selectedIcon}"></i>`;
                        previewLabel.textContent = this.selectedIcon.replace('fa-brands ', '').replace('fa-solid ', '');
                    } else if (this.uploadedImageData) {
                        previewBox.innerHTML = `<img src="${this.uploadedImageData}" alt="preview">`;
                        previewLabel.textContent = this.selectedFile ? this.selectedFile.name : 'アップロード画像';
                    } else {
                        previewBox.innerHTML = '<i class="bi bi-question-lg" style="color:var(--text-light);"></i>';
                        previewLabel.textContent = '未選択';
                    }
                },

                clearSelection() {
                    this.selectedIcon = null;
                    this.selectedFile = null;
                    this.uploadedImageData = null;

                    document.querySelectorAll('.icon-grid-item').forEach(item => {
                        item.classList.remove('selected');
                    });

                    this.updatePreview();
                },

                confirmSelection() {
                    if (this.currentRow === null) return;

                    const row = document.querySelector(`.sns-link-row[data-row-index="${this.currentRow}"]`);
                    if (!row) return;

                    const preview = row.querySelector('.sns-icon-preview');
                    const hiddenInput = row.querySelector('.sns-icon-value');
                    const fileInput = row.querySelector('.sns-icon-file');

                    if (this.selectedIcon) {
                        // FontAwesomeアイコンの場合
                        preview.innerHTML = `<i class="${this.selectedIcon}"></i>`;
                        preview.classList.add('has-icon');
                        hiddenInput.value = this.selectedIcon;

                        // ファイル入力をクリア
                        if (fileInput) fileInput.value = '';

                    } else if (this.uploadedImageData && this.selectedFile) {
                        // アップロード画像の場合
                        preview.innerHTML = `<img src="${this.uploadedImageData}" alt="icon">`;
                        preview.classList.add('has-icon');

                        // DataTransferを使ってファイル入力に設定
                        const dataTransfer = new DataTransfer();
                        dataTransfer.items.add(this.selectedFile);
                        fileInput.files = dataTransfer.files;

                        // hidden inputにはdata URLを一時的に設定
                        hiddenInput.value = "UPLOADIMAGE"; //this.uploadedImageData;

                    } else {
                        // クリアの場合
                        preview.innerHTML = '';
                        preview.classList.remove('has-icon');
                        hiddenInput.value = '';
                        if (fileInput) fileInput.value = '';
                    }

                    this.closeDialog();
                }
            };

            // DOM読み込み完了時に初期化
            document.addEventListener('DOMContentLoaded', () => {
                IconSelector.init();
            });
        })();
    </script>


</body>

</html>