<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Release Email Preview &mdash; {{ $sprint }}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        body       { background: #f0f2f5; min-height: 100vh; }
        .toolbar   { background: #fff; border-bottom: 1px solid #dee2e6;
                     padding: 10px 20px; position: sticky; top: 0; z-index: 100;
                     box-shadow: 0 1px 4px rgba(0,0,0,.06); }
        .preview-frame { max-width: 680px; margin: 24px auto; border-radius: 8px;
                         box-shadow: 0 2px 12px rgba(0,0,0,.1); overflow: hidden; background: #fff; }
        #email-iframe  { width: 100%; border: none; min-height: 620px; display: block; }
        #source-block  { background: #1e1e1e; color: #d4d4d4;
                         font-family: 'Courier New', monospace; font-size: 12.5px;
                         padding: 20px; white-space: pre-wrap; word-break: break-word;
                         max-height: 520px; overflow-y: auto; margin: 0; }
        .status-badge  { font-size: 12px; padding: 4px 12px; border-radius: 20px; font-weight: 600; }
        .badge-draft   { background: #fff3cd; color: #856404; border: 1px solid #ffc107; }
        .badge-approved{ background: #d1e7dd; color: #0a3622; border: 1px solid #198754; }
        .pane-label    { background: #f8f9fa; padding: 8px 16px; font-size: 12px;
                         color: #6c757d; font-weight: 600; border-bottom: 1px solid #dee2e6;
                         display: flex; align-items: center; justify-content: space-between; }
    </style>
</head>
<body>

{{-- ────────────────────── Toolbar ────────────────────── --}}
<div class="toolbar">
    <div class="d-flex align-items-center gap-3 flex-wrap">

        {{-- Sprint Selector --}}
        <div class="d-flex align-items-center gap-2">
            <label for="sprint-select" class="form-label mb-0 fw-semibold small text-secondary">Sprint:</label>
            <select id="sprint-select" class="form-select form-select-sm" style="width:auto"
                    onchange="window.location.href='/releases/'+this.value+'/preview'">
                @foreach($availableSprints as $s)
                    <option value="{{ $s }}" @selected($s === $sprint)>{{ $s }}</option>
                @endforeach
            </select>
        </div>

        <div class="vr d-none d-md-block"></div>

        {{-- Action Buttons --}}
        <div class="d-flex gap-2 flex-wrap">
            {{-- Regenerate --}}
            <button id="btn-regen" class="btn btn-sm btn-outline-primary d-flex align-items-center gap-1"
                    onclick="regenerate()">
                <span id="regen-icon">🔄</span>
                <span id="regen-label">Regenerate</span>
                <span id="regen-spin" class="spinner-border spinner-border-sm d-none" role="status"></span>
            </button>

            {{-- Approve --}}
            <button id="btn-approve" class="btn btn-sm btn-success"
                    onclick="approve()" @disabled($approved)>
                ✅ Approve &amp; Save to Notion
            </button>

            {{-- Copy HTML --}}
            <button class="btn btn-sm btn-outline-secondary" onclick="copyHtml()" title="Copy raw HTML to clipboard">
                📋 Copy HTML
            </button>

            {{-- View Source / Preview toggle --}}
            <button class="btn btn-sm btn-outline-dark" onclick="toggleSource()">
                <span id="src-label">🔍 View Source</span>
            </button>
        </div>

        <div class="ms-auto d-flex align-items-center gap-3">
            <span id="status-badge"
                  class="status-badge {{ $approved ? 'badge-approved' : 'badge-draft' }}">
                {{ $approved ? '✓ Approved' : '⏳ Draft' }}
            </span>
            <span class="text-muted small">{{ count($releaseNotes) }} note(s)</span>
        </div>
    </div>
</div>

{{-- ────────────────────── Flash Alert ────────────────────── --}}
<div id="alert-wrap" class="px-3 pt-3">
    <div id="alert-banner" class="alert alert-dismissible fade d-none" role="alert">
        <span id="alert-msg"></span>
        <button type="button" class="btn-close" onclick="dismissAlert()"></button>
    </div>
</div>

{{-- ────────────────────── Preview / Source Panes ────────────────────── --}}
<div class="container-fluid px-3 pb-5">

    {{-- Source Pane (hidden by default) --}}
    <div id="source-container" class="preview-frame d-none">
        <div class="pane-label">
            📄 Raw HTML Source
            <span class="badge bg-secondary">{{ strlen($emailHtml) }} bytes</span>
        </div>
        <pre id="source-block">{{ htmlspecialchars($emailHtml) }}</pre>
    </div>

    {{-- Preview Pane --}}
    <div id="preview-container" class="preview-frame">
        <div class="pane-label">
            📧 Email Preview &mdash; rendered in iframe
            <span class="text-muted" style="font-weight:400;">max-width: 600px &bull; inline CSS</span>
        </div>
        {{-- sandbox: no scripts/forms/navigation — LLM-generated HTML is untrusted --}}
        <iframe id="email-iframe"
                title="Release Email Preview"
                sandbox
                srcdoc="{{ htmlspecialchars($emailHtml) }}"></iframe>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const CSRF          = document.querySelector('meta[name="csrf-token"]').content;
const currentSprint = @json($sprint);
let   currentHtml   = @json($emailHtml);
let   srcVisible    = false;

/* ── Regenerate ── */
async function regenerate() {
    const btn    = document.getElementById('btn-regen');
    const icon   = document.getElementById('regen-icon');
    const label  = document.getElementById('regen-label');
    const spin   = document.getElementById('regen-spin');

    btn.disabled = true;
    icon.textContent = '';
    label.textContent = 'Regenerating…';
    spin.classList.remove('d-none');

    try {
        const res  = await fetch(`/releases/${currentSprint}/regenerate`, {
            method : 'POST',
            headers: { 'X-CSRF-TOKEN': CSRF, 'Content-Type': 'application/json', Accept: 'application/json' },
        });
        const data = await res.json();

        if (data.html) {
            currentHtml = data.html;
            refreshPreview();
            document.getElementById('status-badge').textContent = '⏳ Draft';
            document.getElementById('status-badge').className   = 'status-badge badge-draft';
            document.getElementById('btn-approve').disabled     = false;
            showAlert('✓ Email regenerated by Claude — ' + data.count + ' note(s).', 'success');
        } else {
            showAlert('⚠ ' + (data.error ?? 'Regeneration failed'), 'danger');
        }
    } catch (e) {
        showAlert('⚠ Network error: ' + e.message, 'danger');
    } finally {
        btn.disabled = false;
        icon.textContent  = '🔄';
        label.textContent = 'Regenerate';
        spin.classList.add('d-none');
    }
}

/* ── Approve & Save ── */
async function approve() {
    const btn = document.getElementById('btn-approve');
    btn.disabled = true;
    btn.textContent = '⏳ Saving…';

    try {
        const res  = await fetch(`/releases/${currentSprint}/approve`, {
            method : 'POST',
            headers: { 'X-CSRF-TOKEN': CSRF, 'Content-Type': 'application/json', Accept: 'application/json' },
            body   : JSON.stringify({ html: currentHtml }),
        });
        const data = await res.json();

        if (data.success) {
            const link = data.notion_url ? ` <a href="${data.notion_url}" target="_blank" class="alert-link">View in Notion →</a>` : '';
            showAlert('✅ Approved and saved to Notion!' + link, 'success');
            document.getElementById('status-badge').textContent = '✓ Approved';
            document.getElementById('status-badge').className   = 'status-badge badge-approved';
        } else {
            showAlert('⚠ ' + (data.error ?? 'Approval failed'), 'danger');
            btn.disabled     = false;
            btn.innerHTML    = '✅ Approve &amp; Save to Notion';
        }
    } catch (e) {
        showAlert('⚠ Network error: ' + e.message, 'danger');
        btn.disabled  = false;
        btn.innerHTML = '✅ Approve &amp; Save to Notion';
    }
}

/* ── Copy HTML ── */
async function copyHtml() {
    try {
        await navigator.clipboard.writeText(currentHtml);
        showAlert('📋 HTML copied to clipboard!', 'success');
    } catch (e) {
        showAlert('Could not copy: ' + e.message, 'warning');
    }
}

/* ── Source / Preview Toggle ── */
function toggleSource() {
    srcVisible = !srcVisible;
    document.getElementById('source-container').classList.toggle('d-none', !srcVisible);
    document.getElementById('preview-container').classList.toggle('d-none', srcVisible);
    document.getElementById('src-label').textContent = srcVisible ? '📧 View Preview' : '🔍 View Source';
    if (srcVisible) document.getElementById('source-block').textContent = currentHtml;
}

function refreshPreview() {
    document.getElementById('email-iframe').srcdoc      = currentHtml;
    document.getElementById('source-block').textContent = currentHtml;
}

/* ── Alert ── */
function showAlert(msg, type = 'success') {
    const el = document.getElementById('alert-banner');
    el.className         = `alert alert-${type} alert-dismissible fade show`;
    document.getElementById('alert-msg').innerHTML = msg;
    setTimeout(dismissAlert, 6000);
}
function dismissAlert() {
    const el = document.getElementById('alert-banner');
    el.classList.remove('show');
    setTimeout(() => el.classList.add('d-none'), 200);
}
</script>
</body>
</html>