@extends('layouts.app')

@section('content')

<div class="container-fluid blade-manager">

```
{{-- =====================================================
     HEADER
====================================================== --}}

<div class="bm-header">

    <div>
        <div class="bm-title">
            <i class="fa fa-code text-primary"></i>
            Blade Content Manager
        </div>

        <div class="bm-subtitle">
            Visual editor untuk mengelola konten Blade
        </div>
    </div>

    <div class="bm-header-actions">

        <span class="bm-year">
            <i class="fa fa-calendar"></i>
            {{ session('tahuntanam') }}
        </span>

        <button
            type="button"
            class="btn btn-primary btn-sm"
            id="btnSave">

            <i class="fa fa-save"></i>
            Save

        </button>

    </div>

</div>


{{-- =====================================================
     FILE LIST
====================================================== --}}

<div class="bm-files">

    @foreach($data['file'] as $key => $file)

        <button
            type="button"
            class="bm-file"
            data-key="{{ $key }}"
            data-file="{{ $file }}"
            data-url="{{ $data['url'][$key] ?? '' }}">

            <div class="bm-file-icon">

                <i class="fa fa-file-code"></i>

            </div>

            <div class="bm-file-info">

                <div class="bm-file-title">
                    {{ ucfirst($key) }}
                </div>

                <div class="bm-file-name">
                    {{ $file ?: 'File belum disetting' }}
                </div>

            </div>

            <i class="fa fa-chevron-right bm-file-arrow"></i>

        </button>

    @endforeach

</div>


{{-- =====================================================
     MAIN EDITOR
====================================================== --}}

<div class="bm-workspace" id="bmWorkspace">


    {{-- =================================================
         LEFT CODE EDITOR
    ================================================== --}}

    <div class="bm-code-panel">

        {{-- HEADER --}}

        <div class="bm-panel-header">

            <div class="bm-panel-title">

                <i class="fa fa-code"></i>

                <span id="currentFile">
                    Pilih file
                </span>

            </div>

            <div class="bm-panel-actions">

                <button
                    type="button"
                    class="btn btn-light btn-sm"
                    id="btnCopy"
                    title="Copy">

                    <i class="fa fa-copy"></i>

                </button>

                <button
                    type="button"
                    class="btn btn-light btn-sm"
                    id="btnEditorFullscreen"
                    title="Fullscreen">

                    <i class="fa fa-expand"></i>

                </button>

            </div>

        </div>


        {{-- TOOLBAR --}}

        <div class="bm-code-toolbar">

            <span id="editorStatus">
                Ready
            </span>

            <span>
                Lines:
                <strong id="lineCount">
                    0
                </strong>
            </span>

        </div>


        {{-- CODE --}}

        <div class="bm-code-wrapper">

            <div
                class="bm-line-numbers"
                id="lineNumbers">
            </div>

            <div id="aiLineButton" class="bm-ai-line-button">
                <button
                    type="button"
                    id="btnAiLine"
                    class="btn btn-primary btn-sm"
                    title="Tambah kode dengan AI">
                    <i class="fa fa-magic"></i> AI
                </button>
            </div>

            <textarea
                id="bladeEditor"
                spellcheck="false"
                autocomplete="off"
                autocorrect="off"
                autocapitalize="off"
                wrap="off"
                placeholder="Pilih file terlebih dahulu..."></textarea>

        </div>

    </div>


    {{-- =================================================
         RIGHT PREVIEW
    ================================================== --}}

    <div class="bm-preview-panel">

        {{-- HEADER --}}

        <div class="bm-panel-header">

            <div class="bm-panel-title">

                <i class="fa fa-desktop"></i>

                Visual Preview

            </div>


            <div class="bm-panel-actions">

                <button
                    type="button"
                    class="btn btn-light btn-sm"
                    id="btnPreviewRefresh"
                    title="Refresh">

                    <i class="fa fa-refresh"></i>

                </button>


                <button
                    type="button"
                    class="btn btn-light btn-sm"
                    id="btnPreviewFullscreen"
                    title="Fullscreen">

                    <i class="fa fa-expand"></i>

                </button>

            </div>

        </div>


        {{-- URL BAR --}}

        <div class="bm-url-bar">

            <i class="fa fa-link"></i>

            <input
                type="text"
                id="previewUrl"
                readonly
                placeholder="Preview URL">

        </div>


        {{-- IFRAME --}}

        <div
            class="bm-iframe-wrapper"
            id="iframeWrapper">

            <div
                class="bm-loading"
                id="iframeLoading">

                <span class="spinner-border spinner-border-sm"></span>

                <span>
                    Loading preview...
                </span>

            </div>


            <iframe
                id="previewFrame"
                src="about:blank"
                frameborder="0"
                scrolling="yes">
            </iframe>

        </div>


        {{-- SELECTED ELEMENT INFO --}}

        <div
            class="bm-selected"
            id="selectedElementPanel">

            <div class="bm-selected-header">

                <div>

                    <i class="fa fa-mouse-pointer"></i>

                    Selected Element

                </div>

                <span
                    id="selectedTag"
                    class="bm-tag">

                    -

                </span>

            </div>


            <div class="bm-selected-body">

                <div class="bm-property">

                    <label>
                        Tag
                    </label>

                    <input
                        type="text"
                        id="propTag"
                        readonly>

                </div>


                <div class="bm-property">

                    <label>
                        Class
                    </label>

                    <input
                        type="text"
                        id="propClass"
                        readonly>

                </div>


                <div class="bm-property">

                    <label>
                        Text
                    </label>

                    <input
                        type="text"
                        id="propText"
                        readonly>

                </div>


                <div class="bm-property">

                    <label>
                        Source Line
                    </label>

                    <input
                        type="text"
                        id="propLine"
                        readonly>

                </div>

            </div>

        </div>

    </div>

</div>
```

