@extends('layouts.admin')

@section('title', 'Edit Template: ' . $template->label)

@section('content')
<div class="max-w-4xl">
    {{-- Back button --}}
    <div class="mb-6">
        <a href="{{ route('admin.message-templates.index') }}" class="inline-flex items-center text-sm text-gray-500 hover:text-gray-700">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"/></svg>
            Kembali ke Daftar Template
        </a>
    </div>

    <form action="{{ route('admin.message-templates.update', $template) }}" method="POST">
        @csrf
        @method('PUT')

        {{-- Template Info --}}
        <div class="bg-white rounded-xl border border-gray-100 p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800">{{ $template->label }}</h3>
                    <p class="text-sm text-gray-500 mt-0.5">Tipe: <code class="bg-gray-100 px-1.5 py-0.5 rounded text-xs">{{ $template->type }}</code></p>
                </div>
            </div>

            {{-- Available Variables --}}
            @if($template->available_variables)
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <p class="text-sm font-medium text-blue-700 mb-2">Variabel yang tersedia:</p>
                <div class="flex flex-wrap gap-2">
                    @foreach($template->available_variables as $var)
                    <button type="button" onclick="copyVariable('{{ $var }}')"
                        class="inline-flex items-center px-2.5 py-1 bg-white border border-blue-200 text-blue-700 text-xs rounded-lg font-mono hover:outline hover:outline-2 hover:outline-blue-300 cursor-pointer">
                        <span>{</span>{{ $var }}<span>}</span>
                        <svg class="w-3 h-3 ml-1.5 text-blue-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9.75a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184"/></svg>
                    </button>
                    @endforeach
                </div>
                <p class="text-xs text-blue-500 mt-2">Klik variabel untuk menyalin ke clipboard</p>
            </div>
            @endif
        </div>

        {{-- Email Section --}}
        <div class="bg-white rounded-xl border border-gray-100 p-6 mb-6">
            <div class="flex items-center space-x-2 mb-4">
                <svg class="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/></svg>
                <h4 class="text-lg font-semibold text-gray-800">Pesan Email</h4>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Subject Email</label>
                    <input type="text" name="email_subject" value="{{ old('email_subject', $template->email_subject) }}"
                        class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 outline-none @error('email_subject') border-red-300 @enderror">
                    @error('email_subject')
                    <p class="text-xs text-red-500 mt-1">{{ $message }}</p>
                    @enderror
                    <p class="text-xs text-gray-400 mt-1">Gunakan variabel seperti {job_title} untuk data dinamis</p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Body Email</label>
                    <textarea name="email_body" rows="8"
                        class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 outline-none font-mono text-sm @error('email_body') border-red-300 @enderror">{{ old('email_body', $template->email_body) }}</textarea>
                    @error('email_body')
                    <p class="text-xs text-red-500 mt-1">{{ $message }}</p>
                    @enderror
                    <p class="text-xs text-gray-400 mt-1">Mendukung HTML. Gunakan &lt;strong&gt;, &lt;br&gt;, &lt;a href=""&gt; untuk formatting.</p>
                </div>

                {{-- Email Preview --}}
                <div>
                    <button type="button" onclick="togglePreview('email')" class="text-sm text-indigo-600 hover:text-indigo-800 font-medium">
                        Preview Email &darr;
                    </button>
                    <div id="email-preview" class="hidden mt-2 bg-gray-50 border border-gray-200 rounded-lg p-4">
                        <p class="text-xs text-gray-500 mb-1">Subject:</p>
                        <p id="email-subject-preview" class="text-sm font-medium text-gray-800 mb-3"></p>
                        <p class="text-xs text-gray-500 mb-1">Body:</p>
                        <div id="email-body-preview" class="text-sm text-gray-700 prose prose-sm max-w-none"></div>
                    </div>
                </div>
            </div>
        </div>

        {{-- WhatsApp Section --}}
        <div class="bg-white rounded-xl border border-gray-100 p-6 mb-6">
            <div class="flex items-center space-x-2 mb-4">
                <svg class="w-5 h-5 text-green-500" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 0C5.373 0 0 5.373 0 12c0 2.625.846 5.059 2.284 7.034L.789 23.492a.75.75 0 00.917.918l4.462-1.494A11.945 11.945 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 22c-2.319 0-4.476-.668-6.305-1.812l-.44-.263-3.035 1.015 1.017-3.038-.27-.447A9.955 9.955 0 012 12C2 6.486 6.486 2 12 2s10 4.486 10 10-4.486 10-10 10z"/></svg>
                <h4 class="text-lg font-semibold text-gray-800">Pesan WhatsApp</h4>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Isi Pesan WhatsApp</label>
                    <textarea name="wa_body" rows="8"
                        class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:ring-2 focus:ring-green-500 outline-none font-mono text-sm @error('wa_body') border-red-300 @enderror">{{ old('wa_body', $template->wa_body) }}</textarea>
                    @error('wa_body')
                    <p class="text-xs text-red-500 mt-1">{{ $message }}</p>
                    @enderror
                    <p class="text-xs text-gray-400 mt-1">Gunakan *teks* untuk bold, _teks_ untuk italic (format WhatsApp).</p>
                </div>

                {{-- WA Preview --}}
                <div>
                    <button type="button" onclick="togglePreview('wa')" class="text-sm text-green-600 hover:text-green-800 font-medium">
                        Preview WhatsApp &darr;
                    </button>
                    <div id="wa-preview" class="hidden mt-2 bg-green-50 border border-green-200 rounded-lg p-4">
                        <div id="wa-body-preview" class="text-sm text-gray-700 whitespace-pre-line"></div>
                    </div>
                </div>
            </div>
        </div>

        {{-- Actions --}}
        <div class="flex items-center justify-between">
            <button type="submit" class="bg-indigo-600 text-white px-8 py-3 rounded-lg font-semibold hover:outline hover:outline-2 hover:outline-indigo-800">
                Simpan Perubahan
            </button>

            <button type="button" onclick="confirmReset()" class="text-sm text-gray-500 hover:text-red-600">
                Reset ke Default
            </button>
        </div>
    </form>

    {{-- Hidden reset form --}}
    <form id="reset-form" action="{{ route('admin.message-templates.reset', $template) }}" method="POST" class="hidden">
        @csrf
    </form>
