<?php
// OneLauncher - buttons.php
require_once 'includes/auth.php';
require_once 'db.php';

$pageTitle = 'Botões Verticais';
$nav = 'buttons';
$msg = '';

if (isset($_POST['save_all_buttons'])) {
    $errors = [];
    $allowed_image_exts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    
    for ($i = 1; $i <= 3; $i++) {
        $package = $_POST["package_name_$i"];
        $icon_url = $_POST["icon_url_$i"];
        $action_type = $_POST["action_type_$i"];

        // Upload de ícone individual
        if (isset($_FILES["icon_file_$i"]) && $_FILES["icon_file_$i"]['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads';
            if (!file_exists($upload_dir))
                mkdir($upload_dir, 0777, true);
            $ext = strtolower(pathinfo($_FILES["icon_file_$i"]['name'], PATHINFO_EXTENSION));
            if (in_array($ext, $allowed_image_exts)) {
                $new_name = "btn_{$i}_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $ext;
                if (move_uploaded_file($_FILES["icon_file_$i"]['tmp_name'], "$upload_dir/$new_name")) {
                    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://";
                    $icon_url = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/uploads/$new_name";
                }
            } else {
                $errors[] = "A extensão do arquivo do ícone do botão $i não é permitida. Apenas JPG, JPEG, PNG, WEBP e GIF são suportados.";
            }
        }

        if (empty($errors)) {
            global $active_theme_id;
            // Garante que a linha existe antes de atualizar
            $conn->query("INSERT IGNORE INTO vertical_buttons (theme_id, button_index, label) VALUES ($active_theme_id, $i, 'BOTÃO $i')");
            
            $stmt = $conn->prepare("UPDATE vertical_buttons SET package_name = ?, icon_url = ?, action_type = ? WHERE button_index = ? AND theme_id = ?");
            $stmt->bind_param("sssii", $package, $icon_url, $action_type, $i, $active_theme_id);
            $stmt->execute();
        }
    }
    
    if (empty($errors)) {
        $msg = "Todos os botões foram atualizados com sucesso!";
    } else {
        $msg_error = implode('<br>', array_map('htmlspecialchars', $errors));
    }
}

global $active_theme_id;
$res = $conn->query("SELECT * FROM vertical_buttons WHERE theme_id = $active_theme_id");
if (!$res || $res->num_rows < 3) {
    for ($i = 1; $i <= 3; $i++) {
        $conn->query("INSERT IGNORE INTO vertical_buttons (theme_id, button_index, label) VALUES ($active_theme_id, $i, 'BOTÃO $i')");
    }
}
$res = $conn->query("SELECT * FROM vertical_buttons WHERE theme_id = $active_theme_id ORDER BY button_index ASC");
$buttons = [];
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $buttons[$row['button_index']] = $row;
    }
}

// Fallback para evitar 'Undefined array key'
for ($i = 1; $i <= 3; $i++) {
    if (!isset($buttons[$i])) {
        $buttons[$i] = [
            'action_type' => 'app',
            'package_name' => '',
            'icon_url' => '',
            'label' => "BOTÃO $i"
        ];
    }
}

// Buscar apps disponíveis na loja para o seletor
$resStore = $conn->query("SELECT package_name, name FROM app_store WHERE theme_id = $active_theme_id ORDER BY name ASC");
$storeApps = [];
while ($app = $resStore->fetch_assoc())
    $storeApps[] = $app;

