<?php
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>{PPP:page_title}</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">

    <!-- Stylesheets -->
    <link rel="stylesheet" href="{PPP:site_url}/system_resource/vender/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="{PPP:site_url}/system_resource/css/dialog2.css">
    <link rel="stylesheet" href="{PPP:site_url}/system_resource/css/console2_common.css">
    <link rel="stylesheet" href="{PPP:site_url}/system_resource/css/console2_edit.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>
        const SITE_TITLE = "{PPP #:site_title}";
        const SITE_URL = "{PPP #:site_url}";
        const BASE_URL = "{PPP #:base_url}";
        const GUEST_MODE = <?php echo $guest_mode ?>;
        const RESIZE_BORDER = '<?php echo $resize_border ?>';
        const USE_RND_FILENAME = '<?php echo $use_rnd_filename ?>';
        const USE_CLIPBOARD = '<?php echo $use_clipboard ?>';
        const EXIF_TEMPLATE = "{PPP #:exif_template}";
        const SHARE_TEMPLATES = <?php echo $share_templates ?>;
    </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/console2_common.js" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script src="{PPP:site_url}/system_resource/vender/modern-context/modern-context.min.js"></script>
    <script src="{PPP:site_url}/system_resource/script/image_edit.js" defer></script>
    <script src="{PPP:site_url}/system_resource/script/edit2.js" defer></script>
</head>

