<?php
$menuConfig = $menuConfig ?? MenuConfig::getDefault();
$menuItems = $menuConfig['items'] ?? [];
$allPages = $allPages ?? [];
$menuSearch = ($settings['menu_search'] ?? '1') === '1';
$hasMultiLang = !empty($menuLanguages ?? null) && count($menuLanguages) >= 2;
if ($hasMultiLang) {
    foreach ($menuLanguages as &$_ml) {
        $_ml['flag'] = Translator::flagCode($_ml['code']);
    }
    unset($_ml);
}
?>

<style>
 
.mb { display: grid; grid-template-columns: 300px 1fr; gap: 16px; align-items: start; }
@media (max-width: 960px) { .mb { grid-template-columns: 1fr; } }

 
.mb-side { position: sticky; top: 80px; display: flex; flex-direction: column; gap: 10px; }
.mb-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; overflow: hidden; }
.mb-card__hd {
    display: flex; align-items: center; justify-content: space-between;
    padding: 11px 14px; cursor: pointer; user-select: none;
    font-size: 13px; font-weight: 600; color: #374151; transition: background 0.1s;
}
.mb-card__hd:hover { background: #f9fafb; }
.mb-card__hd i.chev { font-size: 11px; color: #9ca3af; transition: transform 0.2s; }
.mb-card__hd[aria-expanded="true"] i.chev { transform: rotate(180deg); }
.mb-card__hd[aria-expanded="true"] { border-bottom: 1px solid #f3f4f6; }
.mb-card__bd { padding: 12px 14px; }
.mb-card__bd[hidden] { display: none; }
.mb-opt { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 6px; font-size: 13px; color: #374151; cursor: pointer; transition: background 0.1s; }
.mb-opt:hover { background: #f3f4f6; }
.mb-opt input[type="checkbox"] { width: 15px; height: 15px; accent-color: #4f46e5; cursor: pointer; }
.mb-opt i.fa-solid, .mb-opt i.fa-brands { width: 16px; text-align: center; font-size: 13px; color: #6b7280; }
.mb-btn {
    display: flex; align-items: center; justify-content: center; gap: 5px;
    width: 100%; margin-top: 8px; padding: 7px 12px;
    background: #4f46e5; color: #fff; border: none; border-radius: 7px;
    font-size: 12px; font-weight: 600; cursor: pointer; transition: background 0.12s;
}
.mb-btn:hover { background: #4338ca; }
.mb-btn:active { transform: scale(0.98); }
.mb-inp {
    width: 100%; padding: 7px 10px; border: 1px solid #d1d5db; border-radius: 7px;
    font-size: 13px; outline: none; transition: border-color 0.12s, box-shadow 0.12s;
}
.mb-inp:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79,70,229,0.08); }
.mb-inp + .mb-inp { margin-top: 6px; }
.mb-chk { display: flex; align-items: center; gap: 7px; margin-top: 6px; font-size: 12px; color: #6b7280; cursor: pointer; }
.mb-chk input { width: 14px; height: 14px; accent-color: #4f46e5; cursor: pointer; }

 
.mb-search-card {
    display: flex; align-items: center; gap: 10px; padding: 12px 14px;
    background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; cursor: pointer;
}
.mb-search-card input { width: 16px; height: 16px; accent-color: #4f46e5; cursor: pointer; }
.mb-search-card__txt { flex: 1; }
.mb-search-card__lbl { font-size: 13px; font-weight: 600; color: #374151; }
.mb-search-card__desc { font-size: 11px; color: #9ca3af; }

 
.mb-panel { background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; }
.mb-panel__hd { padding: 14px 18px; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; }
.mb-panel__title { font-size: 14px; font-weight: 600; color: #111827; }
.mb-panel__count { font-size: 11px; font-weight: 700; background: #e5e7eb; color: #6b7280; padding: 2px 8px; border-radius: 10px; }
.mb-panel__bd { padding: 14px; }

 
.mb-zone { min-height: 60px; border: 2px dashed #e5e7eb; border-radius: 10px; padding: 6px; transition: border-color 0.2s, background 0.2s; }
.mb-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px 16px; color: #b0b8c4; }
.mb-empty i { font-size: 28px; margin-bottom: 8px; opacity: 0.3; }
.mb-empty span { font-size: 13px; }
.mb-empty small { font-size: 11px; margin-top: 2px; opacity: 0.7; }

 
.mi { margin-bottom: 3px; }
.mi-row {
    display: flex; align-items: center; gap: 7px;
    padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb;
    border-radius: 8px; transition: all 0.12s; min-height: 40px; flex-wrap: wrap;
}
.mi-row:hover { border-color: #c7d2fe; background: #fafafe; }
.mi-row.editing { border-color: #818cf8; background: #fefefe; box-shadow: 0 1px 4px rgba(79,70,229,0.08); }
.mi-handle { cursor: grab; color: #d1d5db; display: flex; flex-shrink: 0; padding: 2px; transition: color 0.1s; }
.mi-handle:hover { color: #818cf8; }
.mi-handle:active { cursor: grabbing; }
.mi-icon-btn {
    width: 28px; height: 28px; display: flex; align-items: center; justify-content: center;
    border-radius: 6px; flex-shrink: 0; cursor: pointer; border: 1px dashed #d1d5db;
    background: #fff; color: #9ca3af; font-size: 13px; transition: all 0.12s;
}
.mi-icon-btn:hover { border-color: #818cf8; color: #6366f1; background: #eef2ff; }
.mi-icon-btn.has-icon { border-style: solid; background: #eef2ff; color: #4f46e5; border-color: #c7d2fe; }
.mi-label { flex: 1; font-size: 13px; font-weight: 500; color: #1f2937; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.mi-badge { font-size: 10px; font-weight: 700; text-transform: uppercase; padding: 1px 6px; border-radius: 4px; flex-shrink: 0; letter-spacing: 0.02em; }
.mi-badge--internal { background: #dbeafe; color: #1d4ed8; }
.mi-badge--page { background: #d1fae5; color: #047857; }
.mi-badge--custom { background: #ede9fe; color: #7c3aed; }
.mi-actions { display: flex; gap: 1px; flex-shrink: 0; opacity: 0; transition: opacity 0.12s; }
.mi-row:hover .mi-actions, .mi-row.editing .mi-actions { opacity: 1; }
.mi-act {
    width: 26px; height: 26px; display: flex; align-items: center; justify-content: center;
    background: none; border: none; border-radius: 5px; cursor: pointer; color: #9ca3af; font-size: 12px; transition: all 0.1s;
}
.mi-act--edit:hover { color: #4f46e5; background: #eef2ff; }
.mi-act--del:hover { color: #dc2626; background: #fef2f2; }
.mi-act--indent:hover { color: #059669; background: #ecfdf5; }
.mi-act--outdent:hover { color: #d97706; background: #fffbeb; }
.mi-act[disabled] { opacity: 0.2; pointer-events: none; }
.mi-act .fa-right-long, .mi-act .fa-left-long { font-size: 11px; }

 
.mi-edit-inline {
    display: none; width: 100%; padding: 8px 0 4px 0;
    margin-top: 6px; border-top: 1px dashed #e5e7eb;
}
.mi-edit-inline.open { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.mi-ef { display: flex; align-items: center; gap: 6px; }
.mi-ef-lbl { font-size: 11px; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: 0.03em; }
.mi-ef input[type="text"] {
    width: 180px; padding: 5px 9px; border: 1px solid #d1d5db; border-radius: 6px;
    font-size: 12px; outline: none; transition: border-color 0.12s;
}
.mi-ef input[type="text"]:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79,70,229,0.06); }
.mi-ef-chk { display: flex; align-items: center; gap: 5px; font-size: 11px; color: #6b7280; cursor: pointer; }
.mi-ef-chk input { width: 13px; height: 13px; accent-color: #4f46e5; }
.mi-ef-done {
    padding: 4px 12px; background: #4f46e5; color: #fff; border: none; border-radius: 5px;
    font-size: 11px; font-weight: 600; cursor: pointer; transition: background 0.1s; margin-left: auto;
}
.mi-ef-done:hover { background: #4338ca; }

 
.mi-children { margin-left: 34px; min-height: 0; padding: 2px 0; border-left: 2px solid transparent; transition: border-color 0.15s; }
.mi-children.has-kids { border-left-color: #e5e7eb; padding-left: 8px; margin-top: 1px; }
.mi-children .mi-row { background: #fff; border-style: dashed; }
.mi-children .mi-children { display: none; }

 
.sortable-ghost { opacity: 0.3; }
.sortable-ghost .mi-row { border: 2px dashed #818cf8; background: #eef2ff; }
.sortable-drag .mi-row { box-shadow: 0 8px 24px rgba(0,0,0,0.12); border-color: #818cf8; transform: rotate(0.5deg); }
.sortable-chosen .mi-row { border-color: #a5b4fc; }

 
.ip-overlay {
    display: none; position: fixed; inset: 0; z-index: 9999;
    background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
    align-items: center; justify-content: center;
}
.ip-overlay.open { display: flex; }
.ip-modal {
    background: #fff; border-radius: 14px; width: 900px; max-width: 95vw;
    max-height: 85vh; display: flex; flex-direction: column;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2); animation: ipIn 0.2s ease;
}
@keyframes ipIn { from { opacity: 0; transform: scale(0.96) translateY(8px); } to { opacity: 1; transform: none; } }
.ip-hd {
    display: flex; align-items: center; gap: 10px; padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb; flex-shrink: 0;
}
.ip-hd__title { font-size: 15px; font-weight: 600; color: #111827; flex: 1; }
.ip-hd__close {
    width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;
    border: none; background: #f3f4f6; border-radius: 8px; cursor: pointer; color: #6b7280; font-size: 14px;
}
.ip-hd__close:hover { background: #e5e7eb; color: #111; }
.ip-toolbar {
    display: flex; align-items: center; gap: 10px; padding: 12px 20px;
    border-bottom: 1px solid #f3f4f6; flex-shrink: 0; flex-wrap: wrap;
}
.ip-search-wrap { position: relative; flex: 1; min-width: 180px; }
.ip-search-wrap i { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: #9ca3af; font-size: 13px; pointer-events: none; }
.ip-search {
    width: 100%; padding: 8px 12px 8px 34px;
    border: 1px solid #d1d5db; border-radius: 8px; font-size: 13px;
    outline: none; transition: border-color 0.12s;
}
.ip-search:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79,70,229,0.08); }
.ip-styles { display: flex; gap: 4px; flex-shrink: 0; }
.ip-style-btn {
    padding: 5px 12px; border: 1px solid #e5e7eb; border-radius: 6px;
    font-size: 12px; font-weight: 600; cursor: pointer; background: #fff; color: #6b7280; transition: all 0.1s;
}
.ip-style-btn:hover { border-color: #c7d2fe; color: #4f46e5; }
.ip-style-btn.active { background: #4f46e5; color: #fff; border-color: #4f46e5; }
.ip-count { font-size: 11px; color: #9ca3af; flex-shrink: 0; white-space: nowrap; }
.ip-grid {
    display: grid; grid-template-columns: repeat(auto-fill, minmax(58px, 1fr));
    gap: 4px; padding: 14px 20px 20px; overflow-y: auto; flex: 1;
}
.ip-icon {
    display: flex; align-items: center; justify-content: center; aspect-ratio: 1;
    border-radius: 8px; cursor: pointer; color: #4b5563; font-size: 20px;
    transition: all 0.1s; border: 2px solid transparent;
}
.ip-icon:hover { background: #eef2ff; color: #4f46e5; border-color: #c7d2fe; }
.ip-icon.selected { background: #4f46e5; color: #fff; border-color: #4f46e5; }
.ip-empty { grid-column: 1 / -1; text-align: center; padding: 32px; color: #9ca3af; font-size: 13px; }
.ip-footer {
    display: flex; align-items: center; justify-content: space-between; gap: 10px;
    padding: 12px 20px; border-top: 1px solid #e5e7eb; flex-shrink: 0;
}
.ip-footer__sel { font-size: 13px; color: #6b7280; display: flex; align-items: center; gap: 8px; }
.ip-footer__sel i { font-size: 20px; color: #4f46e5; }
.ip-footer__actions { display: flex; gap: 6px; }
.ip-btn { padding: 7px 16px; border-radius: 7px; font-size: 12px; font-weight: 600; cursor: pointer; border: none; transition: all 0.1s; }
.ip-btn--ghost { background: #f3f4f6; color: #6b7280; }
.ip-btn--ghost:hover { background: #e5e7eb; }
.ip-btn--primary { background: #4f46e5; color: #fff; }
.ip-btn--primary:hover { background: #4338ca; }
.ip-btn--danger { background: none; color: #dc2626; font-weight: 500; padding: 7px 10px; }
.ip-btn--danger:hover { background: #fef2f2; }
 
.mi-tl-btn {
    width: 26px; height: 26px; display: flex; align-items: center; justify-content: center;
    border-radius: 6px; border: 1px dashed #d1d5db; background: #fff; color: #9ca3af;
    cursor: pointer; transition: all 0.12s; flex-shrink: 0; padding: 0;
}
.mi-tl-btn:hover { border-color: #818cf8; color: #6366f1; background: #eef2ff; }
.mi-tl-btn--active { border-style: solid; border-color: #c7d2fe; background: #eef2ff; color: #4f46e5; }
@keyframes miIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }

 
@media (max-width: 960px) {
    .mb-side { position: static; }
}
@media (max-width: 639px) {
    .mb { gap: 10px; }
     
    .mi-ef input[type="text"] { width: 100%; min-width: 0; }
    .mi-edit-inline.open { flex-direction: column; align-items: stretch; }
    .mi-ef { width: 100%; }
    .mi-ef-done { margin-left: 0; width: 100%; justify-content: center; display: flex; align-items: center; gap: 4px; }
     
    .mi-children.has-kids { margin-left: 18px; padding-left: 6px; }
     
    .mi-actions { opacity: 1; }
     
    .mi-row { padding: 6px 8px; gap: 5px; font-size: 12px; }
    .mi-label { font-size: 12px; }
    .mi-badge { font-size: 9px; padding: 1px 5px; }
    .mi-act { width: 24px; height: 24px; font-size: 11px; }
     
    .mb-card__hd { padding: 9px 10px; font-size: 12px; }
    .mb-card__bd { padding: 10px; }
    .mb-panel__hd { padding: 10px 12px; }
    .mb-panel__title { font-size: 13px; }
    .mb-panel__bd { padding: 10px; }
    .mb-zone { padding: 4px; }
     
    .mb-opt { padding: 5px 6px; font-size: 12px; gap: 6px; }
    .mb-btn { padding: 6px 10px; font-size: 11px; }
    .mb-inp { padding: 6px 8px; font-size: 12px; }
     
    .ip-footer { flex-wrap: wrap; }
    .ip-footer__actions { width: 100%; justify-content: flex-end; }
    .ip-styles { overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .ip-hd, .ip-toolbar, .ip-footer { padding-left: 12px; padding-right: 12px; }
    .ip-grid { padding: 10px 12px 14px; }
}
@media (max-width: 479px) {
    .mi-icon-btn { width: 24px; height: 24px; font-size: 11px; }
    .mi-children.has-kids { margin-left: 12px; padding-left: 4px; }
    .ip-grid { grid-template-columns: repeat(auto-fill, minmax(46px, 1fr)); }
}
</style>

<form method="POST" action="/admin/appearance" id="menuForm">
    <?= Router::csrfField() ?>
    <input type="hidden" name="_tab" value="appearance">
    <input type="hidden" name="_sub" value="menu">
    <input type="hidden" name="menu_json" id="menuJson" value="">

    <?php HookSystem::doAction('admin.menu_extra', $settings ?? []); ?>

    <div class="mb">

        
        <div class="mb-side">

            
            <div class="mb-card">
                <div class="mb-card__hd" aria-expanded="true" onclick="mbToggle(this)">
                    <span><i class="fa-solid fa-link" style="margin-right:6px;font-size:12px;opacity:.5;"></i> Internal Links</span>
                    <i class="fa-solid fa-chevron-down chev"></i>
                </div>
                <div class="mb-card__bd">
                    <?php
                    $internals = [
                        'home'            => ['label' => 'Home',            'fa' => 'fa-house'],
                        'categories'      => ['label' => 'Categories',      'fa' => 'fa-grid-2'],
                        'tags'            => ['label' => 'Tags',            'fa' => 'fa-tags'],
                        'pornstars'       => ['label' => 'Pornstars',       'fa' => 'fa-users'],
                        'channels'         => ['label' => 'Channels',         'fa' => 'fa-clapperboard'],
                        'albums'           => ['label' => 'Albums',           'fa' => 'fa-images'],
                        'new_videos'      => ['label' => 'New Videos',      'fa' => 'fa-sparkles'],
                        'top_rated'       => ['label' => 'Top Rated',       'fa' => 'fa-star'],
                        'most_viewed'     => ['label' => 'Most Viewed',     'fa' => 'fa-eye'],
                        'most_favorited'  => ['label' => 'Most Favorited',  'fa' => 'fa-heart'],
                    ];
                    if (!empty($hasMultipleVideoTypes)) {
                        $internals['vtype_switcher'] = ['label' => 'Video Type Switcher', 'fa' => 'fa-shuffle'];
                    }
                    foreach ($internals as $iKey => $iInfo): ?>
                    <label class="mb-opt">
                        <input type="checkbox" value="<?= $iKey ?>" class="add-internal" data-fa="<?= $iInfo['fa'] ?>">
                        <i class="fa-solid <?= $iInfo['fa'] ?>"></i>
                        <span><?= $iInfo['label'] ?></span>
                    </label>
                    <?php endforeach; ?>
                    <button type="button" id="btnAddInternal" class="mb-btn"><i class="fa-solid fa-plus" style="font-size:11px;"></i> Add selected</button>
                </div>
            </div>

            
            <?php if (!empty($allPages)): ?>
            <div class="mb-card">
                <div class="mb-card__hd" aria-expanded="false" onclick="mbToggle(this)">
                    <span><i class="fa-solid fa-file-lines" style="margin-right:6px;font-size:12px;opacity:.5;"></i> Pages</span>
                    <i class="fa-solid fa-chevron-down chev"></i>
                </div>
                <div class="mb-card__bd" hidden>
                    <?php foreach ($allPages as $pg): ?>
                    <label class="mb-opt">
                        <input type="checkbox" value="<?= (int)$pg['id'] ?>" data-label="<?= htmlspecialchars($pg['title']) ?>" data-slug="<?= htmlspecialchars($pg['slug']) ?>" class="add-page">
                        <i class="fa-solid fa-file-lines"></i>
                        <span><?= htmlspecialchars($pg['title']) ?></span>
                    </label>
                    <?php endforeach; ?>
                    <button type="button" id="btnAddPages" class="mb-btn"><i class="fa-solid fa-plus" style="font-size:11px;"></i> Add selected</button>
                </div>
            </div>
            <?php endif; ?>

            
            <div class="mb-card">
                <div class="mb-card__hd" aria-expanded="false" onclick="mbToggle(this)">
                    <span><i class="fa-solid fa-arrow-up-right-from-square" style="margin-right:6px;font-size:12px;opacity:.5;"></i> Custom Link</span>
                    <i class="fa-solid fa-chevron-down chev"></i>
                </div>
                <div class="mb-card__bd" hidden>
                    <input type="text" id="customUrl" placeholder="https://..." class="mb-inp">
                    <input type="text" id="customLabel" placeholder="Link label" class="mb-inp">
                    <label class="mb-chk"><input type="checkbox" id="customBlank"> Open in new tab</label>
                    <button type="button" id="btnAddCustom" class="mb-btn"><i class="fa-solid fa-plus" style="font-size:11px;"></i> Add to menu</button>
                </div>
            </div>

            
            <label class="mb-search-card">
                <input type="checkbox" name="menu_search" value="1" <?php if ($menuSearch): ?>checked<?php endif; ?>>
                <div class="mb-search-card__txt">
                    <div class="mb-search-card__lbl"><i class="fa-solid fa-magnifying-glass" style="font-size:11px;opacity:.5;margin-right:4px;"></i> Search bar</div>
                    <div class="mb-search-card__desc">Show in header navigation</div>
                </div>
            </label>

        </div>

        
        <div class="mb-panel">
            <div class="mb-panel__hd">
                <span class="mb-panel__title">Menu Structure</span>
                <span class="mb-panel__count" id="menuCount">0</span>
            </div>
            <div class="mb-panel__bd">
                <div id="menuList" class="mb-zone">
                    <div class="mb-empty" id="menuEmpty">
                        <i class="fa-solid fa-bars-staggered"></i>
                        <span>No menu items yet</span>
                        <small>Add items from the left panel</small>
                    </div>
                </div>
                <p style="font-size:11px;color:#b0b8c4;margin-top:10px;line-height:1.5;">
                    <i class="fa-solid fa-grip-dots-vertical" style="opacity:.5;"></i> Drag to reorder
                    &middot; <i class="fa-solid fa-right-long" style="opacity:.5;font-size:10px;"></i> Indent / <i class="fa-solid fa-left-long" style="opacity:.5;font-size:10px;"></i> Outdent for sub-menus
                    &middot; Click icon for picker
                </p>
            </div>
        </div>
    </div>

    <div class="mt-6">
        <button type="submit" class="inline-flex items-center px-5 py-2.5 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors shadow-sm">
            <i class="fa-solid fa-check" style="margin-right:6px;font-size:12px;"></i> Save changes
        </button>
    </div>
</form>


<div class="ip-overlay" id="iconPicker">
    <div class="ip-modal">
        <div class="ip-hd">
            <span class="ip-hd__title">Choose an icon</span>
            <button type="button" class="ip-hd__close" onclick="ipClose()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="ip-toolbar">
            <div class="ip-search-wrap">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" class="ip-search" id="ipSearch" placeholder="Search icons..." autocomplete="off">
            </div>
            <div class="ip-styles" id="ipStyles">
                <button type="button" class="ip-style-btn active" data-style="solid">Solid</button>
                <button type="button" class="ip-style-btn" data-style="regular">Regular</button>
                <button type="button" class="ip-style-btn" data-style="light">Light</button>
                <button type="button" class="ip-style-btn" data-style="thin">Thin</button>
                <button type="button" class="ip-style-btn" data-style="brands">Brands</button>
            </div>
            <span class="ip-count" id="ipCount"></span>
        </div>
        <div class="ip-grid" id="ipGrid"></div>
        <div class="ip-footer">
            <div class="ip-footer__sel" id="ipSelected">
                <span>No icon selected</span>
            </div>
            <div class="ip-footer__actions">
                <button type="button" class="ip-btn ip-btn--danger" id="ipRemoveBtn" style="display:none;" onclick="ipRemove()">Remove icon</button>
                <button type="button" class="ip-btn ip-btn--ghost" onclick="ipClose()">Cancel</button>
                <button type="button" class="ip-btn ip-btn--primary" onclick="ipConfirm()">Select</button>
            </div>
        </div>
    </div>
</div>

<?php if ($hasMultiLang): ?>

<style>
.mt-overlay{display:none;position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.5);backdrop-filter:blur(2px);align-items:center;justify-content:center}
.mt-overlay.open{display:flex}
.mt-modal{background:#fff;border-radius:14px;width:480px;max-width:95vw;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,.2);animation:mtIn .2s ease}
@keyframes mtIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
.mt-modal__header{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid #e5e7eb;flex-shrink:0}
.mt-modal__title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:#111827}
.mt-modal__close{width:28px;height:28px;display:flex;align-items:center;justify-content:center;border:none;background:#f3f4f6;border-radius:7px;cursor:pointer;color:#6b7280}
.mt-modal__close:hover{background:#e5e7eb;color:#111}
.mt-modal__body{padding:12px 18px;overflow-y:auto;flex:1}
.mt-lang-row{padding:10px 0;border-bottom:1px solid #f3f4f6}
.mt-lang-row:last-child{border-bottom:none}
.mt-lang-row__label{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.mt-lang-row__name{font-size:13px;font-weight:600;color:#374151}
.mt-lang-row__badge{font-size:10px;font-weight:600;color:#6366f1;background:#eef2ff;padding:1px 6px;border-radius:4px}
.mt-lang-row__note{font-size:12px;color:#9ca3af;font-style:italic}
.mt-lang-row__input{width:100%;padding:7px 10px;border:1px solid #d1d5db;border-radius:7px;font-size:13px;outline:none;transition:border-color .12s;box-sizing:border-box}
.mt-lang-row__input:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.08)}
.mt-modal__footer{display:flex;justify-content:flex-end;padding:12px 18px;border-top:1px solid #e5e7eb;flex-shrink:0}
.mt-modal__done{padding:7px 18px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;border:none;background:#4f46e5;color:#fff;transition:background .12s}
.mt-modal__done:hover{background:#4338ca}
</style>
<div class="mt-overlay" id="translateModal">
    <div class="mt-modal">
        <div class="mt-modal__header">
            <div class="mt-modal__title">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;color:#6366f1;"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                <span>Translate label</span>
            </div>
            <button type="button" class="mt-modal__close" onclick="tlClose()">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
        </div>
        <div class="mt-modal__body" id="tlBody"></div>
        <div class="mt-modal__footer">
            <button type="button" onclick="tlDone()" class="mt-modal__done">Done</button>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>
<script>
(function() {
    var menuList = document.getElementById('menuList');
    var menuForm = document.getElementById('menuForm');
    var menuJsonInput = document.getElementById('menuJson');
    var emptyMsg = document.getElementById('menuEmpty');
    var countBadge = document.getElementById('menuCount');

    var internalUrls = { home:'/', categories:'/categories', tags:'/tags', pornstars:'/pornstars', channels:'/channels', new_videos:'/videos/new', top_rated:'/videos/top-rated', most_viewed:'/videos/most-viewed', most_favorited:'/videos/most-favorited', vtype_switcher:'#' };
    var internalDefIcons = { home:'house', categories:'grid-2', tags:'tags', pornstars:'users', channels:'clapperboard', new_videos:'sparkles', top_rated:'star', most_viewed:'eye', most_favorited:'heart', vtype_switcher:'shuffle' };

    var counter = Date.now();
    var menuHasMultiLang = <?= json_encode($hasMultiLang) ?>;
    var menuLanguages = <?= json_encode($hasMultiLang ? $menuLanguages : [], JSON_UNESCAPED_UNICODE) ?>;
    var menuDefaultLang = <?= json_encode($menuDefaultLang ?? 'en') ?>;
    var menuInternalTrans = <?= json_encode($menuInternalTranslations ?? [], JSON_UNESCAPED_UNICODE) ?>;
    var globeSvg = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
    function uid() { return 'custom_' + (counter++); }
    function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }

    function updateState() {
        var tops = menuList.querySelectorAll(':scope > .mi');
        var total = menuList.querySelectorAll('.mi').length;
        emptyMsg.style.display = tops.length > 0 ? 'none' : '';
        countBadge.textContent = total;
        menuList.querySelectorAll('.mi-children').forEach(function(c) {
            c.classList.toggle('has-kids', c.children.length > 0);
        });
        
        menuList.querySelectorAll('.mi').forEach(function(mi) {
            var indentBtn = mi.querySelector(':scope > .mi-row .mi-act--indent');
            var outdentBtn = mi.querySelector(':scope > .mi-row .mi-act--outdent');
            if (!indentBtn || !outdentBtn) return;
            
            
            var prev = mi.previousElementSibling;
            var canIndent = prev && prev.classList.contains('mi') && mi.parentElement === menuList && prev.querySelector(':scope > .mi-children');
            indentBtn.disabled = !canIndent;
            
            var canOutdent = mi.parentElement.classList.contains('mi-children');
            outdentBtn.disabled = !canOutdent;
        });
    }

    
    function createItem(d) {
        var w = document.createElement('div');
        w.className = 'mi';
        w.dataset.id = d.id || uid();
        w.dataset.type = d.type || 'custom';
        w.dataset.label = d.label || '';
        w.dataset.url = d.url || '';
        w.dataset.target = d.target || '_self';
        w.dataset.pageId = d.page_id || '';
        w.dataset.icon = d.icon || '';
        w.dataset.translations = JSON.stringify(d._translations || {});
        if (d.id === 'categories') w.dataset.megaMenu = d.mega_menu === false ? '0' : '1';

        var type = d.type || 'custom';
        var itemId = d.id || '';
        var isWidget = (itemId === 'vtype_switcher');
        var iconCls = d.icon ? 'mi-icon-btn has-icon' : 'mi-icon-btn';
        var iconHtml = d.icon ? '<i class="fa-solid fa-' + esc(d.icon) + '"></i>' : '<i class="fa-solid fa-image" style="opacity:.4;font-size:11px;"></i>';

        
        var globeHtml = '';
        if (menuHasMultiLang && !isWidget) {
            var _tr = d._translations || {};
            var _hasAny = false;
            for (var _k in _tr) { if (_tr.hasOwnProperty(_k) && _k !== menuDefaultLang && _tr[_k]) { _hasAny = true; break; } }
            
            if (!_hasAny && type === 'internal' && menuInternalTrans[itemId]) {
                for (var _lk in menuInternalTrans[itemId]) {
                    if (_lk !== menuDefaultLang && menuInternalTrans[itemId][_lk]) { _hasAny = true; break; }
                }
            }
            globeHtml = '<button type="button" class="mi-tl-btn' + (_hasAny ? ' mi-tl-btn--active' : '') + '" data-action="translate" title="Translate label">' + globeSvg + '</button>';
        }

        var editFields = '';
        if (!isWidget) {
            editFields = '<div class="mi-ef"><span class="mi-ef-lbl">Label</span> <input type="text" class="edit-label" data-field="label"></div>';
            if (type === 'custom') {
                editFields += '<div class="mi-ef"><span class="mi-ef-lbl">URL</span> <input type="text" class="edit-url" data-field="url"></div>';
                editFields += '<div class="mi-ef"><label class="mi-ef-chk"><input type="checkbox" class="edit-target"> New tab</label></div>';
            }
            if (itemId === 'categories') {
                editFields += '<div class="mi-ef" style="width:100%;padding-top:4px;border-top:1px dashed #e5e7eb;margin-top:2px;"><label class="mi-ef-chk" style="font-size:12px;color:#374151;"><input type="checkbox" class="edit-megamenu"> <i class="fa-solid fa-grid-2" style="font-size:11px;opacity:.45;"></i> Mega-menu dropdown</label></div>';
            }
        }

        w.innerHTML =
            '<div class="mi-row">' +
                '<span class="mi-handle"><i class="fa-solid fa-grip-dots-vertical"></i></span>' +
                '<button type="button" class="' + iconCls + '" data-action="icon">' + iconHtml + '</button>' +
                globeHtml +
                '<span class="mi-label">' + esc(d.label || '') + '</span>' +
                '<span class="mi-badge mi-badge--' + type + '">' + type + '</span>' +
                '<div class="mi-actions">' +
                    '<button type="button" class="mi-act mi-act--indent" data-action="indent" title="Make sub-item"><i class="fa-solid fa-right-long"></i></button>' +
                    '<button type="button" class="mi-act mi-act--outdent" data-action="outdent" title="Move to top level"><i class="fa-solid fa-left-long"></i></button>' +
                    (!isWidget ? '<button type="button" class="mi-act mi-act--edit" data-action="edit" title="Edit"><i class="fa-solid fa-pen"></i></button>' : '') +
                    '<button type="button" class="mi-act mi-act--del" data-action="delete" title="Delete"><i class="fa-solid fa-trash"></i></button>' +
                '</div>' +
                (editFields ? '<div class="mi-edit-inline">' + editFields + '<button type="button" class="mi-ef-done" data-action="apply"><i class="fa-solid fa-check" style="font-size:10px;"></i> Done</button></div>' : '') +
            '</div>' +
            (isWidget ? '' : '<div class="mi-children"></div>');

        
        w.addEventListener('click', function(e) {
            var btn = e.target.closest('[data-action]');
            if (!btn) return;
            
            if (btn.closest('.mi') !== w) return;
            e.preventDefault();
            e.stopPropagation();
            var a = btn.dataset.action;
            if (a === 'edit') toggleEdit(w);
            else if (a === 'delete') deleteItem(w);
            else if (a === 'apply') applyEdit(w);
            else if (a === 'icon') openIconPicker(w);
            else if (a === 'indent') indentItem(w);
            else if (a === 'outdent') outdentItem(w);
            else if (a === 'translate') openTranslateModal(w);
        });

        return w;
    }

    function closeAllEdits() {
        menuList.querySelectorAll('.mi-edit-inline.open').forEach(function(p) {
            p.classList.remove('open');
            p.closest('.mi-row').classList.remove('editing');
        });
    }

    function toggleEdit(item) {
        var row = item.querySelector(':scope > .mi-row');
        var panel = row.querySelector('.mi-edit-inline');
        var isOpen = panel.classList.contains('open');

        closeAllEdits();

        if (!isOpen) {
            panel.classList.add('open');
            row.classList.add('editing');
            var labelInp = panel.querySelector('.edit-label');
            labelInp.value = item.dataset.label;
            if (item.dataset.type === 'custom') {
                panel.querySelector('.edit-url').value = item.dataset.url;
                panel.querySelector('.edit-target').checked = item.dataset.target === '_blank';
            }
            var mmCb = panel.querySelector('.edit-megamenu');
            if (mmCb) mmCb.checked = item.dataset.megaMenu !== '0';
            labelInp.focus();
        }
    }

    function applyEdit(item) {
        var row = item.querySelector(':scope > .mi-row');
        var panel = row.querySelector('.mi-edit-inline');
        var label = panel.querySelector('.edit-label').value.trim();
        if (label) {
            item.dataset.label = label;
            item.querySelector(':scope > .mi-row .mi-label').textContent = label;
        }
        if (item.dataset.type === 'custom') {
            item.dataset.url = panel.querySelector('.edit-url').value.trim();
            item.dataset.target = panel.querySelector('.edit-target').checked ? '_blank' : '_self';
        }
        var mmCb = panel.querySelector('.edit-megamenu');
        if (mmCb) item.dataset.megaMenu = mmCb.checked ? '1' : '0';
        panel.classList.remove('open');
        row.classList.remove('editing');
    }

    function deleteItem(item) {
        
        var ch = item.querySelector(':scope > .mi-children');
        if (ch) {
            var par = item.parentElement;
            while (ch.firstElementChild) par.insertBefore(ch.firstElementChild, item);
        }
        item.style.opacity = '0';
        item.style.transform = 'translateX(20px)';
        item.style.transition = 'all 0.2s';
        setTimeout(function() { item.remove(); updateState(); }, 200);
    }

    
    function indentItem(item) {
        var prev = item.previousElementSibling;
        if (!prev || !prev.classList.contains('mi')) return;
        
        if (item.parentElement !== menuList) return;
        var childZone = prev.querySelector(':scope > .mi-children');
        
        if (!childZone) return;
        closeAllEdits();
        childZone.appendChild(item);
        
        var ownChildren = item.querySelector(':scope > .mi-children');
        if (ownChildren) {
            
            while (ownChildren.firstElementChild) {
                menuList.insertBefore(ownChildren.firstElementChild, prev.nextSibling);
            }
        }
        initChildSort(childZone);
        updateState();
    }

    function outdentItem(item) {
        var parentChildren = item.parentElement;
        if (!parentChildren || !parentChildren.classList.contains('mi-children')) return;
        var parentMi = parentChildren.closest('.mi');
        if (!parentMi) return;
        closeAllEdits();
        
        var grandParent = parentMi.parentElement;
        grandParent.insertBefore(item, parentMi.nextSibling);
        updateState();
    }

    function addToMenu(d) {
        var el = createItem(d);
        menuList.appendChild(el);
        initChildSort(el.querySelector(':scope > .mi-children'));
        updateState();
        el.querySelector(':scope > .mi-row').style.animation = 'miIn 0.25s ease';
    }

    
    function initChildSort(c) {
        if (!c || c._si) return;
        c._si = true;
        new Sortable(c, {
            group: { name: 'menu', pull: true, put: function(to, from, el) {
                
                var ch = el.querySelector(':scope > .mi-children');
                return !ch || !ch.children.length;
            }},
            handle: '.mi-handle', animation: 200, easing: 'cubic-bezier(0.25,1,0.5,1)',
            ghostClass: 'sortable-ghost', chosenClass: 'sortable-chosen', dragClass: 'sortable-drag',
            fallbackOnBody: true, swapThreshold: 0.55,
            onEnd: function() { updateState(); }
        });
    }

    new Sortable(menuList, {
        group: { name: 'menu', pull: true, put: true },
        handle: '.mi-handle', animation: 200, easing: 'cubic-bezier(0.25,1,0.5,1)',
        ghostClass: 'sortable-ghost', chosenClass: 'sortable-chosen', dragClass: 'sortable-drag',
        fallbackOnBody: true, swapThreshold: 0.55, draggable: '.mi',
        onEnd: function() { updateState(); }
    });

    
    var existing = <?= json_encode($menuItems, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    existing.forEach(function(item) {
        var el = createItem(item);
        if (item.children && item.children.length) {
            var cc = el.querySelector(':scope > .mi-children');
            item.children.forEach(function(child) {
                var ce = createItem(child);
                var gc = ce.querySelector(':scope > .mi-children');
                if (gc) gc.remove();
                cc.appendChild(ce);
            });
        }
        menuList.appendChild(el);
        initChildSort(el.querySelector(':scope > .mi-children'));
    });
    updateState();
    menuList.querySelectorAll('.mi-children').forEach(initChildSort);

    
    document.getElementById('btnAddInternal').addEventListener('click', function() {
        document.querySelectorAll('.add-internal:checked').forEach(function(cb) {
            addToMenu({ id: cb.value, type: 'internal', label: cb.parentElement.querySelector('span').textContent.trim(), url: internalUrls[cb.value] || '/', icon: internalDefIcons[cb.value] || '' });
            cb.checked = false;
        });
    });

    var bp = document.getElementById('btnAddPages');
    if (bp) bp.addEventListener('click', function() {
        document.querySelectorAll('.add-page:checked').forEach(function(cb) {
            addToMenu({ id: 'page_' + cb.value, type: 'page', label: cb.dataset.label, page_id: cb.value, icon: 'file-lines' });
            cb.checked = false;
        });
    });

    document.getElementById('btnAddCustom').addEventListener('click', function() {
        var url = document.getElementById('customUrl').value.trim();
        var label = document.getElementById('customLabel').value.trim();
        if (!url || !label) {
            if (!url) document.getElementById('customUrl').style.borderColor = '#ef4444';
            if (!label) document.getElementById('customLabel').style.borderColor = '#ef4444';
            setTimeout(function() { document.getElementById('customUrl').style.borderColor = ''; document.getElementById('customLabel').style.borderColor = ''; }, 1200);
            return;
        }
        addToMenu({ id: uid(), type: 'custom', label: label, url: url, target: document.getElementById('customBlank').checked ? '_blank' : '_self', icon: 'arrow-up-right-from-square' });
        document.getElementById('customUrl').value = '';
        document.getElementById('customLabel').value = '';
        document.getElementById('customBlank').checked = false;
    });

    
    function readItem(el) {
        var o = { id: el.dataset.id, type: el.dataset.type, label: el.dataset.label, icon: el.dataset.icon || '', _translations: JSON.parse(el.dataset.translations || '{}'), children: [] };
        if (o.type === 'custom') { o.url = el.dataset.url; o.target = el.dataset.target; }
        else if (o.type === 'internal') { o.url = el.dataset.url; }
        else if (o.type === 'page') { o.page_id = parseInt(el.dataset.pageId) || 0; }
        if (o.id === 'categories') { o.mega_menu = el.dataset.megaMenu !== '0'; }
        var cc = el.querySelector(':scope > .mi-children');
        if (cc) {
            cc.querySelectorAll(':scope > .mi').forEach(function(k) {
                var ci = readItem(k);
                ci.children = [];
                o.children.push(ci);
            });
        }
        return o;
    }

    menuForm.addEventListener('submit', function() {
        var items = [];
        menuList.querySelectorAll(':scope > .mi').forEach(function(el) { items.push(readItem(el)); });
        menuJsonInput.value = JSON.stringify({ items: items });
    });

    
    window.mbToggle = function(hd) {
        var exp = hd.getAttribute('aria-expanded') === 'true';
        hd.setAttribute('aria-expanded', exp ? 'false' : 'true');
        hd.nextElementSibling.hidden = exp;
    };

    
    var ipOverlay = document.getElementById('iconPicker');
    var ipGrid = document.getElementById('ipGrid');
    var ipSearch = document.getElementById('ipSearch');
    var ipSelDisplay = document.getElementById('ipSelected');
    var ipRemoveBtn = document.getElementById('ipRemoveBtn');
    var ipCountEl = document.getElementById('ipCount');
    var ipAllIcons = [];
    var ipFiltered = [];
    var ipStyle = 'solid';
    var ipCurrentIcon = '';
    var ipTarget = null;
    var ipLoaded = false;

    function ipLoad(cb) {
        if (ipLoaded) return cb();
        fetch('/assets/fontawesomepro/icons.json').then(function(r) { return r.json(); }).then(function(data) {
            ipAllIcons = data;
            ipLoaded = true;
            cb();
        });
    }

    window.openIconPicker = function(miEl) {
        ipTarget = miEl;
        ipCurrentIcon = miEl.dataset.icon || '';
        ipLoad(function() {
            ipSearch.value = '';
            ipFilter();
            ipUpdateSel();
            ipOverlay.classList.add('open');
            setTimeout(function() { ipSearch.focus(); }, 100);
        });
    };

    window.ipClose = function() {
        ipOverlay.classList.remove('open');
        ipTarget = null;
    };

    window.ipConfirm = function() {
        if (ipTarget) {
            ipTarget.dataset.icon = ipCurrentIcon;
            var btn = ipTarget.querySelector(':scope > .mi-row .mi-icon-btn');
            if (ipCurrentIcon) {
                btn.className = 'mi-icon-btn has-icon';
                btn.innerHTML = '<i class="fa-solid fa-' + ipCurrentIcon + '"></i>';
            } else {
                btn.className = 'mi-icon-btn';
                btn.innerHTML = '<i class="fa-solid fa-image" style="opacity:.4;font-size:11px;"></i>';
            }
        }
        ipClose();
    };

    window.ipRemove = function() {
        ipCurrentIcon = '';
        ipUpdateSel();
        ipGrid.querySelectorAll('.ip-icon.selected').forEach(function(x) { x.classList.remove('selected'); });
    };

    function ipUpdateSel() {
        if (ipCurrentIcon) {
            ipSelDisplay.innerHTML = '<i class="fa-solid fa-' + ipCurrentIcon + '"></i> <span>fa-' + ipCurrentIcon + '</span>';
            ipRemoveBtn.style.display = '';
        } else {
            ipSelDisplay.innerHTML = '<span style="color:#9ca3af;">No icon selected</span>';
            ipRemoveBtn.style.display = 'none';
        }
    }

    function ipFilter() {
        var q = ipSearch.value.trim().toLowerCase();
        ipFiltered = ipAllIcons.filter(function(ic) {
            if (ipStyle === 'brands') return ic.b && ic.n.indexOf(q) !== -1;
            if (ic.b) return false;
            return ic.n.indexOf(q) !== -1;
        });
        ipRender();
    }

    var ipDebounce = null;
    function ipRender() {
        if (ipDebounce) cancelAnimationFrame(ipDebounce);
        ipDebounce = requestAnimationFrame(function() {
            var list = ipFiltered;
            ipCountEl.textContent = list.length + ' icons';

            if (!list.length) {
                ipGrid.innerHTML = '<div class="ip-empty"><i class="fa-solid fa-face-meh" style="font-size:24px;opacity:.3;margin-bottom:8px;display:block;"></i>No icons found</div>';
                return;
            }

            var faPrefix = ipStyle === 'brands' ? 'fa-brands' : 'fa-' + ipStyle;
            var frag = document.createDocumentFragment();

            for (var i = 0; i < list.length; i++) {
                var n = list[i].n;
                var div = document.createElement('div');
                div.className = 'ip-icon' + (n === ipCurrentIcon ? ' selected' : '');
                div.dataset.name = n;
                div.title = n;
                var ic = document.createElement('i');
                ic.className = faPrefix + ' fa-' + n;
                div.appendChild(ic);
                frag.appendChild(div);
            }

            ipGrid.innerHTML = '';
            ipGrid.appendChild(frag);

            
            if (ipCurrentIcon) {
                var sel = ipGrid.querySelector('.ip-icon.selected');
                if (sel) {
                    setTimeout(function() { sel.scrollIntoView({ block: 'center', behavior: 'instant' }); }, 50);
                }
            }
        });
    }

    ipGrid.addEventListener('click', function(e) {
        var icon = e.target.closest('.ip-icon');
        if (!icon) return;
        ipGrid.querySelectorAll('.ip-icon.selected').forEach(function(x) { x.classList.remove('selected'); });
        icon.classList.add('selected');
        ipCurrentIcon = icon.dataset.name;
        ipUpdateSel();
    });

    ipSearch.addEventListener('input', function() { ipFilter(); });

    
    document.getElementById('ipStyles').addEventListener('click', function(e) {
        var btn = e.target.closest('.ip-style-btn');
        if (!btn) return;
        document.querySelectorAll('.ip-style-btn').forEach(function(b) { b.classList.remove('active'); });
        btn.classList.add('active');
        ipStyle = btn.dataset.style;
        ipFilter();
    });

    

    
    var tlOverlay = menuHasMultiLang ? document.getElementById('translateModal') : null;
    var tlBody = menuHasMultiLang ? document.getElementById('tlBody') : null;
    var tlTarget = null;

    window.openTranslateModal = function(miEl) {
        if (!tlOverlay) return;
        tlTarget = miEl;
        var trans = JSON.parse(miEl.dataset.translations || '{}');
        var itemType = miEl.dataset.type;
        var itemId = miEl.dataset.id;

        var html = '';
        menuLanguages.forEach(function(lang) {
            var code = lang.code;
            var isDefault = (code === menuDefaultLang);
            html += '<div class="mt-lang-row">';
            html += '<div class="mt-lang-row__label">';
            html += '<span class="fi fi-' + esc(lang.flag) + ' fis" style="width:16px;height:16px;border-radius:2px;box-shadow:0 0 0 1px rgba(0,0,0,0.08);flex-shrink:0;"></span>';
            html += '<span class="mt-lang-row__name">' + esc(lang.name) + '</span>';
            if (isDefault) html += '<span class="mt-lang-row__badge">Default</span>';
            html += '</div>';
            if (isDefault) {
                html += '<div class="mt-lang-row__note">Uses the main label</div>';
            } else {
                html += '<input type="text" class="mt-lang-row__input" data-lang="' + code + '" dir="' + ((lang.direction || 'ltr') === 'rtl' ? 'rtl' : 'ltr') + '">';
            }
            html += '</div>';
        });

        tlBody.innerHTML = html;

        
        menuLanguages.forEach(function(lang) {
            if (lang.code === menuDefaultLang) return;
            var inp = tlBody.querySelector('[data-lang="' + lang.code + '"]');
            if (!inp) return;
            var langSysVal = (itemType === 'internal' && menuInternalTrans[itemId] && menuInternalTrans[itemId][lang.code]) ? menuInternalTrans[itemId][lang.code] : '';
            
            inp.value = trans[lang.code] || langSysVal;
            inp.placeholder = langSysVal || 'Leave empty for default';
        });

        tlOverlay.classList.add('open');
        var firstInput = tlBody.querySelector('.mt-lang-row__input');
        if (firstInput) setTimeout(function() { firstInput.focus(); }, 100);
    };

    window.tlClose = function() {
        if (!tlOverlay) return;
        tlOverlay.classList.remove('open');
        tlTarget = null;
    };

    window.tlDone = function() {
        if (!tlTarget) return;
        var trans = {};
        var itemType = tlTarget.dataset.type;
        var itemId = tlTarget.dataset.id;
        tlBody.querySelectorAll('.mt-lang-row__input').forEach(function(inp) {
            var val = inp.value.trim();
            if (!val) return;
            
            if (itemType === 'internal' && menuInternalTrans[itemId] && menuInternalTrans[itemId][inp.dataset.lang] === val) {
                return;
            }
            trans[inp.dataset.lang] = val;
        });
        tlTarget.dataset.translations = JSON.stringify(trans);
        
        var globeBtn = tlTarget.querySelector(':scope > .mi-row .mi-tl-btn');
        if (globeBtn) {
            var hasAny = Object.keys(trans).length > 0;
            if (!hasAny && itemType === 'internal' && menuInternalTrans[itemId]) {
                for (var lk in menuInternalTrans[itemId]) {
                    if (lk !== menuDefaultLang && menuInternalTrans[itemId][lk]) { hasAny = true; break; }
                }
            }
            globeBtn.classList.toggle('mi-tl-btn--active', hasAny);
        }
        tlClose();
    };

    if (tlOverlay) {
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (ipOverlay.classList.contains('open')) ipClose();
            if (tlOverlay && tlOverlay.classList.contains('open')) tlClose();
        }
    });
})();
</script>