include 'includes/head.php';
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<style>
    /* ===== DESIGN SYSTEM - LAYOUT LIMPO E ACESSÍVEL ===== */
    :root {
        --card-bg: rgba(18, 25, 45, 0.7);
        --card-border: rgba(255, 255, 255, 0.06);
        --input-bg: rgba(10, 18, 35, 0.75);
        --input-border: rgba(255, 255, 255, 0.1);
        --accent: #4f8cff;
        --accent-hover: #3a6fd8;
        --text-primary: #f0f3fa;
        --text-secondary: #a0b4cf;
        --text-muted: #6c7a94;
        --danger: #ff5c5c;
        --shadow-card: 0 8px 24px rgba(0, 0, 0, 0.35);
        --radius-md: 14px;
        --radius-sm: 10px;
    }

    /* Reset de acessibilidade global */
    *:focus-visible {
        outline: 2px solid var(--accent);
        outline-offset: 2px;
        border-radius: 4px;
    }

    .page-wrapper {
        max-width: 1280px;
        margin: 0 auto;
    }

    /* Cabeçalho da página */
    .page-header {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        margin-bottom: 2rem;
    }

    .page-title {
        font-size: 1.8rem;
        font-weight: 600;
        color: #fff;
        display: flex;
        align-items: center;
        gap: 0.6rem;
        letter-spacing: -0.3px;
        line-height: 1.3;
    }

    .page-title i {
        font-size: 2rem;
        color: var(--accent);
        background: rgba(79, 140, 255, 0.12);
        padding: 0.6rem;
        border-radius: var(--radius-sm);
    }

    .page-subtitle {
        color: var(--text-secondary);
        font-size: 0.95rem;
        margin: 0.25rem 0 0 0;
        font-weight: 400;
    }

    .btn-save-all {
        background: var(--accent);
        border: none;
        color: #fff;
        font-weight: 600;
        font-size: 0.95rem;
        padding: 0.75rem 1.8rem;
        border-radius: 50px;
        box-shadow: 0 6px 18px rgba(79, 140, 255, 0.3);
        transition: all 0.25s ease;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        letter-spacing: 0.3px;
    }

    .btn-save-all:hover {
        background: var(--accent-hover);
        box-shadow: 0 8px 24px rgba(79, 140, 255, 0.45);
        transform: translateY(-1px);
    }

    .btn-save-all:active {
        transform: translateY(1px);
        box-shadow: 0 4px 12px rgba(79, 140, 255, 0.25);
    }

    .btn-save-all:disabled {
        opacity: 0.7;
        cursor: not-allowed;
        transform: none;
    }

    /* Alert de feedback */
    .alert-feedback {
        background: rgba(46, 204, 113, 0.15);
        border-left: 4px solid #2ecc71;
        color: #d4edda;
        border-radius: var(--radius-sm);
        padding: 1rem 1.4rem;
        margin-bottom: 2rem;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        animation: fadeSlideIn 0.3s ease;
    }

    @keyframes fadeSlideIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* Grid de cards */
    .buttons-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
        gap: 1.8rem;
    }

    /* Card individual */
    .btn-config-card {
        background: var(--card-bg);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid var(--card-border);
        border-radius: var(--radius-md);
        padding: 1.6rem;
        box-shadow: var(--shadow-card);
        transition: border-color 0.2s, box-shadow 0.2s;
    }

    .btn-config-card:hover {
        border-color: rgba(79, 140, 255, 0.25);
        box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(79, 140, 255, 0.15);
    }

    .card-header {
        display: flex;
        align-items: center;
        gap: 0.8rem;
        margin-bottom: 1.8rem;
        padding-bottom: 1.2rem;
        border-bottom: 1px solid rgba(255, 255, 255, 0.08);
    }

    .btn-index-badge {
        background: rgba(79, 140, 255, 0.18);
        color: var(--accent);
        font-weight: 700;
        font-size: 1.2rem;
        width: 38px;
        height: 38px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid rgba(79, 140, 255, 0.3);
    }

    .card-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #fff;
        margin: 0;
        letter-spacing: -0.2px;
    }

    /* Labels flutuantes estilo moderno */
    .field-group {
        margin-bottom: 1.5rem;
    }

    .field-label {
        display: flex;
        align-items: center;
        gap: 0.4rem;
        font-size: 0.9rem;
        font-weight: 600;
        color: var(--text-secondary);
        margin-bottom: 0.5rem;
        letter-spacing: 0.2px;
    }

    .field-label i {
        font-size: 1rem;
        color: var(--accent);
        opacity: 0.8;
    }

    .form-control-custom,
    .form-select-custom {
        width: 100%;
        background: var(--input-bg);
        border: 1px solid var(--input-border);
        color: var(--text-primary);
        padding: 0.75rem 1rem;
        border-radius: var(--radius-sm);
        font-size: 0.95rem;
        transition: all 0.2s;
        line-height: 1.5;
        font-family: inherit;
    }

    .form-control-custom:focus,
    .form-select-custom:focus {
        background: rgba(15, 25, 50, 0.9);
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(79, 140, 255, 0.2);
        outline: none;
    }

    .form-select-custom {
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%238a9bb5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 1rem center;
        background-size: 1rem;
        padding-right: 2.5rem;
    }

    .helper-text {
        font-size: 0.82rem;
        color: var(--text-muted);
        margin-top: 0.35rem;
        display: block;
    }

    /* Seletor de app da loja (condicional) */
    .store-select-group {
        transition: all 0.3s ease;
    }

    /* Upload de ícone */
    .icon-upload-area {
        display: flex;
        gap: 1rem;
        align-items: flex-start;
        flex-wrap: wrap;
    }

    .icon-preview-box {
        width: 90px;
        height: 90px;
        background: rgba(8, 15, 33, 0.8);
        border: 2px dashed rgba(255, 255, 255, 0.15);
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;
        transition: border-color 0.2s;
        flex-shrink: 0;
    }

    .icon-preview-box.has-image {
        border-style: solid;
        border-color: rgba(79, 140, 255, 0.4);
    }

    .icon-preview-box img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        padding: 0.5rem;
    }

    .icon-placeholder {
        color: var(--text-muted);
        font-size: 2rem;
        opacity: 0.6;
    }

    .clear-icon-btn {
        position: absolute;
        top: 4px;
        right: 4px;
        background: rgba(0,0,0,0.65);
        border: 1px solid rgba(255,255,255,0.15);
        color: #fff;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 14px;
        line-height: 1;
        opacity: 0;
        transition: opacity 0.2s, background 0.2s;
        z-index: 5;
        backdrop-filter: blur(4px);
    }

    .icon-preview-box:hover .clear-icon-btn {
        opacity: 1;
    }

    .clear-icon-btn:hover {
        background: var(--danger);
        border-color: var(--danger);
    }

    .upload-controls {
        flex: 1;
        min-width: 200px;
    }

    .file-input-wrapper {
        position: relative;
        overflow: hidden;
        display: inline-block;
        width: 100%;
        margin-bottom: 0.6rem;
    }

    .file-input-button {
        display: block;
        background: rgba(255,255,255,0.05);
        border: 1px dashed var(--input-border);
        color: var(--text-secondary);
        padding: 0.65rem 1rem;
        border-radius: var(--radius-sm);
        text-align: center;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 0.9rem;
    }

    .file-input-button:hover {
        border-color: var(--accent);
        color: #fff;
        background: rgba(79,140,255,0.1);
    }

    .file-input-wrapper input[type="file"] {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }

    .url-input-group {
        display: flex;
        gap: 0.4rem;
        align-items: center;
    }

    .url-prefix {
        background: rgba(255,255,255,0.05);
        border: 1px solid var(--input-border);
        color: var(--text-muted);
        padding: 0.65rem 0.8rem;
        border-radius: var(--radius-sm);
        font-size: 0.9rem;
        white-space: nowrap;
    }

    /* Responsividade */
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .btn-save-all {
            width: 100%;
            justify-content: center;
        }

        .buttons-grid {
            grid-template-columns: 1fr;
        }

        .icon-upload-area {
            flex-direction: column;
            align-items: center;
        }

        .icon-preview-box {
            width: 100px;
            height: 100px;
        }
    }

    /* ===== PRESETS DE APPS ===== */
    .presets-section {
        margin-top: 1.5rem;
        padding-top: 1.2rem;
        border-top: 1px solid rgba(255,255,255,0.07);
    }

    .presets-label {
        font-size: 0.82rem;
        font-weight: 600;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 0.8px;
        margin-bottom: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.4rem;
    }

    .presets-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 0.5rem;
    }

    .preset-chip {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.3rem;
        padding: 0.55rem 0.3rem;
        background: rgba(255,255,255,0.04);
        border: 1px solid rgba(255,255,255,0.08);
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.2s;
        text-align: center;
    }

    .preset-chip:hover {
        background: rgba(79,140,255,0.12);
        border-color: rgba(79,140,255,0.4);
        transform: translateY(-2px);
    }

    .preset-chip img {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        object-fit: contain;
    }

    .preset-chip .preset-name {
        font-size: 0.68rem;
        color: var(--text-secondary);
        line-height: 1.2;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 100%;
    }

    .preset-chip.selected {
        background: rgba(79,140,255,0.18);
        border-color: var(--accent);
    }

    /* ===== DESIGNER VISUAL ===== */
    .btn-open-designer {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background: linear-gradient(135deg, rgba(130,0,255,0.15), rgba(79,140,255,0.15));
        border: 1px dashed rgba(130,80,255,0.4);
        color: #b088ff;
        font-size: 0.85rem;
        font-weight: 600;
        padding: 0.6rem 1rem;
        border-radius: var(--radius-sm);
        cursor: pointer;
        transition: all 0.2s;
        width: 100%;
        justify-content: center;
        margin-top: 0.6rem;
    }

    .btn-open-designer:hover {
        background: linear-gradient(135deg, rgba(130,0,255,0.25), rgba(79,140,255,0.25));
        border-color: rgba(130,80,255,0.7);
        color: #c9a8ff;
    }

    /* ===== MODAL DO DESIGNER ===== */
    .designer-modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.75);
        backdrop-filter: blur(8px);
        z-index: 9999;
        display: none;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }

    .designer-modal-overlay.open {
        display: flex;
    }

    .designer-modal {
        background: #0f1929;
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 20px;
        padding: 2rem;
        width: 100%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 30px 80px rgba(0,0,0,0.6);
        animation: modalIn 0.3s ease;
    }

    @keyframes modalIn {
        from { opacity: 0; transform: scale(0.96) translateY(10px); }
        to { opacity: 1; transform: scale(1) translateY(0); }
    }

    .designer-layout {
        display: grid;
        grid-template-columns: auto 1fr;
        gap: 2rem;
        align-items: start;
    }

    @media (max-width: 600px) {
        .designer-layout {
            grid-template-columns: 1fr;
        }
        .canvas-wrapper { margin: 0 auto; }
    }

    .canvas-wrapper {
        position: relative;
        width: 116px;
        flex-shrink: 0;
    }

    #btnDesignerCanvas {
        width: 116px;
        height: 250px;
        border-radius: 14px;
        display: block;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        border: 1px solid rgba(255,255,255,0.1);
    }

    .canvas-label {
        text-align: center;
        font-size: 0.72rem;
        color: var(--text-muted);
        margin-top: 0.5rem;
    }

    .designer-controls {
        display: flex;
        flex-direction: column;
        gap: 1.2rem;
    }

    .designer-modal-title {
        font-size: 1.3rem;
        font-weight: 700;
        color: #fff;
        margin: 0 0 1.5rem 0;
        display: flex;
        align-items: center;
        gap: 0.6rem;
    }

    .color-swatches {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.5rem;
    }

    .color-swatch {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        cursor: pointer;
        border: 2px solid transparent;
        transition: transform 0.15s, border-color 0.15s;
    }

    .color-swatch:hover { transform: scale(1.2); }
    .color-swatch.active { border-color: #fff; transform: scale(1.15); }

    .logo-upload-zone {
        border: 2px dashed rgba(255,255,255,0.15);
        border-radius: var(--radius-sm);
        padding: 1.5rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.2s;
        position: relative;
        overflow: hidden;
    }

    .logo-upload-zone:hover {
        border-color: var(--accent);
        background: rgba(79,140,255,0.05);
    }

    .logo-upload-zone input[type=file] {
        position: absolute;
        inset: 0;
        opacity: 0;
        cursor: pointer;
        width: 100%;
        height: 100%;
    }

    .logo-upload-zone .zone-icon { font-size: 2rem; color: var(--text-muted); }
    .logo-upload-zone .zone-text { font-size: 0.85rem; color: var(--text-secondary); margin-top: 0.3rem; }
    .logo-upload-zone .zone-hint { font-size: 0.75rem; color: var(--text-muted); }

    .designer-actions {
        display: flex;
        gap: 0.75rem;
        flex-wrap: wrap;
    }

    .btn-designer-apply {
        flex: 1;
        background: var(--accent);
        color: #fff;
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 0.95rem;
    }

    .btn-designer-apply:hover {
        background: var(--accent-hover);
        transform: translateY(-1px);
    }

    .btn-designer-cancel {
        background: rgba(255,255,255,0.06);
        color: var(--text-secondary);
        border: 1px solid rgba(255,255,255,0.1);
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 0.95rem;
    }

    .btn-designer-cancel:hover {
        background: rgba(255,255,255,0.1);
        color: #fff;
    }

    .btn-designer-download {
        background: rgba(46,204,113,0.15);
        color: #2ecc71;
        border: 1px solid rgba(46,204,113,0.3);
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 0.95rem;
        display: flex;
        align-items: center;
        gap: 0.4rem;
    }

    .btn-designer-download:hover {
        background: rgba(46,204,113,0.25);
    }
</style>

<div class="page-wrapper">
    <!-- Cabeçalho -->
    <div class="page-header">
        <div>
            <h1 class="page-title">
                <i class="bi bi-grid-3x3-gap-fill"></i> 
                Botões de Ação
            </h1>
            <p class="page-subtitle">Configure os 3 botões principais exibidos na lateral esquerda da interface.</p>
        </div>
        <button type="submit" name="save_all_buttons" form="buttonsForm" class="btn-save-all" id="saveAllBtn">
            <i class="bi bi-cloud-check-fill"></i> Atualizar Todos os Botões
        </button>
    </div>

    <?php 
    if (isset($msg_error)) {
        $msg = "Erro: " . $msg_error;
    }
    ?>

    <!-- Formulário -->
    <form id="buttonsForm" method="POST" action="buttons.php" enctype="multipart/form-data">
        <input type="hidden" name="save_all_buttons" value="1">

        <div class="buttons-grid">
            <?php for ($i = 1; $i <= 3; $i++): ?>
                    <div class="btn-config-card">
                        <!-- Cabeçalho do card -->
                        <div class="card-header">
                            <div class="btn-index-badge"><?php echo $i; ?></div>
                            <h2 class="card-title">Botão <?php echo $i; ?></h2>
                        </div>

                        <!-- Tipo de Ação -->
                        <div class="field-group">
                            <label class="field-label" for="action_type_<?php echo $i; ?>">
                                <i class="bi bi-cpu"></i> Tipo de Ação
                            </label>
                            <select name="action_type_<?php echo $i; ?>" id="action_type_<?php echo $i; ?>" class="form-select-custom">
                                <option value="app" <?php echo ($buttons[$i]['action_type'] == 'app') ? 'selected' : ''; ?>>📱 Abrir App Específico</option>
                                <option value="direct_install" <?php echo ($buttons[$i]['action_type'] == 'direct_install') ? 'selected' : ''; ?>>📥 Instalar App da Loja</option>
                                <?php if ($buttons[$i]['action_type'] == 'store'): ?>
                                    <option value="store" selected style="display: none;">🛒 Abrir Loja de Apps</option>
                                <?php endif; ?>
                                <?php if ($buttons[$i]['action_type'] == 'installed_apps'): ?>
                                    <option value="installed_apps" selected style="display: none;">📦 Abrir Meus Apps</option>
                                <?php endif; ?>
                            </select>
                            <span class="helper-text">Define o comportamento do botão quando pressionado.</span>
                        </div>

                        <!-- Seletor de App da Loja (condicional) -->
                        <div class="field-group store-select-group <?php echo ($buttons[$i]['action_type'] == 'direct_install') ? '' : 'd-none'; ?>" data-store-select-container="<?php echo $i; ?>">
                            <label class="field-label" for="store_app_<?php echo $i; ?>">
                                <i class="bi bi-shop"></i> Selecionar App da Loja
                            </label>
                            <select id="store_app_<?php echo $i; ?>" class="form-select-custom store-app-selector" data-target-input="<?php echo $i; ?>">
                                <option value="">-- Escolha um aplicativo --</option>
                                <?php foreach ($storeApps as $app): ?>
                                        <option value="<?php echo htmlspecialchars($app['package_name']); ?>" <?php echo ($buttons[$i]['package_name'] == $app['package_name']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($app['name']); ?>
                                        </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Package Name -->
                        <div class="field-group">
                            <label class="field-label" for="package_name_<?php echo $i; ?>">
                                <i class="bi bi-box-seam"></i> ID do Pacote (Package Name)
                            </label>
                            <input type="text" name="package_name_<?php echo $i; ?>" id="package_name_<?php echo $i; ?>" 
                                   value="<?php echo htmlspecialchars($buttons[$i]['package_name']); ?>" 
                                   class="form-control-custom" 
                                   placeholder="Ex: com.google.android.youtube"
                                   data-package-input="<?php echo $i; ?>">
                            <span class="helper-text">Necessário para abrir um app específico ou instalar.</span>
                        </div>

                        <!-- Ícone Personalizado -->
                        <div class="field-group">
                            <label class="field-label">
                                <i class="bi bi-image"></i> Ícone do Botão
                            </label>
                            <div class="icon-upload-area">
                                <!-- Preview -->
                                <div class="icon-preview-box <?php echo $buttons[$i]['icon_url'] ? 'has-image' : ''; ?>" data-preview-container="<?php echo $i; ?>">
                                    <?php if ($buttons[$i]['icon_url']): ?>
                                            <img src="<?php echo htmlspecialchars($buttons[$i]['icon_url']); ?>" alt="Pré-visualização do ícone">
                                    <?php else: ?>
                                            <i class="bi bi-image icon-placeholder"></i>
                                    <?php endif; ?>
                                    <button type="button" class="clear-icon-btn" data-clear-index="<?php echo $i; ?>" title="Remover ícone">
                                        <i class="bi bi-x"></i>
                                    </button>
                                </div>

                                <!-- Controles de upload -->
                                <div class="upload-controls">
                                    <div class="file-input-wrapper">
                                        <div class="file-input-button" id="file-label-<?php echo $i; ?>">
                                            <i class="bi bi-upload me-1"></i> Selecionar arquivo
                                        </div>
                                        <input type="file" name="icon_file_<?php echo $i; ?>" 
                                               class="icon-file-input" 
                                               accept="image/*" 
                                               data-icon-index="<?php echo $i; ?>"
                                               aria-labelledby="file-label-<?php echo $i; ?>">
                                    </div>

                                    <div class="url-input-group">
                                        <span class="url-prefix">URL</span>
                                        <input type="url" name="icon_url_<?php echo $i; ?>" 
                                               value="<?php echo htmlspecialchars($buttons[$i]['icon_url']); ?>" 
                                               class="form-control-custom icon-url-input" 
                                               placeholder="https://exemplo.com/icone.png"
                                               data-icon-index="<?php echo $i; ?>"
                                               style="flex:1;">
                                    </div>

                                    <!-- Botão do Designer Visual -->
                                    <button type="button" class="btn-open-designer" data-designer-target="<?php echo $i; ?>">
                                        <i class="bi bi-palette2"></i> Criar com Designer Visual
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Presets de Apps -->
                        <div class="presets-section">
                            <div class="presets-label">
                                <i class="bi bi-lightning-fill"></i> Presets Rápidos
                            </div>
                            <div class="presets-grid" data-preset-target="<?php echo $i; ?>">
                                <!-- Presets gerados via JS -->
                            </div>
                        </div>
                    </div>
            <?php endfor; ?>
        </div>
    </form>
</div>

<!-- ===== MODAL DO DESIGNER VISUAL ===== -->
<div class="designer-modal-overlay" id="designerModalOverlay">
    <div class="designer-modal">
        <h2 class="designer-modal-title">
            <i class="bi bi-palette2" style="color:#b088ff"></i> Designer Visual de Botão
        </h2>
        <div class="designer-layout">
            <!-- Preview do Canvas -->
            <div class="canvas-wrapper">
                <canvas id="btnDesignerCanvas" width="232" height="500"></canvas>
                <div class="canvas-label">232 × 500 px</div>
            </div>

            <!-- Controles -->
            <div class="designer-controls">
                <!-- Cor de Fundo -->
                <div class="field-group" style="margin-bottom:0">
                    <label class="field-label"><i class="bi bi-paint-bucket"></i> Cor de Fundo</label>
                    <div class="color-swatches" id="colorSwatches">
                        <div class="color-swatch active" data-color="#0d1117" style="background:#0d1117" title="Preto"></div>
                        <div class="color-swatch" data-color="#09122e" style="background:#09122e" title="Azul Noite"></div>
                        <div class="color-swatch" data-color="#12202e" style="background:#12202e" title="Dark Navy"></div>
                        <div class="color-swatch" data-color="#1a0a2e" style="background:#1a0a2e" title="Roxo Escuro"></div>
                        <div class="color-swatch" data-color="#0a1f0a" style="background:#0a1f0a" title="Verde Escuro"></div>
                        <div class="color-swatch" data-color="#1a0a0a" style="background:#1a0a0a" title="Vermelho Escuro"></div>
                        <div class="color-swatch" data-color="#11a853" style="background:#11a853" title="Verde Google"></div>
                        <div class="color-swatch" data-color="#1877f2" style="background:#1877f2" title="Azul Facebook"></div>
                        <div class="color-swatch" data-color="#e1306c" style="background:#e1306c" title="Rosa Instagram"></div>
                        <div class="color-swatch" data-color="#ff0000" style="background:#ff0000" title="Vermelho YouTube"></div>
                        <div class="color-swatch" data-color="#25d366" style="background:#25d366" title="Verde WhatsApp"></div>
                        <div class="color-swatch" data-color="#1db954" style="background:#1db954" title="Verde Spotify"></div>
                    </div>
                    <div style="display:flex; align-items:center; gap:0.75rem; margin-top:0.75rem;">
                        <input type="color" id="customBgColor" value="#0d1117" style="width:40px; height:40px; border:none; border-radius:8px; cursor:pointer; background:none; padding:0;">
                        <label style="font-size:0.85rem; color:var(--text-secondary);">Cor personalizada</label>
                    </div>
                </div>

                <!-- Gradiente -->
                <div class="field-group" style="margin-bottom:0">
                    <label class="field-label"><i class="bi bi-layers"></i> Gradiente (opcional)</label>
                    <div style="display:flex; gap:0.6rem; align-items:center;">
                        <input type="color" id="gradientColor" value="#1a1a2e" style="width:40px; height:40px; border:none; border-radius:8px; cursor:pointer; background:none; padding:0;">
                        <select id="gradientDir" class="form-select-custom" style="flex:1; padding:0.5rem 0.75rem;">
                            <option value="bottom">↓ De cima pra baixo</option>
                            <option value="top">↑ De baixo pra cima</option>
                            <option value="right">→ Da esquerda pra direita</option>
                            <option value="none">✕ Sem gradiente</option>
                        </select>
                    </div>
                </div>

                <!-- Upload da Logo -->
                <div class="field-group" style="margin-bottom:0">
                    <label class="field-label"><i class="bi bi-image"></i> Logo (sem fundo, PNG recomendado)</label>
                    <div class="logo-upload-zone" id="logoUploadZone">
                        <input type="file" id="logoFileInput" accept="image/*">
                        <i class="bi bi-cloud-arrow-up zone-icon"></i>
                        <div class="zone-text">Clique para selecionar a logo</div>
                        <div class="zone-hint">PNG com fundo transparente para melhor resultado</div>
                    </div>
                    <div style="margin-top:0.75rem; display:flex; align-items:center; gap:0.75rem;">
                        <label class="field-label" style="margin:0"><i class="bi bi-arrows-angle-expand"></i> Tamanho da logo</label>
                        <input type="range" id="logoSizeSlider" min="20" max="90" value="60" style="flex:1; accent-color:var(--accent);">
                        <span id="logoSizeValue" style="font-size:0.85rem; color:var(--text-secondary); width:35px;">60%</span>
                    </div>
                    <div style="display:flex; align-items:center; gap:0.75rem; margin-top:0.5rem;">
                        <label class="field-label" style="margin:0"><i class="bi bi-arrows-move"></i> Posição vertical</label>
                        <input type="range" id="logoPosSlider" min="10" max="90" value="50" style="flex:1; accent-color:var(--accent);">
                        <span id="logoPosValue" style="font-size:0.85rem; color:var(--text-secondary); width:35px;">50%</span>
                    </div>
                </div>

                <!-- Ações -->
                <div class="designer-actions">
                    <button type="button" class="btn-designer-apply" id="btnDesignerApply">
                        <i class="bi bi-check2-circle me-1"></i> Usar como ícone do Botão
                    </button>
                    <button type="button" class="btn-designer-download" id="btnDesignerDownload">
                        <i class="bi bi-download"></i> Baixar
                    </button>
                    <button type="button" class="btn-designer-cancel" id="btnDesignerCancel">
                        Cancelar
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    // 0. ALTERNAR CAMPOS BASEADO NO TIPO DE AÇÃO
    const actionSelectors = document.querySelectorAll('select[name^="action_type_"]');
    actionSelectors.forEach(select => {
        select.addEventListener('change', function() {
            const idx = this.name.split('_').pop();
            const storeContainer = document.querySelector(`[data-store-select-container="${idx}"]`);
            if (this.value === 'direct_install') {
                storeContainer.classList.remove('d-none');
            } else {
                storeContainer.classList.add('d-none');
            }
        });
    });

    // Sincronizar seletor da loja com package_name
    const storeSelectors = document.querySelectorAll('.store-app-selector');
    storeSelectors.forEach(select => {
        select.addEventListener('change', function() {
            const idx = this.dataset.targetInput;
            const packageInput = document.querySelector(`input[name="package_name_${idx}"]`);
            if (this.value) {
                packageInput.value = this.value;
            }
        });
    });

    // 1. PRÉ-VISUALIZAÇÃO DINÂMICA AO SELECIONAR ARQUIVO
    const fileInputs = document.querySelectorAll('.icon-file-input');
    fileInputs.forEach(input => {
        input.addEventListener('change', function(e) {
            const idx = this.dataset.iconIndex;
            const previewContainer = document.querySelector(`[data-preview-container="${idx}"]`);
            const urlInput = document.querySelector(`.icon-url-input[data-icon-index="${idx}"]`);
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(ev) {
                    previewContainer.innerHTML = '';
                    const img = document.createElement('img');
                    img.src = ev.target.result;
                    img.alt = 'Pré-visualização';
                    previewContainer.appendChild(img);
                    previewContainer.classList.add('has-image');
                    if (urlInput) urlInput.value = '';
                    addClearButton(previewContainer, idx);
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });

    // 2. ATUALIZAR PREVIEW QUANDO URL FOR DIGITADA MANUALMENTE
    const urlInputs = document.querySelectorAll('.icon-url-input');
    urlInputs.forEach(input => {
        input.addEventListener('blur', function() {
            const idx = this.dataset.iconIndex;
            const previewContainer = document.querySelector(`[data-preview-container="${idx}"]`);
            const fileInput = document.querySelector(`.icon-file-input[data-icon-index="${idx}"]`);
            let url = this.value.trim();
            if (url) {
                if (fileInput) fileInput.value = '';
                previewContainer.innerHTML = '';
                const img = document.createElement('img');
                img.src = url;
                img.alt = 'Ícone via URL';
                img.onerror = () => {
                    previewContainer.innerHTML = '<i class="bi bi-image icon-placeholder"></i>';
                    previewContainer.classList.remove('has-image');
                    addClearButton(previewContainer, idx);
                };
                previewContainer.appendChild(img);
                previewContainer.classList.add('has-image');
                addClearButton(previewContainer, idx);
            } else {
                const hasFile = fileInput && fileInput.files.length > 0;
                if (!hasFile) {
                    previewContainer.innerHTML = '<i class="bi bi-image icon-placeholder"></i>';
                    previewContainer.classList.remove('has-image');
                    addClearButton(previewContainer, idx);
                }
            }
        });
    });

    // 3. FUNÇÃO PARA ADICIONAR BOTÃO DE LIMPAR
    function addClearButton(container, idx) {
        const oldBtn = container.querySelector('.clear-icon-btn');
        if (oldBtn) oldBtn.remove();
        const clearBtn = document.createElement('button');
        clearBtn.type = 'button';
        clearBtn.className = 'clear-icon-btn';
        clearBtn.innerHTML = '<i class="bi bi-x"></i>';
        clearBtn.title = 'Remover ícone';
        clearBtn.setAttribute('data-clear-index', idx);
        clearBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const fileInput = document.querySelector(`.icon-file-input[data-icon-index="${idx}"]`);
            if (fileInput) fileInput.value = '';
            const urlInput = document.querySelector(`.icon-url-input[data-icon-index="${idx}"]`);
            if (urlInput) urlInput.value = '';
            container.innerHTML = '<i class="bi bi-image icon-placeholder"></i>';
            container.classList.remove('has-image');
            addClearButton(container, idx);
        });
        container.appendChild(clearBtn);
    }

    // Inicializa botões de limpar existentes
    document.querySelectorAll('[data-preview-container]').forEach(container => {
        const idx = container.getAttribute('data-preview-container');
        addClearButton(container, idx);
    });

    // 4. VALIDAÇÃO ANTES DE ENVIAR
    const form = document.getElementById('buttonsForm');
    const saveBtn = document.getElementById('saveAllBtn');
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        let isValid = true;
        for (let i = 1; i <= 3; i++) {
            const actionType = document.querySelector(`select[name="action_type_${i}"]`).value;
            const packageName = document.querySelector(`input[name="package_name_${i}"]`).value.trim();
            const iconFile = document.querySelector(`input[name="icon_file_${i}"]`).files[0];
            const iconUrl = document.querySelector(`input[name="icon_url_${i}"]`).value.trim();
            
            // Um botão é considerado "vazio" se não tiver package name E não tiver ícone (file ou URL)
            const isEmpty = (packageName === '' && !iconFile && iconUrl === '');
            if (isEmpty) {
                // Se estiver vazio, não fazemos validação de obrigatoriedade para este botão (usa o padrão do app)
                continue;
            }
            
            if (actionType === 'app' && packageName === '') {
                Swal.fire({
                    title: 'Atenção!',
                    text: `Botão ${i}: é obrigatório informar o Package Name quando o tipo for "Abrir App Específico".`,
                    icon: 'warning',
                    background: '#0B1121',
                    color: '#fff',
                    confirmButtonColor: '#0066FF'
                });
                isValid = false;
                break;
            }
            
            if (!iconFile && iconUrl === '') {
                Swal.fire({
                    title: 'Atenção!',
                    text: `Botão ${i}: informe um ícone (imagem ou URL) para o botão.`,
                    icon: 'warning',
                    background: '#0B1121',
                    color: '#fff',
                    confirmButtonColor: '#0066FF'
                });
                isValid = false;
                break;
            }
        }
        
        if (!isValid) {
            return false;
        }
        
        Swal.fire({
            title: 'Confirmar Alterações',
            text: 'Deseja atualizar as configurações dos botões?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#0066FF',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Sim, salvar!',
            cancelButtonText: 'Cancelar',
            background: '#0B1121',
            color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) {
                if (saveBtn) {
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Salvando...';
                }
                form.submit();
            }
        });
    });
    
    // 5. Tooltips via Bootstrap
    if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
})();

