@extends('admin.layouts.app')

@section('title', $mode === 'create' ? '템플릿 생성' : '템플릿 수정')
@section('page_title', $mode === 'create' ? '템플릿 생성' : '템플릿 수정')
@section('page_desc', 'SMS 발송 화면에서 선택해 빠르게 삽입할 수 있습니다.')

@push('head')
    <style>
        .tpl-wrap{max-width:980px}
        .tpl-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start}
        @media (max-width: 980px){.tpl-grid{grid-template-columns:1fr}}

        .tpl-row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
        .tpl-actions{display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap}

        .tpl-btn{padding:8px 12px;font-size:13px;border-radius:12px;line-height:1.1;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;
            border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.06);color:inherit;cursor:pointer;}
        .tpl-btn:hover{background:rgba(255,255,255,.10);}
        .tpl-btn--primary{background:rgba(59,130,246,.88);border-color:rgba(59,130,246,.95);color:#fff;}
        .tpl-btn--primary:hover{background:rgba(59,130,246,.98);}
        .tpl-btn--ghost{background:transparent;}

        .tpl-badge{padding:6px 10px;border-radius:999px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);font-size:12px;}
        .tpl-help{line-height:1.6}
    </style>
@endpush

@section('content')
    <form method="POST"
          action="{{ $mode === 'create' ? route('admin.templates.store') : route('admin.templates.update', ['id'=>$tpl->id]) }}"
          id="tplForm">
        @csrf
        @if($mode !== 'create')
            @method('PUT')
        @endif

        <div class="tpl-wrap">
            {{-- 상단 헤더 카드 --}}
            <div class="a-card" style="padding:16px; margin-bottom:16px;">
                <div class="tpl-row" style="justify-content:space-between;">
                    <div>
                        <div style="font-weight:800; font-size:16px;">
                            {{ $mode === 'create' ? '새 템플릿 만들기' : '템플릿 수정' }}
                        </div>
                        <div class="a-muted" style="margin-top:6px;">
                            발송 화면에서 선택해 문구를 빠르게 삽입할 수 있습니다.
                        </div>
                    </div>

                    <div class="tpl-row">
                        <div class="tpl-badge">
                            상태: <b>{{ (int)old('is_active', $tpl->is_active ?? 1) === 1 ? '활성' : '비활성' }}</b>
                        </div>
                        @if($mode !== 'create')
                            <div class="tpl-badge">ID: <b>{{ $tpl->id }}</b></div>
                        @endif
                    </div>
                </div>
            </div>

            {{-- 본문 그리드 --}}
            <div class="tpl-grid">
                <div class="a-card" style="padding:16px;">
                    {{-- code --}}
                    @if($mode === 'create')
                        <div style="margin-bottom:14px;">
                            <div class="a-muted" style="margin-bottom:6px;">Code (unique)</div>
                            <input class="a-input" name="code" value="{{ old('code') }}" placeholder="ex) welcome_01">
                            <div class="a-muted" style="margin-top:6px;">영문/숫자/대시/언더바 3~60</div>
                        </div>
                    @else
                        <div style="margin-bottom:14px;">
                            <div class="a-muted" style="margin-bottom:6px;">Code</div>
                            <div><code>{{ $tpl->code }}</code></div>
                        </div>
                    @endif

                    {{-- title --}}
                    <div style="margin-bottom:14px;">
                        <div class="a-muted" style="margin-bottom:6px;">제목</div>
                        <input class="a-input" name="title" value="{{ old('title', $tpl->title ?? '') }}" placeholder="예) 설날 인사">
                    </div>

                    {{-- description --}}
                    <div style="margin-bottom:14px;">
                        <div class="a-muted" style="margin-bottom:6px;">설명 (선택)</div>
                        <input class="a-input" name="description" value="{{ old('description', $tpl->description ?? '') }}" placeholder="예) 2026 설 연휴 공지용">
                    </div>

                    {{-- active --}}
                    <div style="margin-top:10px;">
                        <label class="a-pill">
                            <input type="checkbox" name="is_active" value="1"
                                @checked((int)old('is_active', $tpl->is_active ?? 1) === 1)>
                            활성
                        </label>
                        <div class="a-muted" style="margin-top:6px;">비활성 템플릿은 발송 화면 목록에 표시되지 않습니다.</div>
                    </div>
                </div>

                <div class="a-card" style="padding:16px;">
                    {{-- body --}}
                    <div style="display:flex; justify-content:space-between; align-items:end; gap:10px; flex-wrap:wrap;">
                        <div>
                            <div class="a-muted" style="margin-bottom:6px;">본문</div>
                            <div class="a-muted">토큰을 넣어 템플릿 발송/개인화에 활용할 수 있습니다.</div>
                        </div>
                        <div class="tpl-row">
                            <button type="button" class="tpl-btn tpl-btn--ghost" data-insert="{_text_02_}">{_text_02_}</button>
                            <button type="button" class="tpl-btn tpl-btn--ghost" data-insert="{_text_03_}">{_text_03_}</button>
                            <button type="button" class="tpl-btn tpl-btn--ghost" data-insert="{_text_04_}">{_text_04_}</button>
                            <span class="a-muted">토큰 빠른 삽입</span>
                        </div>
                    </div>

                    <textarea class="a-input" name="body" id="tplBody" rows="10"
                              placeholder="예) 안녕하세요 {_text_02_} 회원님&#10;오늘 날짜는 {_text_03_} 입니다.">{{ old('body', $tpl->body ?? '') }}</textarea>

                    <div class="a-muted tpl-help" style="margin-top:10px;">
                        <b>템플릿 발송 CSV 예시</b><br>
                        <code>01036828958,홍길동,20210111</code><br>
                        <span class="a-muted">({_text_02_}=홍길동, {_text_03_}=20210111)</span>
                    </div>
                </div>
            </div>

            {{-- 하단 액션 --}}
            <div class="a-card" style="padding:16px; margin-top:16px;">
                <div class="tpl-actions">
                    <button class="tpl-btn tpl-btn--primary" type="submit">저장</button>
                    <a class="tpl-btn" href="{{ route('admin.templates.index') }}">목록</a>
                </div>
            </div>
        </div>
    </form>

    @push('scripts')
        <script>
            (() => {
                const form = document.getElementById('tplForm');
                const body = document.getElementById('tplBody');
                if (!form || !body) return;

                // token insert
                form.querySelectorAll('[data-insert]').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const token = btn.getAttribute('data-insert') || '';
                        const start = body.selectionStart ?? body.value.length;
                        const end   = body.selectionEnd ?? body.value.length;

                        body.value = body.value.slice(0,start) + token + body.value.slice(end);
                        body.focus();
                        body.selectionStart = body.selectionEnd = start + token.length;
                    });
                });
            })();
        </script>
    @endpush
@endsection
