@extends('layouts.app')
@section('title', 'Edit · ' . $page->title)

@section('content')
<section class="content-header">
    <h1><i class="fas fa-pen-ruler"></i> {{ $page->title }}
        <small>Page builder</small></h1>
</section>

<section class="content" x-data="vsBuilder()" x-init="init()">
    @include('clinicSite::admin._flash')

    <div class="row">
        {{-- ============ Builder canvas ============ --}}
        <div class="col-md-8">
            @component('components.widget', ['class' => 'box-primary'])
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;">
                    <h4 style="margin:0;">Sections</h4>
                    <div>
                        <a href="{{ route('cs.preview', $page->id) }}" target="_blank" class="btn btn-sm btn-default"><i class="fa fa-eye"></i> Preview</a>
                        <button type="button" class="btn btn-sm btn-success" @click="save()" :disabled="saving">
                            <i class="fa" :class="saving ? 'fa-spinner fa-spin' : 'fa-save'"></i> <span x-text="saving ? 'Saving…' : 'Save sections'"></span>
                        </button>
                    </div>
                </div>

                <template x-if="blocks.length === 0">
                    <p class="text-muted text-center" style="padding:30px;">No sections yet. Add one from the panel on the right →</p>
                </template>

                <template x-for="(block, i) in blocks" :key="block.id">
                    <div style="border:1px solid #e5e9f0;border-radius:9px;margin-bottom:12px;background:#fff;">
                        <div style="display:flex;align-items:center;gap:10px;padding:10px 12px;background:#f7f9fc;border-bottom:1px solid #eef1f6;border-radius:9px 9px 0 0;">
                            <i :class="reg[block.type] ? reg[block.type].icon : 'fas fa-cube'" style="color:#3c8dbc;"></i>
                            <strong x-text="reg[block.type] ? reg[block.type].label : block.type"></strong>
                            <span style="margin-left:auto;"></span>
                            <button type="button" class="btn btn-xs btn-default" @click="move(i,-1)" :disabled="i===0" title="Move up"><i class="fa fa-arrow-up"></i></button>
                            <button type="button" class="btn btn-xs btn-default" @click="move(i,1)" :disabled="i===blocks.length-1" title="Move down"><i class="fa fa-arrow-down"></i></button>
                            <button type="button" class="btn btn-xs btn-default" @click="toggle(block)" title="Collapse"><i class="fa" :class="block._open===false?'fa-chevron-down':'fa-chevron-up'"></i></button>
                            <button type="button" class="btn btn-xs btn-default" @click="duplicate(i)" title="Duplicate"><i class="fa fa-copy"></i></button>
                            <button type="button" class="btn btn-xs btn-danger" @click="remove(i)" title="Remove"><i class="fa fa-trash"></i></button>
                        </div>
                        <div style="padding:14px;" x-show="block._open !== false">
                            <template x-for="field in (reg[block.type] ? reg[block.type].fields : [])" :key="field.key">
                                <div class="form-group" style="margin-bottom:12px;">
                                    <label x-text="field.label" style="font-size:13px;"></label>

                                    {{-- simple fields --}}
                                    <template x-if="['text','url'].includes(field.type)">
                                        <input type="text" class="form-control input-sm" x-model="block.data[field.key]">
                                    </template>
                                    <template x-if="field.type==='textarea'">
                                        <textarea class="form-control input-sm" rows="2" x-model="block.data[field.key]"></textarea>
                                    </template>
                                    <template x-if="field.type==='richtext'">
                                        <textarea class="form-control input-sm" rows="5" style="font-family:monospace;" x-model="block.data[field.key]"></textarea>
                                    </template>
                                    <template x-if="field.type==='image'">
                                        <div style="display:flex;gap:8px;align-items:center;">
                                            <input type="text" class="form-control input-sm" placeholder="Image URL" x-model="block.data[field.key]">
                                            <template x-if="block.data[field.key]"><img :src="block.data[field.key]" style="height:34px;border-radius:5px;"></template>
                                            <label class="btn btn-xs btn-default" style="margin:0;white-space:nowrap;">
                                                <i class="fa fa-upload"></i>
                                                <input type="file" accept="image/*" style="display:none" @change="upload($event, v => block.data[field.key] = v)">
                                            </label>
                                        </div>
                                    </template>

                                    {{-- repeater --}}
                                    <template x-if="field.type==='repeater'">
                                        <div style="border:1px dashed #d6deea;border-radius:8px;padding:10px;">
                                            <template x-for="(item, ri) in repeaterArr(block, field.key)" :key="ri">
                                                <div style="border:1px solid #eef1f6;border-radius:7px;padding:10px;margin-bottom:8px;background:#fbfcfe;">
                                                    <div style="text-align:right;"><button type="button" class="btn btn-xs btn-danger" @click="repeaterRemove(block, field.key, ri)"><i class="fa fa-times"></i></button></div>
                                                    <template x-for="sub in field.item" :key="sub.key">
                                                        <div class="form-group" style="margin-bottom:8px;">
                                                            <label x-text="sub.label" style="font-size:12px;"></label>
                                                            <template x-if="sub.type==='image'">
                                                                <div style="display:flex;gap:8px;align-items:center;">
                                                                    <input type="text" class="form-control input-sm" placeholder="Image URL" x-model="item[sub.key]">
                                                                    <template x-if="item[sub.key]"><img :src="item[sub.key]" style="height:30px;border-radius:5px;"></template>
                                                                    <label class="btn btn-xs btn-default" style="margin:0;"><i class="fa fa-upload"></i>
                                                                        <input type="file" accept="image/*" style="display:none" @change="upload($event, v => item[sub.key] = v)"></label>
                                                                </div>
                                                            </template>
                                                            <template x-if="sub.type==='textarea'">
                                                                <textarea class="form-control input-sm" rows="2" x-model="item[sub.key]"></textarea>
                                                            </template>
                                                            <template x-if="!['image','textarea'].includes(sub.type)">
                                                                <input type="text" class="form-control input-sm" x-model="item[sub.key]">
                                                            </template>
                                                        </div>
                                                    </template>
                                                </div>
                                            </template>
                                            <button type="button" class="btn btn-xs btn-default" @click="repeaterAdd(block, field)"><i class="fa fa-plus"></i> Add item</button>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <div style="text-align:center;margin-top:14px;">
                    <button type="button" class="btn btn-success" @click="save()" :disabled="saving">
                        <i class="fa" :class="saving ? 'fa-spinner fa-spin' : 'fa-save'"></i> Save sections</button>
                </div>
            @endcomponent
        </div>

        {{-- ============ Right column: add blocks + page meta ============ --}}
        <div class="col-md-4">
            @component('components.widget', ['title' => 'Add a section'])
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                    @foreach($registry as $type => $b)
                        <button type="button" class="btn btn-default btn-sm text-left" @click="add('{{ $type }}')" style="white-space:normal;">
                            <i class="{{ $b['icon'] }}"></i> {{ $b['label'] }}
                        </button>
                    @endforeach
                </div>
            @endcomponent

            @component('components.widget', ['title' => 'Page settings', 'class' => 'box-primary'])
                <form method="POST" action="{{ route('cs.pages.update', $page->id) }}">@csrf
                    <div class="form-group"><label>Title</label>
                        <input type="text" name="title" class="form-control" value="{{ $page->title }}" required></div>
                    <div class="form-group"><label>URL slug</label>
                        <div class="input-group"><span class="input-group-addon">/</span>
                            <input type="text" name="slug" class="form-control" value="{{ $page->slug }}" {{ $page->is_home ? 'readonly' : '' }}></div>
                        @if($page->is_home)<small class="text-muted">Home page is served at <code>/</code>.</small>@endif
                    </div>
                    <div class="form-group"><label>Status</label>
                        <select name="status" class="form-control">
                            <option value="draft" {{ $page->status==='draft'?'selected':'' }}>Draft</option>
                            <option value="published" {{ $page->status==='published'?'selected':'' }}>Published</option>
                        </select></div>
                    <div class="form-group"><label><input type="checkbox" name="show_in_nav" value="1" {{ $page->show_in_nav ? 'checked' : '' }}> Show in navigation menu</label></div>
                    <hr>
                    <div class="form-group"><label>SEO title</label>
                        <input type="text" name="seo_title" class="form-control" value="{{ $page->seo_title }}"></div>
                    <div class="form-group"><label>Meta description</label>
                        <textarea name="seo_description" class="form-control" rows="2">{{ $page->seo_description }}</textarea></div>
                    <button class="btn btn-primary btn-block"><i class="fa fa-save"></i> Save page settings</button>
                </form>
                <a href="{{ route('cs.pages') }}" class="btn btn-link btn-block">← Back to pages</a>
            @endcomponent
        </div>
    </div>