// ===== PRESETS DE APPS =====
(function() {
    const APP_PRESETS = [
        { name: 'Netflix',      pkg: 'com.netflix.ninja',                   action: 'app',            icon: 'assets/img/preset_netflix.png' },
        { name: 'Globoplay',    pkg: 'com.globo.globoplay',                  action: 'app',            icon: 'assets/img/preset_globoplay.png' },
        { name: 'Disney+',      pkg: 'com.disney.disneyplus',               action: 'app',            icon: 'assets/img/preset_disney.png' },
        { name: 'YouTube',      pkg: 'com.google.android.youtube',          action: 'app',            icon: 'assets/img/preset_youtube.png' },
        { name: 'UniTV',        pkg: 'com.global.unitviptv',                action: 'app',            icon: 'assets/img/preset_unitv.png' },
        { name: 'Loja de Apps', pkg: '',                                     action: 'store',          icon: 'assets/img/preset_lojadeapps.png' },
        { name: 'Meus Apps',    pkg: '',                                     action: 'installed_apps', icon: 'assets/img/preset_meusapps.png' },
    ];

    document.querySelectorAll('[data-preset-target]').forEach(grid => {
        const targetIdx = grid.dataset.presetTarget;

        APP_PRESETS.forEach(preset => {
            const chip = document.createElement('div');
            chip.className = 'preset-chip';
            chip.title = preset.name + (preset.pkg ? '\n' + preset.pkg : '');

            const img = document.createElement('img');
            img.src = preset.icon;
            img.alt = preset.name;
            img.onerror = () => { img.src = 'https://cdn-icons-png.flaticon.com/512/1055/1055644.png'; };

            const label = document.createElement('span');
            label.className = 'preset-name';
            label.textContent = preset.name;

            chip.appendChild(img);
            chip.appendChild(label);

            chip.addEventListener('click', () => {
                // Preenche action type
                const actionSelect = document.querySelector(`select[name="action_type_${targetIdx}"]`);
                if (actionSelect) {
                    let option = actionSelect.querySelector(`option[value="${preset.action}"]`);
                    if (!option) {
                        option = document.createElement('option');
                        option.value = preset.action;
                        option.style.display = 'none';
                        if (preset.action === 'store') {
                            option.textContent = '🛒 Abrir Loja de Apps';
                        } else if (preset.action === 'installed_apps') {
                            option.textContent = '📦 Abrir Meus Apps';
                        }
                        actionSelect.appendChild(option);
                    }
                    actionSelect.value = preset.action;
                    actionSelect.dispatchEvent(new Event('change'));
                }

                // Preenche package name
                const pkgInput = document.querySelector(`input[name="package_name_${targetIdx}"]`);
                if (pkgInput) pkgInput.value = preset.pkg || '';

                // Carrega a imagem como arquivo e injeta no file input (garante o upload correto)
                const fileInput = document.querySelector(`input[name="icon_file_${targetIdx}"]`);
                const previewContainer = document.querySelector(`[data-preview-container="${targetIdx}"]`);
                const urlInput = document.querySelector(`.icon-url-input[data-icon-index="${targetIdx}"]`);

                fetch(preset.icon)
                    .then(r => r.blob())
                    .then(blob => {
                        const fileName = preset.icon.split('/').pop();
                        const file = new File([blob], fileName, { type: blob.type || 'image/png' });

                        // Injeta no file input
                        const dt = new DataTransfer();
                        dt.items.add(file);
                        if (fileInput) {
                            fileInput.files = dt.files;
                        }

                        // Limpa a URL para evitar conflito (o arquivo tem prioridade)
                        if (urlInput) urlInput.value = '';

                        // Atualiza o preview
                        if (previewContainer) {
                            const objectUrl = URL.createObjectURL(blob);
                            previewContainer.innerHTML = '';
                            const img = document.createElement('img');
                            img.src = objectUrl;
                            img.alt = preset.name;
                            previewContainer.appendChild(img);
                            previewContainer.classList.add('has-image');
                        }
                    })
                    .catch(() => {
                        // Se fetch falhar (CORS ou outro), usa URL absoluta como fallback
                        const absoluteUrl = window.location.origin + window.location.pathname.replace(/\/[^/]*$/, '/') + preset.icon;
                        if (urlInput) {
                            urlInput.value = absoluteUrl;
                            urlInput.dispatchEvent(new Event('blur'));
                        }
                    });

                // Marca selected
                grid.querySelectorAll('.preset-chip').forEach(c => c.classList.remove('selected'));
                chip.classList.add('selected');
            });

            grid.appendChild(chip);
        });
    });
})();