</div>

{{-- =====================================================
     AI INSERT MODAL
====================================================== --}}

<div
    class="modal fade"
    id="aiLineModal"
    tabindex="-1"
    role="dialog"
    aria-hidden="true">

    <div
        class="modal-dialog modal-dialog-centered"
        role="document">

        <div class="modal-content bm-ai-modal">

            <div class="modal-header">

                <div>
                    <div class="bm-ai-modal-title">
                        <i class="fa fa-magic text-primary"></i>
                        Tambah Code dengan AI
                    </div>
                    <div class="bm-ai-modal-subtitle" id="aiLineInfo">
                        Kode akan ditambahkan pada line yang dipilih.
                    </div>
                </div>

                <button
                    type="button"
                    class="close"
                    data-dismiss="modal"
                    aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>

            </div>

            <div class="modal-body">

                <div class="form-group mb-0">
                    <label for="aiPrompt" class="bm-ai-label">
                        Instruksi AI
                    </label>

                    <textarea
                        id="aiPrompt"
                        class="form-control bm-ai-prompt"
                        rows="6"
                        placeholder="Contoh: tambahkan card Bootstrap untuk menampilkan total produksi di line ini...">
                    </textarea>
                </div>

                <div class="bm-ai-hint">
                    <i class="fa fa-info-circle"></i>
                    AI hanya menghasilkan potongan kode. Kode akan dimasukkan ke editor dan belum disimpan sampai tombol <strong>Save</strong> ditekan.
                </div>

            </div>

            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-light btn-sm"
                    id="btnAiCancel"
                    data-dismiss="modal">
                    Batal
                </button>

                <button
                    type="button"
                    class="btn btn-primary btn-sm"
                    id="btnAiGenerate">
                    <i class="fa fa-magic"></i>
                    Generate & Insert
                </button>

            </div>

        </div>

    </div>

</div>

<style>

/* =========================================================
   MAIN
========================================================= */

.blade-manager {

    padding-bottom: 30px;

}


.bm-header {

    display: flex;

    justify-content: space-between;

    align-items: center;

    margin-bottom: 18px;

}


.bm-title {

    font-size: 21px;

    font-weight: 600;

    color: #212529;

}


.bm-title i {

    margin-right: 8px;

}


.bm-subtitle {

    margin-top: 3px;

    color: #8a94a6;

    font-size: 12px;

}


.bm-header-actions {

    display: flex;

    align-items: center;

    gap: 10px;

}


.bm-year {

    background: #f8f9fa;

    border: 1px solid #e4e7eb;

    padding: 7px 12px;

    border-radius: 7px;

    font-size: 12px;

    color: #596273;

}


/* =========================================================
   FILE LIST
========================================================= */

.bm-files {

    display: flex;

    gap: 10px;

    overflow-x: auto;

    margin-bottom: 15px;

    padding-bottom: 3px;

}


.bm-file {

    min-width: 260px;

    border: 1px solid #e3e7eb;

    background: #fff;

    border-radius: 9px;

    padding: 10px 12px;

    display: flex;

    align-items: center;

    text-align: left;

    cursor: pointer;

    transition: .2s;

}


.bm-file:hover {

    border-color: #007bff;

    box-shadow:
        0 3px 12px rgba(0,0,0,.06);

}


.bm-file.active {

    border-color: #007bff;

    background: #f4f8ff;

}