</section>

<script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
<script>
function vsBuilder(){
    return {
        reg: @json($registry),
        defaults: @json(collect($registry)->mapWithKeys(fn($b,$k)=>[$k=>$b['defaults'] ?? []])),
        blocks: @json($page->orderedBlocks()),
        saving: false,
        saveUrl: "{{ route('cs.pages.blocks', $page->id) }}",
        uploadUrl: "{{ route('cs.media.upload') }}",
        token: "{{ csrf_token() }}",
        init(){ this.blocks.forEach(b => { if(b._open===undefined) b._open = true; if(!b.data) b.data={}; }); },
        uid(){ return Math.random().toString(36).slice(2,10); },
        add(type){
            this.blocks.push({ id:this.uid(), type:type, data:JSON.parse(JSON.stringify(this.defaults[type]||{})), _open:true });
        },
        remove(i){ if(confirm('Remove this section?')) this.blocks.splice(i,1); },
        duplicate(i){ var c=JSON.parse(JSON.stringify(this.blocks[i])); c.id=this.uid(); this.blocks.splice(i+1,0,c); },
        move(i,d){ var j=i+d; if(j<0||j>=this.blocks.length) return; var t=this.blocks[i]; this.blocks[i]=this.blocks[j]; this.blocks[j]=t; },
        toggle(b){ b._open = b._open===false; },
        repeaterArr(block,key){ if(!Array.isArray(block.data[key])) block.data[key]=[]; return block.data[key]; },
        repeaterAdd(block,field){ var o={}; (field.item||[]).forEach(s=>o[s.key]=''); this.repeaterArr(block,field.key).push(o); },
        repeaterRemove(block,key,ri){ block.data[key].splice(ri,1); },
        upload(e, setter){
            var f=e.target.files[0]; if(!f) return;
            var fd=new FormData(); fd.append('files[]', f);
            fetch(this.uploadUrl,{method:'POST',headers:{'X-CSRF-TOKEN':this.token,'Accept':'application/json'},body:fd})
                .then(r=>r.json()).then(d=>{ if(d.success && d.media[0]) setter(d.media[0].url); })
                .catch(()=>alert('Upload failed'));
            e.target.value='';
        },
        save(){
            this.saving=true;
            var payload=this.blocks.map(b=>({id:b.id,type:b.type,data:b.data}));
            fetch(this.saveUrl,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-TOKEN':this.token,'Accept':'application/json'},
                body:JSON.stringify({blocks:payload})})
                .then(r=>r.json()).then(()=>{ this.saving=false; this.flash('Sections saved'); })
                .catch(()=>{ this.saving=false; alert('Save failed'); });
        },
        flash(msg){
            var d=document.createElement('div');
            d.className='alert alert-success'; d.style.cssText='position:fixed;top:60px;right:20px;z-index:9999;box-shadow:0 6px 20px rgba(0,0,0,.15)';
            d.innerHTML='<i class="fa fa-check-circle"></i> '+msg;
            document.body.appendChild(d); setTimeout(()=>d.remove(),2200);
        }
    };
}
</script>
@endsection