// ===== DESIGNER VISUAL DE BOTÃO =====
(function() {
    const overlay = document.getElementById('designerModalOverlay');
    const canvas = document.getElementById('btnDesignerCanvas');
    const ctx = canvas.getContext('2d');
    const logoInput = document.getElementById('logoFileInput');
    const logoZone = document.getElementById('logoUploadZone');
    const logoSizeSlider = document.getElementById('logoSizeSlider');
    const logoPosSlider = document.getElementById('logoPosSlider');
    const logoSizeValue = document.getElementById('logoSizeValue');
    const logoPosValue = document.getElementById('logoPosValue');
    const customBgColor = document.getElementById('customBgColor');
    const gradientColor = document.getElementById('gradientColor');
    const gradientDir = document.getElementById('gradientDir');

    let currentBgColor = '#0d1117';
    let currentGradientColor = '#1a1a2e';
    let currentGradientDir = 'bottom';
    let logoImage = null;
    let currentTargetIdx = null;

    // Abrir modal
    document.querySelectorAll('.btn-open-designer').forEach(btn => {
        btn.addEventListener('click', () => {
            currentTargetIdx = btn.dataset.designerTarget;
            overlay.classList.add('open');
            drawCanvas();
        });
    });

    // Fechar modal
    document.getElementById('btnDesignerCancel').addEventListener('click', () => {
        overlay.classList.remove('open');
    });
    overlay.addEventListener('click', e => {
        if (e.target === overlay) overlay.classList.remove('open');
    });

    // Swatches de cor
    document.querySelectorAll('.color-swatch').forEach(swatch => {
        swatch.addEventListener('click', () => {
            document.querySelectorAll('.color-swatch').forEach(s => s.classList.remove('active'));
            swatch.classList.add('active');
            currentBgColor = swatch.dataset.color;
            customBgColor.value = currentBgColor;
            drawCanvas();
        });
    });

    customBgColor.addEventListener('input', () => {
        currentBgColor = customBgColor.value;
        document.querySelectorAll('.color-swatch').forEach(s => s.classList.remove('active'));
        drawCanvas();
    });

    gradientColor.addEventListener('input', () => {
        currentGradientColor = gradientColor.value;
        drawCanvas();
    });

    gradientDir.addEventListener('change', () => {
        currentGradientDir = gradientDir.value;
        drawCanvas();
    });

    // Upload da logo
    logoInput.addEventListener('change', function() {
        if (this.files && this.files[0]) {
            const reader = new FileReader();
            reader.onload = e => {
                const img = new Image();
                img.onload = () => {
                    logoImage = img;
                    logoZone.querySelector('.zone-text').textContent = this.files[0].name;
                    logoZone.querySelector('.zone-icon').className = 'bi bi-check-circle-fill zone-icon';
                    logoZone.querySelector('.zone-icon').style.color = '#2ecc71';
                    drawCanvas();
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        }
    });

    logoSizeSlider.addEventListener('input', () => {
        logoSizeValue.textContent = logoSizeSlider.value + '%';
        drawCanvas();
    });

    logoPosSlider.addEventListener('input', () => {
        logoPosValue.textContent = logoPosSlider.value + '%';
        drawCanvas();
    });

    function drawCanvas() {
        const W = canvas.width;   // 232
        const H = canvas.height;  // 500

        ctx.clearRect(0, 0, W, H);

        // Fundo
        if (currentGradientDir !== 'none') {
            let grd;
            if (currentGradientDir === 'bottom') grd = ctx.createLinearGradient(0, 0, 0, H);
            else if (currentGradientDir === 'top') grd = ctx.createLinearGradient(0, H, 0, 0);
            else grd = ctx.createLinearGradient(0, 0, W, 0);
            grd.addColorStop(0, currentBgColor);
            grd.addColorStop(1, currentGradientColor);
            ctx.fillStyle = grd;
        } else {
            ctx.fillStyle = currentBgColor;
        }
        ctx.fillRect(0, 0, W, H);

        // Logo
        if (logoImage) {
            const sizePercent = parseInt(logoSizeSlider.value) / 100;
            const posPercent = parseInt(logoPosSlider.value) / 100;

            const maxW = W * sizePercent;
            const maxH = H * sizePercent;
            const ratio = Math.min(maxW / logoImage.width, maxH / logoImage.height);
            const logoW = logoImage.width * ratio;
            const logoH = logoImage.height * ratio;

            const logoX = (W - logoW) / 2;
            const logoY = (H * posPercent) - (logoH / 2);

            ctx.drawImage(logoImage, logoX, logoY, logoW, logoH);
        }
    }

    // Aplicar canvas como ícone do botão
    document.getElementById('btnDesignerApply').addEventListener('click', () => {
        if (!currentTargetIdx) return;

        canvas.toBlob(blob => {
            const file = new File([blob], `btn_designer_${currentTargetIdx}.png`, { type: 'image/png' });

            // Injeta o arquivo no input de arquivo
            const fileInput = document.querySelector(`input[name="icon_file_${currentTargetIdx}"]`);
            const dt = new DataTransfer();
            dt.items.add(file);
            fileInput.files = dt.files;

            // Atualiza preview
            const previewContainer = document.querySelector(`[data-preview-container="${currentTargetIdx}"]`);
            previewContainer.innerHTML = '';
            const previewImg = document.createElement('img');
            previewImg.src = canvas.toDataURL('image/png');
            previewImg.alt = 'Preview do botão';
            previewContainer.appendChild(previewImg);
            previewContainer.classList.add('has-image');

            // Limpa URL input
            const urlInput = document.querySelector(`.icon-url-input[data-icon-index="${currentTargetIdx}"]`);
            if (urlInput) urlInput.value = '';

            overlay.classList.remove('open');
        }, 'image/png');
    });

    // Baixar a imagem gerada
    document.getElementById('btnDesignerDownload').addEventListener('click', () => {
        const link = document.createElement('a');
        link.download = 'botao_personalizado.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    });

    // Inicializa canvas
    drawCanvas();
})();
</script>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>