<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($page['title']) ?> — <?= e($funnel['name']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background: #f9fafb; min-height: 100vh; }
        .page-wrapper { max-width: 720px; margin: 0 auto; }
        .funnel-nav { background: #fff; border-bottom: 1px solid #e5e7eb; padding: .75rem 1.5rem; display: flex; align-items: center; justify-between; }
        .step-indicator { display: flex; align-items: center; gap: .5rem; }
        .step-dot { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-center: center; font-size: .75rem; font-weight: 700; border: 2px solid #e5e7eb; color: #9ca3af; transition: all .3s; }
        .step-dot.active { background: #3b6ff1; border-color: #3b6ff1; color: #fff; }
        .step-dot.done { background: #10b981; border-color: #10b981; color: #fff; }
        .step-line { width: 40px; height: 2px; background: #e5e7eb; }
        .step-line.done { background: #10b981; }
        /* Rendered section styles */
        .funnel-content img { max-width: 100%; height: auto; }
        .funnel-content a { color: #3b6ff1; }
        /* Form styles in funnel */
        .field-label { display:block; font-size:.8rem; font-weight:700; color:#374151; margin-bottom:.4rem; text-transform:uppercase; letter-spacing:.04em; }
        .field-input { width:100%; border:1.5px solid #e5e7eb; border-radius:10px; padding:.65rem 1rem; font-size:.9rem; color:#1f2937; transition:all .2s; outline:none; background:#fafafa; }
        .field-input:focus { border-color:#3b6ff1; box-shadow:0 0 0 3px rgba(59,111,241,.12); background:#fff; }
        .submit-btn { width:100%; padding:.9rem; background:linear-gradient(135deg,#3b6ff1,#6047ea); color:#fff; border:none; border-radius:12px; font-size:1rem; font-weight:700; cursor:pointer; transition:all .2s; box-shadow:0 8px 20px rgba(59,111,241,.35); }
        .submit-btn:hover { transform:translateY(-2px); }
        .radio-opt, .check-opt { display:flex; align-items:center; gap:.6rem; padding:.5rem .75rem; border:1.5px solid #e5e7eb; border-radius:8px; cursor:pointer; margin-bottom:.4rem; }
        .upload-area { border:2px dashed #d1d5db; border-radius:10px; padding:1.5rem; text-align:center; cursor:pointer; transition:all .2s; }
        .upload-area:hover { border-color:#3b6ff1; }
        .error-msg { color:#ef4444; font-size:.78rem; margin-top:.3rem; display:none; }
    </style>
</head>
<body>

<!-- Funnel Navigation -->
<div class="funnel-nav">
    <div class="font-bold text-gray-800 text-sm"><?= e($funnel['name']) ?></div>
    <div class="step-indicator">
        <?php foreach ($allPages as $i => $p): ?>
        <?php if ($i > 0): ?>
        <div class="step-line <?= $i < $currentIndex ? 'done' : '' ?>"></div>
        <?php endif; ?>
        <div class="step-dot <?= $i < $currentIndex ? 'done' : ($i === $currentIndex ? 'active' : '') ?> flex items-center justify-center">
            <?php if ($i < $currentIndex): ?>
                <i class="fas fa-check text-xs"></i>
            <?php else: ?>
                <?= $i + 1 ?>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <div class="text-xs text-gray-500">Step <?= $currentIndex + 1 ?> of <?= count($allPages) ?></div>
</div>

<!-- Page Content -->
<div class="page-wrapper funnel-content">
    <?php if (!empty($sections)): ?>
        <?php foreach ($sections as $section): ?>
        <?php renderFunnelSection($section, $page, $funnel, $formFields, $form); ?>
        <?php endforeach; ?>
    <?php else: ?>
        <!-- Default layout if no builder content -->
        <div style="background:#fff;padding:2.5rem 2rem;text-align:center;border-bottom:1px solid #e5e7eb">
            <h1 style="font-size:2rem;font-weight:800;color:#1a1a2e;margin:0 0 1rem"><?= e($page['title']) ?></h1>
        </div>
    <?php endif; ?>

    <?php if ($form && !empty($formFields) && empty($sections)): ?>
    <!-- Embedded form when no builder content -->
    <div style="background:#f9fafb;padding:2rem">
        <div style="background:#fff;border-radius:16px;padding:2rem;box-shadow:0 4px 20px rgba(0,0,0,.08)">
            <form id="funnelForm" enctype="multipart/form-data" onsubmit="submitFunnelForm(event)">
                <?php foreach ($formFields as $field): ?>
                <div class="mb-4" id="fg-<?= $field['id'] ?>">
                    <label class="field-label"><?= e($field['label']) ?><?php if($field['required']): ?><span style="color:#ef4444;margin-left:3px">*</span><?php endif; ?></label>
                    <?php renderFormField($field); ?>
                    <div class="error-msg" id="err-<?= $field['id'] ?>"></div>
                </div>
                <?php endforeach; ?>
                <button type="submit" class="submit-btn mt-2" id="funnelSubmitBtn">
                    <i class="fas fa-paper-plane mr-2"></i>
                    <?= $nextPage ? 'Continue →' : 'Submit' ?>
                </button>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <!-- Navigation -->
    <div class="flex gap-3 p-6 bg-white border-t border-gray-100">
        <?php if ($prevPage): ?>
        <a href="<?= url('/funnel/'.$funnel['slug'].'/page/'.$prevPage['id']) ?>" class="flex-1 text-center py-3 px-4 border border-gray-200 rounded-xl text-gray-600 font-semibold text-sm hover:border-gray-400 transition-colors">
            ← Back
        </a>
        <?php endif; ?>
        <?php if ($nextPage && empty($formFields)): ?>
        <a href="<?= url('/funnel/'.$funnel['slug'].'/page/'.$nextPage['id']) ?>" class="flex-1 text-center py-3 px-4 rounded-xl font-bold text-sm text-white" style="background:linear-gradient(135deg,#3b6ff1,#6047ea)">
            Continue →
        </a>
        <?php endif; ?>
    </div>
</div>

<?php
function renderFunnelSection($s, $page, $funnel, $formFields, $form) {
    $pad = $s['padding'] ?? '20px 30px';
    $bg  = $s['bg'] ?? '#ffffff';
    switch($s['type'] ?? '') {
        case 'header':
            $tag = $s['tag'] ?? 'h1';
            $safe = htmlspecialchars($s['text'] ?? '', ENT_QUOTES, 'UTF-8');
            echo "<div style='background:{$bg};padding:{$pad};text-align:{$s['align']};'><{$tag} style='color:{$s['color']};margin:0;font-family:Plus Jakarta Sans,sans-serif;font-weight:800;'>{$safe}</{$tag}></div>";
            break;
        case 'text':
            $text = nl2br(htmlspecialchars($s['text'] ?? '', ENT_QUOTES, 'UTF-8'));
            echo "<div style='background:{$bg};padding:{$pad};text-align:{$s['align']};'><p style='color:{$s['color']};margin:0;font-size:{$s['fontSize']};line-height:1.7;'>{$text}</p></div>";
            break;
        case 'image':
            if (!empty($s['src'])) {
                $src = htmlspecialchars($s['src'], ENT_QUOTES, 'UTF-8');
                echo "<div style='background:{$bg};padding:{$pad};text-align:{$s['align']};'><img src='{$src}' alt='" . htmlspecialchars($s['alt']??'', ENT_QUOTES) . "' style='max-width:{$s['width']};height:auto;border-radius:8px;'></div>";
            }
            break;
        case 'button':
            $href = htmlspecialchars($s['url'] ?? '#', ENT_QUOTES, 'UTF-8');
            $text = htmlspecialchars($s['text'] ?? 'Click Here', ENT_QUOTES, 'UTF-8');
            $pad2 = $s['size']==='large' ? '16px 40px' : ($s['size']==='small' ? '8px 20px' : '12px 30px');
            $fs   = $s['size']==='large' ? '18px' : ($s['size']==='small' ? '13px' : '15px');
            echo "<div style='background:{$bg};padding:{$pad};text-align:{$s['align']};'><a href='{$href}' style='display:inline-block;background:{$s['btnBg']};color:{$s['btnColor']};padding:{$pad2};border-radius:8px;font-weight:700;text-decoration:none;font-size:{$fs}'>{$text}</a></div>";
            break;
        case 'form':
            if (!empty($s['form_id']) && $form && $form['id'] == $s['form_id'] && !empty($formFields)) {
                echo "<div style='background:{$bg};padding:{$pad}'><div style='background:#fff;border-radius:16px;padding:2rem;box-shadow:0 4px 20px rgba(0,0,0,.08)'>";
                echo "<form id='funnelForm' enctype='multipart/form-data' onsubmit='submitFunnelForm(event)'>";
                foreach ($formFields as $field) {
                    echo "<div class='mb-4' id='fg-{$field['id']}'>";
                    echo "<label class='field-label'>" . htmlspecialchars($field['label'], ENT_QUOTES, 'UTF-8') . ($field['required'] ? "<span style='color:#ef4444;margin-left:3px'>*</span>" : "") . "</label>";
                    renderFormField($field);
                    echo "<div class='error-msg' id='err-{$field['id']}'></div></div>";
                }
                $nextLabel = isset($GLOBALS['nextPage']) && $GLOBALS['nextPage'] ? 'Continue →' : 'Submit';
                echo "<button type='submit' class='submit-btn mt-2' id='funnelSubmitBtn'><i class='fas fa-paper-plane mr-2'></i>{$nextLabel}</button></form></div></div>";
            }
            break;
        case 'divider':
            echo "<div style='background:{$bg};padding:{$pad}'><hr style='border:none;border-top:1px solid {$s['color']};margin:0;'></div>";
            break;
        case 'spacer':
            echo "<div style='background:{$bg};height:{$s['height']}'></div>";
            break;
        case 'html':
            echo "<div style='background:{$bg};padding:{$pad}'>{$s['content']}</div>";
            break;
    }
}

function renderFormField($field) {
    $n = 'field_' . $field['id'];
    $ph = htmlspecialchars($field['placeholder'] ?? '', ENT_QUOTES, 'UTF-8');
    $req = $field['required'] ? 'required' : '';
    $opts = array_filter(array_map('trim', explode("\n", $field['options'] ?? '')));
    switch($field['field_type']) {
        case 'text':    echo "<input type='text' name='{$n}' class='field-input' placeholder='{$ph}' {$req}>"; break;
        case 'email':   echo "<input type='email' name='{$n}' class='field-input' placeholder='{$ph}' {$req}>"; break;
        case 'phone':   echo "<input type='tel' name='{$n}' class='field-input' placeholder='{$ph}' {$req}>"; break;
        case 'number':  echo "<input type='number' name='{$n}' class='field-input' placeholder='{$ph}' {$req}>"; break;
        case 'date':    echo "<input type='date' name='{$n}' class='field-input' {$req}>"; break;
        case 'textarea':echo "<textarea name='{$n}' rows='4' class='field-input' placeholder='{$ph}' {$req}></textarea>"; break;
        case 'select':
            echo "<select name='{$n}' class='field-input' {$req}><option value=''>Select...</option>";
            foreach ($opts as $o) echo "<option value='" . htmlspecialchars($o, ENT_QUOTES, 'UTF-8') . "'>" . htmlspecialchars($o, ENT_QUOTES, 'UTF-8') . "</option>";
            echo "</select>"; break;
        case 'radio':
            foreach ($opts as $o) {
                $oe = htmlspecialchars($o, ENT_QUOTES, 'UTF-8');
                echo "<label class='radio-opt'><input type='radio' name='{$n}' value='{$oe}' {$req}><span style='font-size:.875rem;color:#374151'>{$oe}</span></label>";
            } break;
        case 'checkbox':
            foreach ($opts as $o) {
                $oe = htmlspecialchars($o, ENT_QUOTES, 'UTF-8');
                echo "<label class='check-opt'><input type='checkbox' name='{$n}[]' value='{$oe}'><span style='font-size:.875rem;color:#374151'>{$oe}</span></label>";
            } break;
        case 'image':
            echo "<div class='upload-area' onclick=\"document.getElementById('{$n}').click()\"><i class='fas fa-image' style='font-size:2rem;color:#d1d5db;display:block;margin-bottom:.5rem'></i><p style='color:#6b7280;font-size:.875rem' id='img-label-{$field['id']}'>Click to upload image</p></div>";
            echo "<input type='file' id='{$n}' name='{$n}' class='hidden' accept='.jpg,.jpeg,.png' {$req} onchange=\"document.getElementById('img-label-{$field['id']}').textContent=this.files[0]?.name||'Click to upload'\">";
            break;
        case 'file':
            echo "<div class='upload-area' onclick=\"document.getElementById('{$n}').click()\"><i class='fas fa-file' style='font-size:2rem;color:#d1d5db;display:block;margin-bottom:.5rem'></i><p style='color:#6b7280;font-size:.875rem' id='file-label-{$field['id']}'>Click to upload file</p></div>";
            echo "<input type='file' id='{$n}' name='{$n}' class='hidden' {$req} onchange=\"document.getElementById('file-label-{$field['id']}').textContent=this.files[0]?.name||'Click to upload'\">";
            break;
    }
}
?>

<script>
const FUNNEL_SLUG = '<?= e($funnel['slug']) ?>';
const NEXT_PAGE_ID = <?= $nextPage ? $nextPage['id'] : 'null' ?>;
const FORM_SLUG = <?= $form ? json_encode($form['slug']) : 'null' ?>;
const APP_URL = '<?= APP_URL ?>';

async function submitFunnelForm(e) {
    e.preventDefault();
    const btn = document.getElementById('funnelSubmitBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';

    document.querySelectorAll('.error-msg').forEach(el => el.style.display = 'none');

    const formData = new FormData(document.getElementById('funnelForm'));
    const resp = await fetch(APP_URL + '/form/' + FORM_SLUG + '/submit', {
        method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:formData
    });
    const data = await resp.json();

    if (data.success) {
        if (data.whatsapp_url) window.open(data.whatsapp_url, '_blank');
        if (NEXT_PAGE_ID) {
            setTimeout(() => { window.location = APP_URL + '/funnel/' + FUNNEL_SLUG + '/page/' + NEXT_PAGE_ID; }, 800);
        } else {
            document.querySelector('.page-wrapper').innerHTML = `
                <div style="text-align:center;padding:4rem 2rem;background:#fff">
                    <div style="width:80px;height:80px;background:#d1fae5;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1.5rem">
                        <i class="fas fa-check-circle" style="font-size:2.5rem;color:#10b981"></i>
                    </div>
                    <h2 style="font-size:1.75rem;font-weight:800;color:#1a1a2e;margin:0 0 .75rem">${data.message}</h2>
                    ${data.whatsapp_url ? `<a href="${data.whatsapp_url}" target="_blank" style="display:inline-flex;align-items:center;gap:.5rem;padding:.75rem 1.5rem;background:linear-gradient(135deg,#25d366,#128c7e);color:#fff;border-radius:10px;font-weight:700;text-decoration:none;margin-top:1rem"><i class="fab fa-whatsapp"></i>Open WhatsApp</a>` : ''}
                </div>`;
        }
    } else {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>' + (NEXT_PAGE_ID ? 'Continue →' : 'Submit');
        if (data.errors) {
            Object.entries(data.errors).forEach(([fid, msg]) => {
                const el = document.getElementById('err-' + fid);
                if (el) { el.style.display='flex'; el.textContent=msg; }
            });
        }
    }
}
</script>
</body>
</html>