.bm-file-icon {

    width: 38px;

    height: 38px;

    min-width: 38px;

    display: flex;

    align-items: center;

    justify-content: center;

    background: #edf4ff;

    color: #2878ff;

    border-radius: 8px;

    margin-right: 10px;

}


.bm-file-info {

    flex: 1;

    min-width: 0;

}


.bm-file-title {

    font-weight: 600;

    font-size: 13px;

    color: #303846;

}


.bm-file-name {

    color: #8a94a6;

    font-size: 10px;

    margin-top: 2px;

    white-space: nowrap;

    overflow: hidden;

    text-overflow: ellipsis;

}


.bm-file-arrow {

    color: #adb5bd;

    font-size: 11px;

}


/* =========================================================
   WORKSPACE
========================================================= */

.bm-workspace {

    display: grid;

    grid-template-columns:
        minmax(400px, 1fr)
        minmax(400px, 1fr);

    height: calc(100vh - 280px);

    min-height: 580px;

    border: 1px solid #dfe4ea;

    border-radius: 10px;

    overflow: hidden;

    background: #fff;

}


.bm-code-panel,
.bm-preview-panel {

    min-width: 0;

    min-height: 0;

    display: flex;

    flex-direction: column;

}


.bm-code-panel {

    border-right: 1px solid #dee2e6;

}


/* =========================================================
   PANEL HEADER
========================================================= */

.bm-panel-header {

    height: 48px;

    min-height: 48px;

    padding: 0 12px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    background: #f8f9fa;

    border-bottom: 1px solid #dee2e6;

}


.bm-panel-title {

    display: flex;

    align-items: center;

    gap: 8px;

    font-size: 13px;

    font-weight: 600;

    color: #3f4854;

}


.bm-panel-title i {

    color: #2878ff;

}


.bm-panel-actions {

    display: flex;

    gap: 4px;

}


/* =========================================================
   CODE TOOLBAR
========================================================= */

.bm-code-toolbar {

    height: 30px;

    min-height: 30px;

    padding: 0 10px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    background: #202124;

    color: #8b949e;

    font-size: 10px;

}


/* =========================================================
   CODE EDITOR
========================================================= */

.bm-code-wrapper {

    position: relative;

    flex: 1;

    min-height: 0;

    display: flex;

    overflow: hidden;

    background: #1e1e1e;

}


.bm-line-numbers {

    width: 52px;

    min-width: 52px;

    padding-top: 14px;

    padding-right: 10px;

    text-align: right;

    background: #181818;

    color: #5f6368;

    font-family:
        Consolas,
        Monaco,
        monospace;

    font-size: 12px;

    line-height: 20px;

    overflow: hidden;

    user-select: none;

}


.bm-line-numbers .active-line {

    display: block;

    width: 100%;

    background: #e8b900;

    color: #111;

    font-weight: bold;

    border-radius: 2px;

}


/* =========================================================
   AI LINE ACTION
========================================================= */

.bm-ai-line-button {

    position: absolute;

    z-index: 30;

    top: 10px;

    left: 5px;

    display: none;

    pointer-events: auto;

}


.bm-ai-line-button button {

    border-radius: 5px;

    padding: 2px 7px;

    font-size: 10px;

    line-height: 17px;

    box-shadow: 0 3px 10px rgba(0,0,0,.28);

}


.bm-ai-line-button button:hover {

    transform: translateY(-1px);

}


/* =========================================================
   AI MODAL
========================================================= */

.bm-ai-modal {

    border: 0;

    border-radius: 10px;

    overflow: hidden;

    box-shadow: 0 15px 45px rgba(0,0,0,.20);

}


.bm-ai-modal .modal-header {

    align-items: flex-start;

    border-bottom: 1px solid #edf0f3;

    padding: 15px 18px;

}


.bm-ai-modal-title {

    font-size: 15px;

    font-weight: 600;

    color: #343a40;

}


.bm-ai-modal-subtitle {

    margin-top: 3px;

    color: #8a94a6;

    font-size: 11px;

}


.bm-ai-modal .modal-body {

    padding: 18px;

}


.bm-ai-label {

    display: block;

    margin-bottom: 7px;

    font-size: 11px;

    font-weight: 600;

    color: #596273;

}


.bm-ai-prompt {

    resize: vertical;

    min-height: 130px;

    font-size: 12px;

    line-height: 1.6;

}


.bm-ai-hint {

    margin-top: 10px;

    padding: 8px 10px;

    border-radius: 6px;

    background: #f7f9fc;

    color: #7b8492;

    font-size: 10px;

    line-height: 1.5;

}


.bm-ai-modal .modal-footer {

    border-top: 1px solid #edf0f3;

    padding: 10px 18px;

}