<body>

    <div class="d-flex">
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>

        <!-- Sidebar -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <span class="sidebar-title">管理コンソール</span>
                <button id="toggleSidebar" title="サイドバー切替">
                    <i class="bi bi-list"></i>
                </button>
            </div>

            <ul class="nav">
                <li class="nav-item">
                    <a class="nav-link" href="{PPP:base_url}/console">
                        <i class="bi bi-house-fill"></i>
                        <span class="menu-text">ダッシュボード</span>
                    </a>
                </li>

                <div class="nav-section-title">コンテンツ</div>

                <li class="nav-item">
                    <a class="nav-link" href="{PPP:base_url}/console/articles">
                        <i class="bi bi-file-text-fill"></i>
                        <span class="menu-text">記事一覧</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {PPP IF:mode==create}active{PPP ENDIF}" href="{PPP:base_url}/edit">
                        <i class="bi bi-pencil-square"></i>
                        <span class="menu-text">新規作成</span>
                    </a>
                </li>

                <div class="nav-section-title">コミュニケーション</div>

                <li class="nav-item">
                    <a class="nav-link" href="{PPP:base_url}/console/messages">
                        <i class="bi bi-envelope-fill"></i>
                        <span class="menu-text">メッセージ</span>
                        {PPP IF:messages}
                        <span class="badge">{PPP:messages}</span>
                        {PPP ENDIF}
                    </a>
                </li>

                <div class="nav-section-title">設定</div>

                <li class="nav-item">
                    <a class="nav-link" href="{PPP:base_url}/setting">
                        <i class="bi bi-gear-fill"></i>
                        <span class="menu-text">サイト設定</span>
                    </a>
                </li>
            </ul>

            <div style="flex: 1;"></div>

            <ul class="nav" style="border-top: 1px solid var(--border-light); margin-top: auto;">
                <li class="nav-item">
                    <a class="nav-link" href="{PPP:site_url}/" target="_blank">
                        <i class="bi bi-box-arrow-up-right"></i>
                        <span class="menu-text">サイトを表示</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{PPP:base_url}/logout">
                        <i class="bi bi-box-arrow-right"></i>
                        <span class="menu-text">ログアウト</span>
                    </a>
                </li>
            </ul>
        </nav>

        <!-- Main Content -->
        <main id="content">
            <!-- System Header -->
            <div class="system_header">
                <a id="back_link" href="{PPP:base_url}/console/articles" class="header_link_exit"><i class="bi bi-arrow-left"></i> 記事一覧</a>
                <div class="header_option_link_area">
                    {PPP IF:mode=="edit"}
                    <a id="preview_link" href="{PPP:log_page_url}" target="_blank"><i class="bi bi-eye"></i> ページを表示</a>
                    {PPP ENDIF}
                    <a id="logout_link" href="{PPP:base_url}/logout">ログアウト</a>
                </div>
            </div>

            <div class="content-header">
                <div class="header-left d-flex align-items-center">
                    <button type="button" class="mobile-menu-btn" id="mobileMenuBtn" aria-label="メニューを開く">
                        <i class="bi bi-list"></i>
                    </button>
                    <div>
                        <h1>{PPP IF:mode=="edit"}記事を編集{PPP ELSE}新規作成{PPP ENDIF}</h1>
                        <p class="content-header-subtitle">
                            {PPP IF:mode=="edit"}
                            ID: {PPP:article_id}
                            {PPP IF:settings["use_feedback"]}
                            <span style="margin-left:1rem"><i class="bi bi-eye"></i> {PPP:views}</span>
                            <span style="margin-left:1rem"><i class="bi bi-heart"></i> {PPP:like}</span>
                            {PPP ENDIF}
                            {PPP ELSE}
                            新しい記事を作成します
                            {PPP ENDIF}
                        </p>
                    </div>
                </div>
                <div class="header-actions">
                    <button type="submit" id="submit2" name="submit2" class="submit-btn submit-btn-primary">
                        <i class="bi bi-check-lg"></i> {PPP:submit_title}
                    </button>
                </div>
            </div>

            <div class="content-body" style="max-width: 1200px;margin:0 auto;">
                <form method="post" enctype="multipart/form-data" id="inputForm">
                    <input type="hidden" name="type" value="{PPP:type}">
                    <input type="hidden" name="id" id="id" value="{PPP:article_id}">
                    <input type="hidden" name="remove_files" id="remove_files">
                    {PPP IF:demo_mode}
                    <div class="message">デモ版です。HTMLタグは削除されます。動画は投稿できません。</div>
                    {/PPP IF}
                    <div class="edit-form-card">
                        <!-- Status Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-toggles"></i>
                                公開設定
                            </div>
                            <div class="status-row">
                                <div class="status-item">
                                    <label>ステータス</label>
                                    <select name="status" class="edit-select">
                                        <option value="0" {PPP IF:article_status==0}selected{PPP ENDIF}>公開</option>
                                        <option value="1" {PPP IF:article_status==1}selected{PPP ENDIF}>下書き</option>
                                    </select>
                                </div>
                                <div class="status-item">
                                    <label>スタイル</label>
                                    <select name="style" class="edit-select">
                                        <option value="0" {PPP IF:article_style==0}selected{PPP ENDIF}>シンプル</option>
                                        <option value="1" {PPP IF:article_style==1}selected{PPP ENDIF}>詳細記事</option>
                                        <option value="4" {PPP IF:article_style==4}selected{PPP ENDIF}>漫画[左]</option>
                                        <option value="5" {PPP IF:article_style==5}selected{PPP ENDIF}>漫画[右]</option>
                                        <option value="6" {PPP IF:article_style==6}selected{PPP ENDIF}>漫画[左_見開き]</option>
                                        <option value="7" {PPP IF:article_style==7}selected{PPP ENDIF}>漫画[右_見開き]</option>
                                        <option value="2" {PPP IF:article_style==2}selected{PPP ENDIF}>小説[横]</option>
                                        <option value="3" {PPP IF:article_style==3}selected{PPP ENDIF}>小説[縦]</option>
                                        <option value="99" {PPP IF:article_style==99}selected{PPP ENDIF}>固定ページ</option>
                                    </select>
                                </div>
                            </div>
                            {PPP IF:artice_editing==1}
                            <div class="alert alert-warning" style="margin-top: 1rem;">
                                <i class="bi bi-exclamation-triangle"></i>
                                自動保存された編集データを表示しています
                                <a href="#">編集中のデータを破棄</a>
                            </div>
                            {PPP ENDIF}
                        </div>

                        <!-- Image Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-images"></i>
                                画像
                            </div>
                            <div class="image-upload-area">
                                <input type="file" name="tmp" id="file_select" accept="image/*,.mp4" multiple class="hide" data-maxsize="{PPP:max_send_size}">

                                <div id="drop_area" class="drop-zone {PPP:post_mode_class}">
                                    <div class="drop-zone-icon"><i class="bi bi-cloud-arrow-up"></i></div>
                                    <div class="drop-zone-text">
                                        画像をドラッグ&ドロップ<br>
                                        または<strong>クリックして選択</strong>
                                    </div>
                                </div>

                                <div id="preview_area" class="{PPP:edit_mode_class}">
                                    <ul id="preview_list">
                                        {PPP:previews}
                                        <li id="drop_area2_root">
                                            <div id="drop_area2" class="drop-zone">
                                                <span><i class="bi bi-plus-lg"></i><br>追加</span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>

                                <div class="thumb-setting">
                                    <label>サムネイル</label>
                                    <select class="edit-select" id="thumbnail" name="thumbnail">
                                        <option value="" {PPP IF:thumbnail=="" }selected{PPP ENDIF}>自動</option>
                                        <option value="@all" {PPP IF:thumbnail=="@all" }selected{PPP ENDIF}>自動（全画像をサムネイル表示）</option>
                                        <option value="@user_thumbnail" {PPP IF:thumbnail=="@user_thumbnail" }selected{PPP ENDIF}>1枚目をサムネイルとして使用</option>
                                        <option value="@text" {PPP IF:thumbnail=="@text" }selected{PPP ENDIF}>サムネイルなし</option>
                                        {PPP LOOP:list_thumbs}
                                        <option value="{PPP:list_thumbs_item}" {PPP IF:thumbnail=="$list_thumbs_item" }selected{PPP ENDIF}>{PPP:list_thumbs_item}</option>
                                        {/PPP LOOP}
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Content Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-text-paragraph"></i>
                                コンテンツ
                            </div>

                            <div class="unified-input-area">
                                <div class="unified-input-header">
                                    <input type="text" id="created_at" name="created_at" value="{PPP:created_at}" placeholder="作成日時" class="unified-date-input">
                                    <button type="button" class="date-reload-btn" id="time_reload" title="現在時刻に更新">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </button>
                                </div>
                                <input type="text" id="title" name="title" value="{PPP:title}" placeholder="タイトルを入力..." class="unified-title-input">
                            </div>

                            <textarea name="contents" id="contents" class="edit-input edit-textarea" placeholder="本文を入力..." wrap="off" data-syntax-editor>{PPP:contents}</textarea>

                            <div style="margin-top: 0.75rem; display: flex; gap: 0.5rem;">
                                <a href="https://ppp.kannagi.net/view.php?id=2" class="command-palette-trigger" target="_blank">
                                    <i class="bi bi-question-circle"></i> ヘルプ
                                </a>
                                <a href="#" id="show_command_palette" class="command-palette-trigger">
                                    <i class="bi bi-command"></i> コマンド一覧
                                </a>
                            </div>
                        </div>

                        <!-- Tags Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-tags"></i>
                                タグ
                            </div>
                            <div class="tag-input-area">
                                <input type="text" id="tags" name="tags" value="{PPP:tags}" placeholder="タグをスペース区切りで入力..." class="edit-input">
                                <span class="tag-cloud-title">タグはスペース区切りで入力。先頭に「-」を付けると隠しタグになります。</span>
                                <div class="console-tag-cloud">
                                    <?= $tagcloud_nolink_sys ?? $tagcloud_nolink ?>
                                    <?= $tagcloud_nolink_more_sys ?? $tagcloud_nolink_more ?>
                                </div>
                            </div>
                        </div>

                        <!-- Options Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-sliders"></i>
                                オプション
                            </div>
                            <div class="options-grid">
                                <div class="option-item">
                                    <input type="checkbox" name="pin" id="pin" {PPP CHECKED:pin}>
                                    <label for="pin">トップページにピン止め</label>
                                    <span class="pin-priority">
                                        優先度: <input type="text" name="sort" value="{PPP:sort}">
                                    </span>
                                </div>
                                <div class="option-item">
                                    <input type="checkbox" name="nsfw" id="nsfw" {PPP CHECKED:nsfw}>
                                    <label for="nsfw">NSFW (R18)</label>
                                </div>
                                <div class="option-item">
                                    <input type="checkbox" name="use_alt_ogimage" id="use_alt_ogimage" {PPP CHECKED:use_alt_ogimage}>
                                    <label for="use_alt_ogimage">TwitterCardに画像を非表示</label>
                                </div>
                                <div class="option-item">
                                    <input type="checkbox" name="hidden" id="hidden" {PPP CHECKED:hidden}>
                                    <label for="hidden">一覧に表示しない</label>
                                </div>
                                <div class="option-item hide">
                                    <input type="checkbox" name="use_html" id="use_html" checked>
                                    <label for="use_html">HTMLを使用する</label>
                                </div>
                            </div>
                        </div>

                        <!-- URL Section -->
                        <div class="edit-form-section">
                            <div class="edit-form-section-title">
                                <i class="bi bi-link-45deg"></i>
                                カスタムURL
                            </div>
                            <div class="url-input-area">
                                <input type="text" id="alt_url" name="alt_url" value="{PPP:alt_url}" placeholder="カスタムURLを設定（例: about, contact）" class="edit-input">
                                <span class="url-hint">{PPP:site_url}/<strong>****</strong> の **** 部分を指定します</span>
                            </div>
                        </div>

                        <!-- Submit Section -->
                        <div class="submit-area">
                            {PPP IF:mode=="edit"}
                            <button type="button" id="delete" class="submit-btn submit-btn-danger" data-target="{PPP:target}">
                                <i class="bi bi-trash"></i> 削除
                            </button>
                            {PPP ELSE}
                            <div></div>
                            {PPP ENDIF}
                            <button type="submit" id="submit" name="submit" class="submit-btn submit-btn-primary">
                                <i class="bi bi-check-lg"></i> {PPP:submit_title}
                            </button>
                        </div>
                    </div>

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

            <footer class="content-footer">
                <p>&copy; 2025 - Powered by PictPostPersonal</p>
            </footer>
        </main>
    </div>

    <!-- Command Palette -->
    <div class="command_palette hide">
        <div class="command_palette_inner">
            <div class="edit-form-section-title" style="margin-bottom: 1rem;">
                <i class="bi bi-command"></i>
                コマンド一覧
            </div>
            <ul>
                <li class="insert_item">{caption} {/caption}</li>
                <li class="insert_item">{1}</li>
                <li class="insert_item">{2}</li>
                <li class="insert_item">{3}</li>
                <li class="insert_item">{c}</li>
                <li class="insert_item">{search search_word}</li>
                <li class="insert_item">{link index_or_url text}</li>
                <li class="insert_item">{article_list tag sort style count}</li>
                <li class="insert_item">{mailform}</li>
                <li class="insert_item">{messageform}</li>
                <li class="insert_item">{vt} {/vt}</li>
                <li class="insert_item">{tc} {/tc}</li>
                <li class="insert_item">{rb}漢字|カナ{/rb}</li>
                <li class="insert_item">{border}</li>
                <li class="insert_item">{border #color}</li>
                <li class="insert_item">{hidden target}</li>
                <li class="insert_item">{md} {/md}</li>
                <li class="insert_item">{more} {/more}</li>
                <li class="insert_item">{mangaview}</li>
                <li class="insert_item">{password key comment} {/password}</li>
                <li class="insert_item">{pagebreak}</li>
            </ul>
            <div style="margin-top: 1rem; text-align: right;">
                <button type="button" class="btn btn-outline command_palette_close">閉じる</button>
            </div>
        </div>
    </div>

    <!-- Image Edit Overlay -->
    <div class="image_edit_overlay hide">
        <div class="image_edit">
            <div class="image_edit_contents">
                <span class="image_edit_title">画像編集</span>
                <br><br>
                <div class="slider_container">
                    <span class="slider_container_col1">色温度補正</span>
                    <div><input type="range" id="temperatureInput" class="gradient_slider slider_container_col2" min="-100" max="100" value="0"></div>
                    <span class="slider_container_col3" id="temperatureValue">0</span>

                    <span class="slider_container_col1">色かぶり補正</span>
                    <div><input type="range" id="tintInput" class="gradient_slider slider_container_col2" min="-100" max="100" value="0"></div>
                    <span class="slider_container_col3" id="tintValue">0</span>

                    <span class="slider_container_col1">明るさ補正</span>
                    <div><input type="range" id="brightnessInput" class="gradient_slider slider_container_col2" min="-100" max="100" value="0"></div>
                    <span class="slider_container_col3" id="brightnessValue">0</span>
                </div>
                <br><br>
                <canvas id="canvas"></canvas>
                <p style="font-size: 0.75rem; color: var(--text-muted); margin: 0.5rem 0 0 0;">マウスドラッグでトリミング範囲を指定できます</p>
                <div class="image_edit_buttons">
                    <button id="image_edit_cancel" class="btn btn-outline" onClick="cancelImageEdit()">キャンセル</button>
                    <button id="image_edit_accept" class="btn btn-primary">OK</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 1. サイドバーを閉じた状態で初期化
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            if (sidebar && content && window.innerWidth > 768) {
                sidebar.classList.add('collapsed');
                content.classList.add('expanded');
            }

            // 2. タグ(.p-tag)クリック時にタグ入力欄に追加
            document.querySelectorAll('.p-tag').forEach(tag => {
                tag.style.cursor = 'pointer';
                tag.addEventListener('click', function() {
                    const tagInput = document.getElementById('tags');
                    let tagString = this.innerText.replace('#', '').trim();
                    if (tagInput && tagString) {
                        const currentValue = tagInput.value.trim();
                        if (!currentValue.split(/\s+/).includes(tagString)) {
                            tagInput.value = currentValue ? currentValue + ' ' + tagString : tagString;
                        }
                    }
                });
            });
        });
    </script>

    <!-- Syntax Editor Script -->
    <script>
        // グローバルにSyntaxEditorインスタンスを保持
        window.syntaxEditors = new Map();

        document.addEventListener('DOMContentLoaded', function() {
            class SyntaxEditor {
                constructor(textarea) {
                    this.textarea = textarea;
                    this.container = null;
                    this.backdrop = null;
                    this.highlights = null;
                    this.isScrolling = false;
                    this.lastValue = '';
                    this.init();
                }

                init() {
                    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);
                    this.syncStyles();

                    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);

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

                    // valueプロパティのsetterをオーバーライドしてコードによる変更を検知
                    this.overrideValueProperty();

                    // フォーカス時にも更新をチェック
                    this.textarea.addEventListener('focus', () => this.update());

                    const syncLoop = () => {
                        this.syncScroll();
                        // 値が変更されていたら更新（フォールバック）
                        if (this.lastValue !== this.textarea.value) {
                            this.update();
                        }
                        requestAnimationFrame(syncLoop);
                    };
                    syncLoop();

                    this.update();

                    window.addEventListener('resize', () => {
                        this.syncStyles();
                        this.update();
                    });
                }

                overrideValueProperty() {
                    const self = this;
                    const descriptor = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
                    const originalSet = descriptor.set;

                    Object.defineProperty(this.textarea, 'value', {
                        get: function() {
                            return descriptor.get.call(this);
                        },
                        set: function(val) {
                            originalSet.call(this, val);
                            self.update();
                        },
                        configurable: true
                    });
                }

                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];
                    });

                    const pb = parseFloat(style.paddingBottom) || 0;
                    this.backdrop.style.paddingBottom = (pb + 50) + 'px';

                    this.highlights.style.fontFamily = style.fontFamily;
                    this.highlights.style.fontSize = style.fontSize;
                    this.highlights.style.lineHeight = style.lineHeight;
                    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;
                    this.lastValue = text;

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

                    text = text.replace(/(&lt;.*?&gt;)/g, '<span class="syntax-tag">$1</span>');
                    text = text.replace(/(?<!\{)\{([^{}]+)\}(?!\})/g, '<span class="syntax-var">{$1}</span>');

                    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();
                }
            }

            const textareas = document.querySelectorAll('textarea[data-syntax-editor]');
            textareas.forEach(textarea => {
                const editor = new SyntaxEditor(textarea);
                window.syntaxEditors.set(textarea.id || textarea, editor);
            });
        });

        // 外部からシンタックスハイライトを更新するためのヘルパー関数
        window.updateSyntaxHighlight = function(textareaId) {
            if (textareaId) {
                const editor = window.syntaxEditors.get(textareaId);
                if (editor) editor.update();
            } else {
                // 全エディタを更新
                window.syntaxEditors.forEach(editor => editor.update());
            }
        };
    </script>
</body>

</html>