</div>

@endsection

@push('scripts')
<script>
function copyVariable(varName) {
    navigator.clipboard.writeText('{' + varName + '}');
    // Brief visual feedback
    const el = event.currentTarget;
    const orig = el.innerHTML;
    el.classList.add('bg-green-100', 'border-green-300');
    setTimeout(() => el.classList.remove('bg-green-100', 'border-green-300'), 600);
}

function togglePreview(type) {
    const preview = document.getElementById(type + '-preview');
    preview.classList.toggle('hidden');
    if (!preview.classList.contains('hidden')) {
        updatePreview(type);
    }
}

function updatePreview(type) {
    const sampleVars = {
        '{applicant_name}': 'Ahmad Fauzi',
        '{job_title}': 'Staff Administrasi',
        '{company}': 'PT Contoh Perusahaan',
        '{site_name}': 'Bursa Kerja',
        '{site_url}': '{{ config("app.url") }}',
        '{stage_name}': 'Tes Tertulis',
        '{stage_number}': '1',
        '{email}': 'ahmad@example.com',
        '{reset_url}': '{{ config("app.url") }}/reset-password?token=sample'
    };

    if (type === 'email') {
        let subject = document.querySelector('input[name="email_subject"]').value;
        let body = document.querySelector('textarea[name="email_body"]').value;
        for (const [k, v] of Object.entries(sampleVars)) {
            subject = subject.replaceAll(k, v);
            body = body.replaceAll(k, v);
        }
        document.getElementById('email-subject-preview').textContent = subject;
        document.getElementById('email-body-preview').innerHTML = body;
    } else {
        let body = document.querySelector('textarea[name="wa_body"]').value;
        for (const [k, v] of Object.entries(sampleVars)) {
            body = body.replaceAll(k, v);
        }
        // Convert *text* to bold for preview
        body = body.replace(/\*(.*?)\*/g, '<strong>$1</strong>');
        document.getElementById('wa-body-preview').innerHTML = body;
    }
}

// Auto-update preview on input
document.querySelector('input[name="email_subject"]')?.addEventListener('input', () => {
    if (!document.getElementById('email-preview').classList.contains('hidden')) updatePreview('email');
});
document.querySelector('textarea[name="email_body"]')?.addEventListener('input', () => {
    if (!document.getElementById('email-preview').classList.contains('hidden')) updatePreview('email');
});
document.querySelector('textarea[name="wa_body"]')?.addEventListener('input', () => {
    if (!document.getElementById('wa-preview').classList.contains('hidden')) updatePreview('wa');
});

function confirmReset() {
    if (confirm('Apakah Anda yakin ingin mereset template ini ke default? Perubahan yang sudah dibuat akan hilang.')) {
        document.getElementById('reset-form').submit();
    }
}
</script>
@endpush