#bladeEditor {

    flex: 1;

    min-width: 0;

    width: 100%;

    height: 100%;

    resize: none;

    border: 0;

    outline: 0;

    padding: 14px 15px;

    background: #1e1e1e;

    color: #d4d4d4;

    font-family:
        Consolas,
        Monaco,
        "Courier New",
        monospace;

    font-size: 13px;

    line-height: 20px;

    tab-size: 4;

    white-space: pre;

    overflow: auto;

}


/* =========================================================
   URL
========================================================= */

.bm-url-bar {

    height: 38px;

    min-height: 38px;

    display: flex;

    align-items: center;

    gap: 7px;

    padding: 0 10px;

    border-bottom: 1px solid #dee2e6;

    background: #fff;

    color: #8a94a6;

}


.bm-url-bar input {

    flex: 1;

    border: 0;

    outline: 0;

    background: transparent;

    font-size: 10px;

    color: #6c757d;

}


/* =========================================================
   IFRAME
========================================================= */

.bm-iframe-wrapper {

    position: relative;

    flex: 1;

    min-height: 0;

    overflow: auto;

    background: #eef0f2;

}


#previewFrame {

    display: block;

    width: 100%;

    min-width: 100%;

    height: 100%;

    min-height: 1000px;

    border: 0;

    background: #fff;

}


/* =========================================================
   LOADING
========================================================= */

.bm-loading {

    position: absolute;

    z-index: 20;

    top: 50%;

    left: 50%;

    transform: translate(-50%, -50%);

    display: flex;

    align-items: center;

    gap: 8px;

    padding: 9px 14px;

    border-radius: 7px;

    background: #fff;

    box-shadow:
        0 5px 20px rgba(0,0,0,.12);

    font-size: 11px;

    color: #6c757d;

}


/* =========================================================
   SELECTED
========================================================= */

.bm-selected {

    display: none;

    border-top: 1px solid #dee2e6;

    background: #fff;

}


.bm-selected-header {

    height: 38px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    padding: 0 10px;

    border-bottom: 1px solid #eee;

    font-size: 11px;

    font-weight: 600;

}


.bm-tag {

    background: #eef5ff;

    color: #2878ff;

    padding: 3px 7px;

    border-radius: 5px;

    font-family: monospace;

}


.bm-selected-body {

    display: grid;

    grid-template-columns:
        70px
        1fr
        70px
        1fr;

    gap: 7px 10px;

    padding: 9px 10px;

}


.bm-property {

    display: contents;

}


.bm-property label {

    font-size: 10px;

    color: #7b8492;

    align-self: center;

}


.bm-property input {

    min-width: 0;

    height: 27px;

    padding: 3px 7px;

    border: 1px solid #dee2e6;

    border-radius: 4px;

    font-size: 10px;

    color: #596273;

    background: #f8f9fa;

}


/* =========================================================
   FULLSCREEN
========================================================= */

.bm-workspace.bm-fullscreen {

    position: fixed;

    z-index: 9999;

    top: 0;

    left: 0;

    width: 100vw;

    height: 100vh;

    min-height: 100vh;

    border-radius: 0;

}


/* =========================================================
   MOBILE
========================================================= */

@media(max-width: 1000px) {

    .bm-workspace {

        grid-template-columns: 1fr;

        height: auto;

    }


    .bm-code-panel {

        min-height: 550px;

        border-right: 0;

        border-bottom: 1px solid #dee2e6;

    }


    .bm-preview-panel {

        min-height: 700px;

    }


    .bm-selected-body {

        grid-template-columns:
            60px
            1fr;

    }

}

</style>

<script>

