<?php
if (!defined('ROOT_PATH')) { http_response_code(403); exit; }
require_once ROOT_PATH . '/admin/templates/header.php';
$isRtl     = \Core\System\Language::direction() === 'rtl';
$priceDisp = number_format((float)($product['sale_price'] ?: $product['price'])) . ' ' . ($product['currency'] ?? 'DZD');
$imageUrl  = $product['featured_image'] ?? '';
if($imageUrl && !str_starts_with($imageUrl,'http')){
    $scheme   = (!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https':'http';
    $imageUrl = $scheme.'://'.$_SERVER['HTTP_HOST'].'/'.ltrim($imageUrl,'/');
}
?>
<div class="content-wrapper"><section class="content pt-3"><div class="container-fluid pb-5">

<div class="d-flex align-items-center justify-content-between mb-4">
    <div class="d-flex align-items-center gap-3">
        <?php if(!empty($product['featured_image'])): ?>
        <img src="<?= htmlspecialchars($product['featured_image']) ?>" width="52" height="52" class="rounded-3 border object-fit-cover shadow-sm">
        <?php endif; ?>
        <div>
            <h4 class="mb-0 fw-bold"><?= htmlspecialchars($product['title']) ?></h4>
            <span class="text-muted small"><i class="bi bi-tag me-1"></i><?= $priceDisp ?></span>
        </div>
    </div>
    <a href="/admin/facebook-ads" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-<?= $isRtl?'right':'left' ?> me-1"></i><?= fbt('fb_ads.back','Back') ?>
    </a>
</div>

<?php if(!$isConfigured): ?>
<div class="alert alert-warning border-0 shadow-sm mb-4">
    <i class="bi bi-exclamation-triangle-fill me-2"></i><?= fbt('fb_ads.not_configured','Facebook not configured.') ?>
    <a href="/admin/facebook-ads/settings" class="alert-link ms-2"><?= fbt('fb_ads.go_settings','Go to Settings →') ?></a>
</div>
<?php endif; ?>

<div class="row g-4">
<!-- ── Left: Ad builder ───────────────────────────── -->
<div class="col-lg-7">

    <!-- Step 1: Campaign objective -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold"><span class="badge bg-primary rounded-pill me-2">1</span><?= fbt('fb_ads.step1','Campaign Objective') ?></h6>
        </div>
        <div class="card-body">
            <input type="text" id="campaign-name" class="form-control mb-3"
                   value="<?= htmlspecialchars($product['title']) ?> — <?= date('d/m/Y') ?>"
                   placeholder="<?= fbt('fb_ads.campaign_name_placeholder','Campaign name...') ?>">
            <div class="row g-2">
            <?php foreach([
                ['OUTCOME_SALES',      '💰', fbt('fb_ads.obj_sales','Sales'),      fbt('fb_ads.obj_sales_hint','Drive purchases')],
                ['OUTCOME_TRAFFIC',    '🔗', fbt('fb_ads.obj_traffic','Traffic'),   fbt('fb_ads.obj_traffic_hint','Send people to your site')],
                ['OUTCOME_AWARENESS',  '📢', fbt('fb_ads.obj_awareness','Awareness'),fbt('fb_ads.obj_awareness_hint','Reach more people')],
                ['OUTCOME_ENGAGEMENT', '💬', fbt('fb_ads.obj_engagement','Engagement'),fbt('fb_ads.obj_engagement_hint','Get more interactions')],
            ] as [$val,$emoji,$label,$hint]): ?>
            <div class="col-6 col-md-3">
                <label class="objective-card text-center p-3 border rounded-3 d-block" style="cursor:pointer;transition:all .15s">
                    <input type="radio" name="objective" value="<?= $val ?>" class="d-none obj-radio" <?= $val==='OUTCOME_SALES'?'checked':'' ?>>
                    <div style="font-size:1.8rem"><?= $emoji ?></div>
                    <div class="fw-semibold small mt-1"><?= $label ?></div>
                    <div style="font-size:.7rem;color:#94a3b8"><?= $hint ?></div>
                </label>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Step 2: Ad Copy (with AI) -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
            <h6 class="mb-0 fw-semibold"><span class="badge bg-primary rounded-pill me-2">2</span><?= fbt('fb_ads.step2','Ad Copy') ?></h6>
            <?php if($aiAvailable): ?>
            <div class="d-flex gap-2 align-items-center">
                <select id="copy-lang" class="form-select form-select-sm" style="width:auto">
                    <option value="ar">🇸🇦 العربية</option>
                    <option value="en">🇬🇧 English</option>
                </select>
                <button class="btn btn-sm fw-semibold" style="background:#1877f2;color:#fff;border:none" onclick="generateCopy()">
                    <i class="bi bi-stars me-1"></i><?= fbt('fb_ads.generate_with_ai','Generate with AI') ?>
                </button>
            </div>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <div id="copy-loading" style="display:none" class="text-center py-3">
                <div class="spinner-border text-primary mb-2" style="width:1.4rem;height:1.4rem"></div>
                <div class="small text-muted"><?= fbt('fb_ads.generating_copy','AI is writing your ad...') ?></div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">
                    <?= fbt('fb_ads.primary_text','Primary Text') ?>
                    <span class="text-muted fw-normal">(<?= fbt('fb_ads.max_125','max 125 chars') ?>)</span>
                </label>
                <textarea id="ad-text" class="form-control" rows="4" maxlength="125" dir="auto"
                          placeholder="<?= fbt('fb_ads.primary_text_placeholder','Write your main ad message...') ?>"
                ><?= htmlspecialchars(strip_tags($product['short_description'] ?? '')) ?></textarea>
                <div class="text-end small text-muted mt-1"><span id="text-count">0</span>/125</div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">
                    <?= fbt('fb_ads.headline','Headline') ?>
                    <span class="text-muted fw-normal">(<?= fbt('fb_ads.max_40','max 40 chars') ?>)</span>
                </label>
                <input type="text" id="ad-headline" class="form-control" maxlength="40"
                       value="<?= htmlspecialchars($product['title']) ?>"
                       placeholder="<?= fbt('fb_ads.headline_placeholder','Short catchy headline...') ?>">
                <div class="text-end small text-muted mt-1"><span id="headline-count">0</span>/40</div>
            </div>

            <div>
                <label class="form-label fw-semibold small">
                    <?= fbt('fb_ads.description','Description') ?>
                    <span class="text-muted fw-normal">(<?= fbt('fb_ads.max_30','max 30 chars') ?>)</span>
                </label>
                <input type="text" id="ad-description" class="form-control" maxlength="30"
                       placeholder="<?= fbt('fb_ads.description_placeholder','Supports the headline...') ?>">
                <div class="text-end small text-muted mt-1"><span id="desc-count">0</span>/30</div>
            </div>
        </div>
    </div>

    <!-- Step 3: Audience -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
            <h6 class="mb-0 fw-semibold"><span class="badge bg-primary rounded-pill me-2">3</span><?= fbt('fb_ads.step3','Target Audience') ?></h6>
            <?php if($aiAvailable): ?>
            <button class="btn btn-sm btn-outline-secondary" onclick="suggestAudience()">
                <i class="bi bi-stars me-1"></i><?= fbt('fb_ads.ai_suggest','AI Suggest') ?>
            </button>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <div id="audience-loading" style="display:none" class="text-center py-2 mb-3">
                <div class="spinner-border spinner-border-sm text-primary me-2"></div>
                <span class="small text-muted"><?= fbt('fb_ads.suggesting_audience','AI is analyzing...') ?></span>
            </div>
            <div id="audience-suggestion" style="display:none" class="alert alert-info border-0 small mb-3 py-2"></div>

            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label fw-semibold small"><?= fbt('fb_ads.country','Country') ?></label>
                    <select id="targeting-country" class="form-select">
                        <option value="DZ" <?= ($cfg['default_country']??'DZ')==='DZ'?'selected':'' ?>>🇩🇿 Algeria</option>
                        <option value="MA">🇲🇦 Morocco</option>
                        <option value="TN">🇹🇳 Tunisia</option>
                        <option value="EG">🇪🇬 Egypt</option>
                        <option value="SA">🇸🇦 Saudi Arabia</option>
                        <option value="AE">🇦🇪 UAE</option>
                        <option value="FR">🇫🇷 France</option>
                        <option value="US">🇺🇸 USA</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold small"><?= fbt('fb_ads.gender','Gender') ?></label>
                    <select id="targeting-gender" class="form-select">
                        <option value=""><?= fbt('fb_ads.all_genders','All') ?></option>
                        <option value="1"><?= fbt('fb_ads.male','Male') ?></option>
                        <option value="2"><?= fbt('fb_ads.female','Female') ?></option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold small"><?= fbt('fb_ads.age_range','Age Range') ?></label>
                    <div class="d-flex gap-2 align-items-center">
                        <input type="number" id="age-min" class="form-control" value="18" min="13" max="65" style="width:70px">
                        <span>–</span>
                        <input type="number" id="age-max" class="form-control" value="45" min="13" max="65" style="width:70px">
                    </div>
                </div>
            </div>

            <!-- Interests -->
            <div class="mt-3">
                <label class="form-label fw-semibold small"><?= fbt('fb_ads.interests','Interests') ?> <span class="text-muted fw-normal">(<?= fbt('fb_ads.optional','optional') ?>)</span></label>
                <div class="d-flex flex-wrap gap-2" id="interests-container">
                <?php foreach($fbInterests as $interest): ?>
                <label class="interest-tag" style="cursor:pointer">
                    <input type="checkbox" class="d-none interest-cb" data-id="<?= $interest['id'] ?>" data-name="<?= htmlspecialchars($interest['name']) ?>">
                    <span class="badge bg-light text-dark border px-3 py-2" style="font-size:.8rem;transition:all .1s"><?= htmlspecialchars($interest['name']) ?></span>
                </label>
                <?php endforeach; ?>
                </div>
                <div id="interests-hint" class="form-text"><?= fbt('fb_ads.interests_hint','Click to select interests for targeting') ?></div>
            </div>
        </div>
    </div>

    <!-- Step 4: Budget & Duration -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold"><span class="badge bg-primary rounded-pill me-2">4</span><?= fbt('fb_ads.step4','Budget & Duration') ?></h6>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label fw-semibold small"><?= fbt('fb_ads.daily_budget','Daily Budget') ?></label>
                    <div class="input-group">
                        <input type="number" id="daily-budget" class="form-control" value="500" min="100" step="50">
                        <span class="input-group-text">DZD</span>
                    </div>
                    <div class="form-text"><?= fbt('fb_ads.min_budget','Minimum: 100 DZD/day') ?></div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold small"><?= fbt('fb_ads.duration','Duration') ?></label>
                    <div class="input-group">
                        <input type="number" id="duration-days" class="form-control" value="7" min="1" max="90">
                        <span class="input-group-text"><?= fbt('fb_ads.days','days') ?></span>
                    </div>
                </div>
            </div>

            <!-- Total cost display -->
            <div class="mt-3 p-3 rounded-3" style="background:#f0f4ff">
                <div class="d-flex justify-content-between align-items-center">
                    <span class="fw-semibold"><?= fbt('fb_ads.total_budget','Total Budget') ?></span>
                    <span class="fw-bold fs-5 text-primary" id="total-budget">3,500 DZD</span>
                </div>
                <div class="text-muted small mt-1" id="budget-note">7 days × 500 DZD/day</div>
            </div>
        </div>
    </div>

    <!-- Launch button -->
    <button id="launch-btn" onclick="launchAd()" class="btn w-100 fw-bold py-3 fs-6"
            style="background:linear-gradient(135deg,#1877f2,#0c5fcc);color:#fff;border:none;border-radius:12px;box-shadow:0 4px 20px rgba(24,119,242,.35)"
            <?= !$isConfigured ? 'disabled' : '' ?>>
        <i class="bi bi-facebook me-2"></i><?= fbt('fb_ads.launch_ad','Launch Facebook Ad') ?>
        <span id="launch-spinner" class="spinner-border spinner-border-sm ms-2 d-none"></span>
    </button>

    <div class="text-center mt-2 small text-muted">
        <i class="bi bi-info-circle me-1"></i><?= fbt('fb_ads.paused_note','Ad will be created as PAUSED for your review before going live.') ?>
    </div>

    <div id="launch-result" class="mt-3" style="display:none"></div>

</div>

<!-- ── Right: Live Preview ───────────────────────── -->
<div class="col-lg-5">
    <div class="card border-0 shadow-sm sticky-top" style="top:80px">
        <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
            <h6 class="mb-0 fw-semibold"><i class="bi bi-phone me-2 text-muted"></i><?= fbt('fb_ads.preview','Ad Preview') ?></h6>
            <div class="d-flex gap-1">
                <button class="btn btn-sm btn-outline-secondary preview-btn active" data-type="feed" onclick="switchPreview(this,'feed')">Feed</button>
                <button class="btn btn-sm btn-outline-secondary preview-btn" data-type="story" onclick="switchPreview(this,'story')">Story</button>
            </div>
        </div>
        <div class="card-body p-3" style="background:#f0f2f5">

            <!-- Facebook Feed Preview -->
            <div id="preview-feed" style="max-width:360px;margin:0 auto">
                <div style="background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.1);overflow:hidden;font-family:system-ui,sans-serif">
                    <!-- Header -->
                    <div style="padding:12px 14px;display:flex;align-items:center;gap:10px">
                        <?php if($imageUrl): ?>
                        <img src="<?= htmlspecialchars($product['featured_image']??'') ?>" style="width:40px;height:40px;border-radius:50%;object-fit:cover">
                        <?php else: ?>
                        <div style="width:40px;height:40px;border-radius:50%;background:#1877f2;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold">F</div>
                        <?php endif; ?>
                        <div>
                            <div style="font-weight:700;font-size:.88rem;color:#1c1e21"><?= htmlspecialchars(\Core\System\ThemeManager::getSetting('site_name','Your Store')) ?></div>
                            <div style="font-size:.72rem;color:#65676b">Sponsored · <i class="bi bi-globe2" style="font-size:.65rem"></i></div>
                        </div>
                        <div style="margin-<?= $isRtl?'right':'left' ?>:auto;font-size:1.2rem;color:#65676b">···</div>
                    </div>
                    <!-- Primary text -->
                    <div id="preview-text" style="padding:0 14px 10px;font-size:.88rem;color:#1c1e21;line-height:1.5;white-space:pre-line">
                        <?= htmlspecialchars(strip_tags($product['short_description'] ?? '')) ?>
                    </div>
                    <!-- Product image -->
                    <?php if($imageUrl): ?>
                    <img src="<?= htmlspecialchars($imageUrl) ?>" style="width:100%;max-height:220px;object-fit:cover">
                    <?php else: ?>
                    <div style="height:180px;background:#f0f2f5;display:flex;align-items:center;justify-content:center;color:#bec3c9;font-size:3rem"><i class="bi bi-image"></i></div>
                    <?php endif; ?>
                    <!-- Headline bar -->
                    <div style="padding:12px 14px;border-top:1px solid #e4e6eb;display:flex;justify-content:space-between;align-items:center">
                        <div>
                            <div id="preview-headline" style="font-weight:700;font-size:.9rem;color:#1c1e21"><?= htmlspecialchars($product['title']) ?></div>
                            <div id="preview-description" style="font-size:.78rem;color:#65676b">$priceDisp</div>
                        </div>
                        <button style="background:#e4e6eb;border:none;padding:7px 14px;border-radius:6px;font-weight:600;font-size:.82rem;cursor:pointer">Shop Now</button>
                    </div>
                    <!-- Reactions bar -->
                    <div style="padding:8px 14px;display:flex;gap:16px;border-top:1px solid #e4e6eb">
                        <span style="font-size:.78rem;color:#65676b">👍 Like</span>
                        <span style="font-size:.78rem;color:#65676b">💬 Comment</span>
                        <span style="font-size:.78rem;color:#65676b">↗ Share</span>
                    </div>
                </div>
            </div>

            <!-- Story Preview (hidden by default) -->
            <div id="preview-story" style="display:none;max-width:200px;margin:0 auto">
                <div style="background:#000;border-radius:14px;overflow:hidden;aspect-ratio:9/16;position:relative">
                    <?php if($imageUrl): ?>
                    <img src="<?= htmlspecialchars($imageUrl) ?>" style="width:100%;height:100%;object-fit:cover">
                    <?php endif; ?>
                    <div style="position:absolute;bottom:0;left:0;right:0;padding:14px;background:linear-gradient(transparent,rgba(0,0,0,.8));color:#fff">
                        <div id="preview-story-text" style="font-size:.78rem;margin-bottom:8px;line-height:1.4"></div>
                        <button style="background:#1877f2;color:#fff;border:none;width:100%;padding:8px;border-radius:6px;font-size:.78rem;font-weight:700">Shop Now</button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

</div><!-- /row -->

</div></section></div>

<script>
(function(){
'use strict';
var PRODUCT_ID = <?= (int)$product['id'] ?>;
var CSRF       = '<?= \Core\System\Csrf::token() ?>';
var selectedInterests = [];

// ── Objective cards ───────────────────────────────────────────
document.querySelectorAll('.objective-card').forEach(function(card){
    card.addEventListener('click',function(){
        document.querySelectorAll('.objective-card').forEach(c=>{c.style.borderColor='';c.style.background='';});
        card.style.borderColor='#1877f2'; card.style.background='#eff6ff';
        card.querySelector('.obj-radio').checked = true;
    });
    if(card.querySelector('.obj-radio').checked){card.style.borderColor='#1877f2';card.style.background='#eff6ff';}
});

// ── Char counters ─────────────────────────────────────────────
function bindCounter(inputId, countId){
    var el = document.getElementById(inputId);
    var ct = document.getElementById(countId);
    if(!el||!ct) return;
    var update = ()=>{ ct.textContent=el.value.length; };
    el.addEventListener('input',update); update();
}
bindCounter('ad-text','text-count');
bindCounter('ad-headline','headline-count');
bindCounter('ad-description','desc-count');

// ── Live preview update ───────────────────────────────────────
['ad-text','ad-headline','ad-description'].forEach(function(id){
    document.getElementById(id)?.addEventListener('input', updatePreview);
});
function updatePreview(){
    var text = document.getElementById('ad-text')?.value || '';
    var hl   = document.getElementById('ad-headline')?.value || '';
    var desc = document.getElementById('ad-description')?.value || '';
    document.getElementById('preview-text').textContent = text;
    document.getElementById('preview-headline').textContent = hl;
    document.getElementById('preview-description').textContent = desc;
    document.getElementById('preview-story-text').textContent = text.substring(0,80);
}

// ── Budget calc ───────────────────────────────────────────────
function updateBudget(){
    var daily = parseInt(document.getElementById('daily-budget')?.value||0);
    var days  = parseInt(document.getElementById('duration-days')?.value||1);
    var total = daily * days;
    document.getElementById('total-budget').textContent = total.toLocaleString() + ' DZD';
    document.getElementById('budget-note').textContent  = days + ' days × ' + daily.toLocaleString() + ' DZD/day';
}
document.getElementById('daily-budget')?.addEventListener('input',updateBudget);
document.getElementById('duration-days')?.addEventListener('input',updateBudget);

// ── Interests ─────────────────────────────────────────────────
document.querySelectorAll('.interest-cb').forEach(function(cb){
    cb.closest('label').addEventListener('click',function(e){
        e.preventDefault();
        var isChecked = !cb.checked;
        cb.checked = isChecked;
        var span = cb.nextElementSibling;
        if(isChecked){
            span.classList.remove('bg-light','text-dark');
            span.classList.add('bg-primary','text-white');
            selectedInterests.push({id:cb.dataset.id, name:cb.dataset.name});
        } else {
            span.classList.add('bg-light','text-dark');
            span.classList.remove('bg-primary','text-white');
            selectedInterests = selectedInterests.filter(i=>i.id!==cb.dataset.id);
        }
    });
});

// ── Preview switcher ──────────────────────────────────────────
window.switchPreview = function(btn, type){
    document.querySelectorAll('.preview-btn').forEach(b=>{b.classList.remove('active');b.classList.add('btn-outline-secondary');});
    btn.classList.add('active');
    document.getElementById('preview-feed').style.display  = type==='feed'?'':'none';
    document.getElementById('preview-story').style.display = type==='story'?'':'none';
};

// ── Generate copy with AI ─────────────────────────────────────
window.generateCopy = function(){
    var loading = document.getElementById('copy-loading');
    var obj     = document.querySelector('.obj-radio:checked')?.value || 'OUTCOME_SALES';
    var lang    = document.getElementById('copy-lang')?.value || 'ar';
    loading.style.display='';

    var fd=new FormData(); fd.append('_csrf',CSRF); fd.append('product_id',PRODUCT_ID); fd.append('objective',obj); fd.append('lang',lang);
    fetch('/admin/facebook-ads/generate-copy',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        loading.style.display='none';
        if(d.success){
            document.getElementById('ad-text').value = d.primary_text; document.getElementById('ad-text').dispatchEvent(new Event('input'));
            document.getElementById('ad-headline').value = d.headline; document.getElementById('ad-headline').dispatchEvent(new Event('input'));
            document.getElementById('ad-description').value = d.description; document.getElementById('ad-description').dispatchEvent(new Event('input'));
            updatePreview();
        } else { alert('❌ '+d.message); }
    }).catch(e=>{loading.style.display='none';alert('Error: '+e.message);});
};

// ── Suggest audience ──────────────────────────────────────────
window.suggestAudience = function(){
    var loading = document.getElementById('audience-loading');
    var suggest = document.getElementById('audience-suggestion');
    loading.style.display='';

    var fd=new FormData(); fd.append('_csrf',CSRF); fd.append('product_id',PRODUCT_ID); fd.append('lang','ar');
    fetch('/admin/facebook-ads/suggest-audience',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        loading.style.display='none';
        if(d.success&&d.audience){
            var a=d.audience;
            if(a.age_min){document.getElementById('age-min').value=a.age_min;}
            if(a.age_max){document.getElementById('age-max').value=a.age_max;}
            if(a.gender&&a.gender!=='all'){document.getElementById('targeting-gender').value=a.gender==='male'?'1':'2';}
            suggest.style.display='';
            suggest.innerHTML='<i class="bi bi-stars me-1 text-primary"></i><strong><?= fbt('fb_ads.ai_suggestion','AI Suggestion:') ?></strong> '+(a.reason||'')+(a.interests?'<br><span class="text-muted">Interests: '+a.interests.join(', ')+'</span>':'');
        }
    }).catch(e=>{loading.style.display='none';});
};

// ── Launch Ad ─────────────────────────────────────────────────
window.launchAd = function(){
    var btn   = document.getElementById('launch-btn');
    var spin  = document.getElementById('launch-spinner');
    var res   = document.getElementById('launch-result');
    var text  = document.getElementById('ad-text')?.value.trim();
    var hl    = document.getElementById('ad-headline')?.value.trim();
    var desc  = document.getElementById('ad-description')?.value.trim();
    var name  = document.getElementById('campaign-name')?.value.trim();

    if(!text||!name){ alert('<?= fbt('fb_ads.error_missing','Fill in the campaign name and ad text.') ?>'); return; }

    if(!confirm('<?= fbt('fb_ads.confirm_launch','Launch this ad on Facebook? It will be created as PAUSED for review.') ?>')) return;

    btn.disabled=true; spin.classList.remove('d-none'); res.style.display='none';

    var fd = new FormData();
    fd.append('_csrf', CSRF);
    fd.append('product_id', PRODUCT_ID);
    fd.append('campaign_name', name);
    fd.append('objective', document.querySelector('.obj-radio:checked')?.value || 'OUTCOME_SALES');
    fd.append('daily_budget', document.getElementById('daily-budget')?.value || 500);
    fd.append('duration_days', document.getElementById('duration-days')?.value || 7);
    fd.append('ad_text', text);
    fd.append('ad_headline', hl);
    fd.append('ad_description', desc);
    fd.append('countries', document.getElementById('targeting-country')?.value || 'DZ');
    fd.append('genders', document.getElementById('targeting-gender')?.value || '');
    fd.append('age_min', document.getElementById('age-min')?.value || 18);
    fd.append('age_max', document.getElementById('age-max')?.value || 55);
    fd.append('interests', JSON.stringify(selectedInterests));

    fetch('/admin/facebook-ads/launch',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(function(d){
        btn.disabled=false; spin.classList.add('d-none');
        res.style.display='';
        if(d.success){
            res.innerHTML = '<div class="alert border-0 py-3" style="background:#f0fdf4;border-left:4px solid #22c55e !important">'
                + '<div class="fw-bold text-success fs-5 mb-2">✅ <?= fbt('fb_ads.ad_created','Ad Created Successfully!') ?></div>'
                + '<p class="text-muted small mb-3"><?= fbt('fb_ads.ad_paused_note','Your ad is PAUSED. Review it in Ads Manager and click PUBLISH to go live.') ?></p>'
                + '<div class="d-flex gap-2">'
                + '<a href="/admin/facebook-ads/campaign/'+d.campaign_id+'" class="btn btn-sm btn-outline-success">'
                + '<i class="bi bi-eye me-1"></i><?= fbt('fb_ads.view_campaign','View Campaign') ?></a>'
                + '<a href="'+d.ads_manager_url+'" target="_blank" rel="noopener" class="btn btn-sm btn-primary">'
                + '<i class="bi bi-facebook me-1"></i><?= fbt('fb_ads.open_ads_manager','Open in Ads Manager →') ?></a>'
                + '</div></div>';
        } else {
            res.innerHTML = '<div class="alert alert-danger border-0 py-3"><div class="fw-bold mb-1">❌ <?= fbt('fb_ads.error','Error') ?></div>'
                + '<div class="small">'+d.message+'</div>'
                + (d.campaign_id ? '<a href="/admin/facebook-ads/campaign/'+d.campaign_id+'" class="btn btn-sm btn-outline-danger mt-2"><?= fbt('fb_ads.view_error','View Error Details') ?></a>' : '')
                + '</div>';
        }
        res.scrollIntoView({behavior:'smooth',block:'nearest'});
    })
    .catch(function(e){
        btn.disabled=false; spin.classList.add('d-none');
        res.style.display='';
        res.innerHTML='<div class="alert alert-danger border-0">❌ Network error: '+e.message+'</div>';
    });
};

})();
</script>

<style>
.objective-card:hover{border-color:#1877f2!important;background:#eff6ff!important}
.interest-tag span{transition:all .1s}
</style>

<?php require_once ROOT_PATH . '/admin/templates/footer.php'; ?>