(function () {

    'use strict';


    /* =====================================================
       VARIABLES
    ====================================================== */

    let currentFile = '';

    let currentUrl = '';

    let originalContent = '';

    let selectedSourceLine = 0;

    let aiTargetLine = 0;


    const editor =
        document.getElementById(
            'bladeEditor'
        );


    const iframe =
        document.getElementById(
            'previewFrame'
        );


    /* =====================================================
       UPDATE LINE NUMBERS
    ====================================================== */

    function updateLineNumbers(
        activeLine
    ) {

        const value =
            editor.value || '';


        const lines =
            value.split('\n').length;


        document.getElementById(
            'lineCount'
        ).innerText = lines;


        let html = '';


        for (
            let i = 1;
            i <= lines;
            i++
        ) {

            if (
                activeLine &&
                i === activeLine
            ) {

                html +=
                    '<span class="active-line">' +
                    i +
                    '</span>';

            } else {

                html +=
                    '<span>' +
                    i +
                    '</span>';

            }


            html += '<br>';

        }


        document.getElementById(
            'lineNumbers'
        ).innerHTML = html;

    }


    /* =====================================================
       SCROLL TO SOURCE LINE
    ====================================================== */

    function goToSourceLine(line) {

        if (!line || line < 1) {

            return;

        }


        selectedSourceLine =
            line;


        const lines =
            editor.value
                .substring(
                    0,
                    editor.value.length
                )
                .split('\n');


        if (
            line > lines.length
        ) {

            return;

        }


        let position = 0;


        for (
            let i = 0;
            i < line - 1;
            i++
        ) {

            position +=
                lines[i].length + 1;

        }


        editor.focus();


        editor.selectionStart =
            position;


        editor.selectionEnd =
            position;


        /*
         * Scroll
         */

        const lineHeight = 20;


        editor.scrollTop =
            Math.max(
                0,
                (line - 5) * lineHeight
            );


        updateLineNumbers(
            line
        );


        document.getElementById(
            'editorStatus'
        ).innerText =
            'Selected source line: ' +
            line;

    }


    /* =====================================================
       FIND SOURCE
    ====================================================== */

    function findSourceInEditor(data) {

        const code =
            editor.value || '';


        let index = -1;


        /*
         * 1. data-source-line
         */

        if (
            data.sourceLine
        ) {

            goToSourceLine(
                parseInt(
                    data.sourceLine
                )
            );

            return;

        }


        /*
         * 2. Cari class
         */

        if (
            data.className
        ) {

            const classes =
                String(
                    data.className
                )
                .split(/\s+/)
                .filter(Boolean);


            for (
                let i = 0;
                i < classes.length;
                i++
            ) {

                const cls =
                    classes[i];


                index =
                    code.indexOf(
                        cls
                    );


                if (index >= 0) {

                    break;

                }

            }

        }


        /*
         * 3. Cari text
         */

        if (
            index < 0 &&
            data.text
        ) {

            const text =
                String(
                    data.text
                ).trim();


            if (
                text.length >= 2
            ) {

                index =
                    code.indexOf(
                        text
                    );

            }

        }


        /*
         * 4. Cari tag
         */

        if (
            index < 0 &&
            data.tag
        ) {

            index =
                code.indexOf(
                    '<' +
                    data.tag
                );

        }


        if (
            index >= 0
        ) {

            /*
             * Hitung line
             */

            const before =
                code.substring(
                    0,
                    index
                );


            const line =
                before.split('\n').length;


            goToSourceLine(
                line
            );

        } else {

            document.getElementById(
                'editorStatus'
            ).innerText =
                'Source element tidak ditemukan';

        }

    }


    /* =====================================================
       SELECTED ELEMENT
    ====================================================== */

    function showSelectedElement(
        data
    ) {

        const panel =
            document.getElementById(
                'selectedElementPanel'
            );


        panel.style.display =
            'block';


        document.getElementById(
            'selectedTag'
        ).innerText =
            '<' +
            (data.tag || 'element') +
            '>';


        document.getElementById(
            'propTag'
        ).value =
            data.tag || '';


        document.getElementById(
            'propClass'
        ).value =
            data.className || '';


        document.getElementById(
            'propText'
        ).value =
            data.text || '';


        document.getElementById(
            'propLine'
        ).value =
            data.sourceLine ||
            '-';

    }


    /* =====================================================
       AI LINE HELPER
    ====================================================== */

    function getCursorLine() {

        if (!editor) {

            return 1;

        }


        const position =
            editor.selectionStart || 0;


        return editor.value
            .substring(0, position)
            .split('\n')
            .length;

    }


    function getLineStartPosition(line) {

        const lines =
            (editor.value || '').split('\n');

        let position = 0;

        for (let i = 0; i < line - 1 && i < lines.length; i++) {

            position += lines[i].length + 1;

        }

        return position;

    }


    function updateActiveCursorLine() {

        if (!currentFile) {

            document.getElementById('aiLineButton').style.display = 'none';

            return;

        }


        const line = getCursorLine();

        selectedSourceLine = line;

        updateLineNumbers(line);

        showAiLineButton(line);

    }


    function showAiLineButton(line) {

        const button =
            document.getElementById('aiLineButton');

        const wrapper =
            document.querySelector('.bm-code-wrapper');

        const lineHeight = 20;
        const topPadding = 14;

        if (!button || !wrapper || !line) {

            return;

        }


        const top =
            topPadding + ((line - 1) * lineHeight) - editor.scrollTop;

        const maxTop = wrapper.clientHeight - 30;

        button.style.top =
            Math.max(3, Math.min(top, maxTop)) + 'px';

        button.style.left = '5px';
        button.style.display = 'block';

    }


    function getLineContext(line) {

        const lines =
            (editor.value || '').split('\n');

        const index = Math.max(0, line - 1);

        const start =
            Math.max(0, index - 10);

        const end =
            Math.min(lines.length, index + 11);

        return {
            before: lines.slice(start, index).join('\n'),
            current: lines[index] || '',
            after: lines.slice(index + 1, end).join('\n')
        };

    }


    function openAiLineModal() {

        if (!currentFile) {

            alert('Pilih file terlebih dahulu.');
            return;

        }


        aiTargetLine = getCursorLine();
        selectedSourceLine = aiTargetLine;

        const info =
            document.getElementById('aiLineInfo');

        if (info) {

            info.innerText =
                'File: ' + currentFile + ' • Insert pada line ' + aiTargetLine;

        }


        const prompt =
            document.getElementById('aiPrompt');

        if (prompt) {

            prompt.value = '';
        }


        if (window.jQuery &&
            typeof window.jQuery.fn.modal === 'function') {

            window.jQuery('#aiLineModal').modal('show');

            setTimeout(function () {
                prompt && prompt.focus();
            }, 250);

        } else {

            const modal = document.getElementById('aiLineModal');

            modal.style.display = 'block';
            modal.classList.add('show');

            modal.removeAttribute('aria-hidden');

            setTimeout(function () {
                prompt && prompt.focus();
            }, 50);

        }

    }


    function closeAiLineModal() {

        if (window.jQuery &&
            typeof window.jQuery.fn.modal === 'function') {

            window.jQuery('#aiLineModal').modal('hide');
            return;

        }


        const modal = document.getElementById('aiLineModal');

        modal.style.display = 'none';
        modal.classList.remove('show');
        modal.setAttribute('aria-hidden', 'true');

    }


    function insertAiCode(line, code) {

        if (!code || !String(code).trim()) {

            throw new Error('AI tidak menghasilkan kode.');

        }


        const cleanCode =
            String(code)
                .replace(/^```(?:blade|php|html|javascript|js)?\s*/i, '')
                .replace(/\s*```$/i, '')
                .replace(/^\s*\n/, '')
                .replace(/\n\s*$/, '');


        const lines =
            editor.value.split('\n');

        const insertLines =
            cleanCode.split('\n');

        const insertIndex =
            Math.max(0, Math.min(lines.length, line - 1));

        lines.splice(insertIndex, 0, ...insertLines);

        editor.value = lines.join('\n');

        updateLineNumbers(line);

        const start =
            getLineStartPosition(line);

        editor.focus();

        editor.selectionStart = start;
        editor.selectionEnd =
            start + cleanCode.length;

        editor.scrollTop =
            Math.max(0, (line - 5) * 20);

        selectedSourceLine = line;

        document.getElementById('editorStatus').innerText =
            'AI code inserted pada line ' + line + ' • Unsaved changes';

        showAiLineButton(line);

    }


    function setAiButtonLoading(loading) {

        const button =
            document.getElementById('btnAiGenerate');

        if (!button) {
            return;
        }


        if (loading) {

            button.disabled = true;
            button.innerHTML =
                '<i class="fa fa-spinner fa-spin"></i> Generating...';

        } else {

            button.disabled = false;
            button.innerHTML =
                '<i class="fa fa-magic"></i> Generate & Insert';

        }

    }


    /* =====================================================
       IFRAME MESSAGE
    ====================================================== */

    window.addEventListener(
        'message',
        function (event) {

            if (
                !event.data ||
                event.data.type !==
                'blade-element-click'
            ) {

                return;

            }


            const data =
                event.data;


            console.log(
                'Iframe element:',
                data
            );


            /*
             * Tampilkan properties
             */

            showSelectedElement(
                data
            );


            /*
             * Cari source code
             */

            findSourceInEditor(
                data
            );

        }
    );


    /* =====================================================
       LOAD PREVIEW
    ====================================================== */

    function loadPreview(
        url
    ) {

        if (!url) {

            iframe.src =
                'about:blank';

            document.getElementById(
                'previewUrl'
            ).value = '';

            return;

        }


        currentUrl =
            url;


        document.getElementById(
            'previewUrl'
        ).value =
            url;


        document.getElementById(
            'iframeLoading'
        ).style.display =
            'flex';


        iframe.src =
            url;

    }


    /* =====================================================
       IFRAME LOADED
    ====================================================== */

    iframe.addEventListener(
        'load',
        function () {

            document.getElementById(
                'iframeLoading'
            ).style.display =
                'none';

        }
    );


    /* =====================================================
       LOAD FILE CONTENT
    ====================================================== */

    function loadFileContent(
        file
    ) {

        if (!file) {

            editor.value = '';

            updateLineNumbers();

            return;

        }


        document.getElementById(
            'editorStatus'
        ).innerText =
            'Loading...';


        fetch(
            '{{ url("masterkonten/content") }}' +
            '?file=' +
            encodeURIComponent(
                file
            )
        )

        .then(function (response) {

            if (!response.ok) {

                throw new Error(
                    'Gagal membaca file'
                );

            }


            return response.json();

        })

        .then(function (result) {

            if (!result.success) {

                throw new Error(
                    result.message ||
                    'Gagal membaca file'
                );

            }


            originalContent =
                result.content || '';


            editor.value =
                originalContent;


            updateLineNumbers();


            document.getElementById(
                'editorStatus'
            ).innerText =
                'Loaded';

        })

        .catch(function (error) {

            console.error(
                error
            );


            document.getElementById(
                'editorStatus'
            ).innerText =
                'Error: ' +
                error.message;

        });

    }


    /* =====================================================
       FILE SELECT
    ====================================================== */

    document.querySelectorAll(
        '.bm-file'
    ).forEach(function (button) {

        button.addEventListener(
            'click',
            function () {

                document.querySelectorAll(
                    '.bm-file'
                ).forEach(function (item) {

                    item.classList.remove(
                        'active'
                    );

                });


                this.classList.add(
                    'active'
                );


                currentFile =
                    this.dataset.file || '';


                currentUrl =
                    this.dataset.url || '';


                document.getElementById(
                    'currentFile'
                ).innerText =
                    currentFile ||
                    'File tidak tersedia';


                /*
                 * Reset selected
                 */

                document.getElementById(
                    'selectedElementPanel'
                ).style.display =
                    'none';


                /*
                 * Load code
                 */

                loadFileContent(
                    currentFile
                );


                /*
                 * Load preview
                 */

                loadPreview(
                    currentUrl
                );

            }
        );

    });


    /* =====================================================
       EDITOR INPUT
    ====================================================== */

    editor.addEventListener(
        'input',
        function () {

            const line = getCursorLine();

            selectedSourceLine = line;

            updateLineNumbers(line);
            showAiLineButton(line);

            document.getElementById(
                'editorStatus'
            ).innerText =
                'Unsaved changes';

        }
    );


    editor.addEventListener(
        'click',
        function () {

            updateActiveCursorLine();

        }
    );


    editor.addEventListener(
        'keyup',
        function (event) {

            if (event.key !== 'Control' &&
                event.key !== 'Meta' &&
                event.key !== 'Alt' &&
                event.key !== 'Shift') {

                updateActiveCursorLine();

            }

        }
    );


    /* =====================================================
       CTRL + S
    ====================================================== */

    editor.addEventListener(
        'keydown',
        function (event) {

            if (
                (event.ctrlKey ||
                 event.metaKey) &&
                event.key.toLowerCase() === 's'
            ) {

                event.preventDefault();

                document.getElementById(
                    'btnSave'
                ).click();

            }


            /*
             * TAB
             */

            if (
                event.key === 'Tab'
            ) {

                event.preventDefault();


                const start =
                    this.selectionStart;


                const end =
                    this.selectionEnd;


                this.value =
                    this.value.substring(
                        0,
                        start
                    ) +
                    '    ' +
                    this.value.substring(
                        end
                    );


                this.selectionStart =
                    this.selectionEnd =
                    start + 4;


                updateLineNumbers(
                    selectedSourceLine
                );

            }

        }
    );


    /* =====================================================
       EDITOR SCROLL
    ====================================================== */

    editor.addEventListener(
        'scroll',
        function () {

            document.getElementById(
                'lineNumbers'
            ).scrollTop =
                this.scrollTop;

            showAiLineButton(getCursorLine());

        }
    );


    /* =====================================================
       AI INSERT
    ====================================================== */

    document.getElementById('btnAiLine')
        .addEventListener('click', function (event) {

            event.preventDefault();
            event.stopPropagation();

            openAiLineModal();

        });


    document.getElementById('btnAiGenerate')
        .addEventListener('click', function () {

            const promptElement =
                document.getElementById('aiPrompt');

            const prompt =
                promptElement.value.trim();

            if (!prompt) {

                alert('Masukkan instruksi untuk AI terlebih dahulu.');
                promptElement.focus();
                return;

            }

            if (!currentFile) {

                alert('Pilih file terlebih dahulu.');
                return;

            }

            aiTargetLine =
                aiTargetLine || getCursorLine();

            const context =
                getLineContext(aiTargetLine);

            setAiButtonLoading(true);

            document.getElementById('editorStatus').innerText =
                'AI sedang membuat kode...';

            fetch(
                '{{ url("masterkonten?action_task=generateAiEditor") }}',
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN':
                            document
                                .querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                    },
                    body: JSON.stringify({
                        file: currentFile.replace('.blade.php', ''),
                        line: aiTargetLine,
                        prompt: prompt,
                        before: context.before,
                        current: context.current,
                        after: context.after,
                        full_content: editor.value
                    })
                }
            )
            .then(function (response) {

                return response.json().then(function (result) {

                    if (!response.ok || !result.success) {

                        throw new Error(
                            result.message ||
                            'Gagal generate kode dengan AI.'
                        );

                    }

                    return result;

                });

            })
            .then(function (result) {

                insertAiCode(
                    aiTargetLine,
                    result.code || ''
                );

                closeAiLineModal();

            })
            .catch(function (error) {

                console.error(error);

                document.getElementById('editorStatus').innerText =
                    'AI error: ' + error.message;

                alert(error.message);

            })
            .finally(function () {

                setAiButtonLoading(false);

            });

        });


    document.getElementById('aiPrompt')
        .addEventListener('keydown', function (event) {

            if ((event.ctrlKey || event.metaKey) &&
                event.key === 'Enter') {

                event.preventDefault();
                document.getElementById('btnAiGenerate').click();

            }

        });


    /* =====================================================
       COPY
    ====================================================== */

    document.getElementById(
        'btnCopy'
    ).addEventListener(
        'click',
        function () {

            navigator.clipboard
                .writeText(
                    editor.value
                )
                .then(function () {

                    document.getElementById(
                        'editorStatus'
                    ).innerText =
                        'Code copied';

                });

        }
    );


    /* =====================================================
       SAVE
    ====================================================== */

    document.getElementById(
        'btnSave'
    ).addEventListener(
        'click',
        function () {

            if (!currentFile) {

                alert(
                    'Pilih file terlebih dahulu.'
                );

                return;

            }


            document.getElementById(
                'editorStatus'
            ).innerText =
                'Saving...';


            fetch(
                '{{ url("masterkonten?action_task=savecontent") }}',
                {

                    method: 'POST',

                    headers: {

                        'Content-Type':
                            'application/json',

                        'X-CSRF-TOKEN':
                            document
                            .querySelector(
                                'meta[name="csrf-token"]'
                            )
                            .getAttribute(
                                'content'
                            )

                    },

                    body: JSON.stringify({

                        file:
                            currentFile.replace('.blade.php', ''),

                        content:
                            editor.value

                    })

                }
            )

            .then(function (response) {

                if (!response.ok) {

                    throw new Error(
                        'HTTP ' +
                        response.status
                    );

                }


                return response.json();

            })

            .then(function (result) {

                if (!result.success) {

                    throw new Error(
                        result.message ||
                        'Gagal menyimpan'
                    );

                }


                originalContent =
                    editor.value;


                document.getElementById(
                    'editorStatus'
                ).innerText =
                    'Saved successfully';


                /*
                 * Refresh preview
                 */

                if (currentUrl) {

                    const separator =
                        currentUrl.indexOf('?') >= 0
                            ? '&'
                            : '?';


                    iframe.src =
                        currentUrl +
                        separator +
                        '_preview=' +
                        Date.now();

                }

            })

            .catch(function (error) {

                console.error(
                    error
                );


                document.getElementById(
                    'editorStatus'
                ).innerText =
                    'Save error: ' +
                    error.message;

            });

        }
    );


    /* =====================================================
       REFRESH PREVIEW
    ====================================================== */

    document.getElementById(
        'btnPreviewRefresh'
    ).addEventListener(
        'click',
        function () {

            if (!currentUrl) {

                return;

            }


            const separator =
                currentUrl.indexOf('?') >= 0
                    ? '&'
                    : '?';


            iframe.src =
                currentUrl +
                separator +
                '_preview=' +
                Date.now();

        }
    );


    /* =====================================================
       EDITOR FULLSCREEN
    ====================================================== */

    document.getElementById(
        'btnEditorFullscreen'
    ).addEventListener(
        'click',
        function () {

            document.getElementById(
                'bmWorkspace'
            ).classList.toggle(
                'bm-fullscreen'
            );

        }
    );


    /* =====================================================
       PREVIEW FULLSCREEN
    ====================================================== */

    document.getElementById(
        'btnPreviewFullscreen'
    ).addEventListener(
        'click',
        function () {

            const workspace =
                document.getElementById(
                    'bmWorkspace'
                );


            workspace.classList.toggle(
                'bm-fullscreen'
            );

        }
    );


    /* =====================================================
       INITIAL
    ====================================================== */

    updateLineNumbers();

    document.getElementById('aiLineButton').style.display = 'none';

})();

</script>

@stop
