@extends('layouts.app')

@section('title', 'Input Data - ' . ($ref['nama_instansi'] ?? ''))
@section('body-class', 'page-data-entry')

@push('styles')
<style>
    .page-data-entry { background: #f3f5f9; }
    /* padding-top 94px = tinggi nav fixed (70px) + jarak, agar judul tak ketutup header */
    .de-wrap { width: 100%; padding: 94px clamp(16px, 4vw, 48px) 120px; box-sizing: border-box; }
    .de-head { display:flex; align-items:flex-end; justify-content:space-between; gap:16px; flex-wrap:wrap; margin-bottom:18px; }
    .de-title { margin:0; font-size:1.6rem; font-weight:800; color:#16233b; letter-spacing:-0.02em; }
    .de-sub { margin:4px 0 0; color:#6b7688; font-size:.95rem; }
    .de-tools { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
    .de-select { padding:9px 12px; border:1px solid #d9dee7; border-radius:10px; background:#fff; font-size:.95rem; color:#16233b; }
    .de-link { display:inline-flex; align-items:center; gap:6px; padding:9px 14px; border-radius:10px; text-decoration:none;
               background:#fff; border:1px solid #d9dee7; color:#2b4a86; font-weight:600; font-size:.9rem; transition:.15s; }
    .de-link:hover { background:#eef3fc; border-color:#b9ccef; }

    .de-alert { padding:12px 16px; border-radius:12px; margin-bottom:14px; font-size:.95rem; font-weight:500; }
    .de-alert.ok { background:#e7f6ec; color:#1c7a3f; border:1px solid #b7e3c4; }
    .de-alert.warn { background:#fff6e5; color:#8a5a00; border:1px solid #ffe0a3; }
    .de-alert.err { background:#fdecec; color:#a12626; border:1px solid #f5c2c2; }

    .de-card { background:#fff; border:1px solid #e6e9f0; border-radius:16px; box-shadow:0 6px 24px rgba(20,35,60,.06); overflow:hidden; }
    .de-scroll { overflow:auto; max-height:calc(100vh - 300px); }
    table.de-grid { width:100%; border-collapse:separate; border-spacing:0; font-size:.95rem; }
    .de-grid thead th { position:sticky; top:0; z-index:3; background:#16233b; color:#fff; font-weight:600;
                        text-align:right; padding:14px 16px; white-space:nowrap; }
    .de-grid thead th:first-child { text-align:left; left:0; z-index:4; border-top-left-radius:0; }
    .de-grid tbody td { padding:0; border-bottom:1px solid #eef1f6; }
    .de-grid tbody td:first-child { position:sticky; left:0; z-index:2; background:#fff; font-weight:600; color:#3a465c;
                                    padding:0 16px; white-space:nowrap; border-right:1px solid #eef1f6; }
    .de-grid tbody tr:nth-child(even) td:first-child { background:#fafbfd; }
    .de-grid tbody tr:nth-child(even) td { background:#fafbfd; }
    .de-grid tbody tr:hover td { background:#f0f5ff; }
    .de-grid tbody tr:hover td:first-child { background:#f0f5ff; }
    .de-cell { width:100%; box-sizing:border-box; border:1.5px solid transparent; background:transparent; text-align:right;
               padding:13px 16px; font-size:.95rem; color:#16233b; border-radius:8px; transition:.12s; -moz-appearance:textfield; }
    .de-cell::-webkit-outer-spin-button, .de-cell::-webkit-inner-spin-button { -webkit-appearance:none; margin:0; }
    .de-cell:hover { background:#fff; border-color:#e1e6ef; }
    .de-cell:focus { outline:none; background:#fff; border-color:#f0a020; box-shadow:0 0 0 3px rgba(240,160,32,.15); }
    .de-cell.changed { background:#fff8e8; border-color:#f0c14b; font-weight:600; }

    .de-savebar { position:fixed; left:0; right:0; bottom:0; z-index:20; background:rgba(255,255,255,.92);
                  backdrop-filter:saturate(180%) blur(8px); border-top:1px solid #e6e9f0; padding:14px clamp(16px,4vw,48px);
                  display:flex; align-items:center; justify-content:flex-end; gap:16px; }
    .de-count { color:#6b7688; font-size:.92rem; }
    .de-count.dirty { color:#8a5a00; font-weight:600; }
    .de-btn { border:none; border-radius:12px; padding:12px 26px; font-size:1rem; font-weight:700; cursor:pointer;
              background:#16233b; color:#fff; transition:.15s; box-shadow:0 4px 14px rgba(22,35,59,.25); }
    .de-btn:hover:not(:disabled) { background:#22345a; transform:translateY(-1px); }
    .de-btn:disabled { background:#c7cdd8; color:#eef0f4; cursor:not-allowed; box-shadow:none; }
    .de-empty { padding:40px; text-align:center; color:#6b7688; }
</style>
@endpush

@section('content')
<div class="de-wrap">
    <div class="de-head">
        <div>
            <h1 class="de-title">{{ $ref['nama_instansi'] }}</h1>
            <p class="de-sub">Input data · Tahun {{ $tahun }}</p>
        </div>
        <div class="de-tools">
            <form method="GET" action="{{ route('data.edit', ['slug' => $slug]) }}" style="margin:0;">
                <select class="de-select" name="tahun" onchange="this.form.submit()" aria-label="Pilih tahun">
                    @for($y = (int)date('Y') + 1; $y >= 2023; $y--)
                        <option value="{{ $y }}" @selected($y === $tahun)>Tahun {{ $y }}</option>
                    @endfor
                </select>
            </form>
            <a href="{{ route('data.fields', ['slug' => $slug]) }}" class="de-link">⚙️ Atur Kolom</a>
        </div>
    </div>

    @if(session('success'))
        <div class="de-alert ok">✅ {{ session('success') }}</div>
    @endif
    @if(session('warning'))
        <div class="de-alert warn">⚠️ {{ session('warning') }}</div>
    @endif
    @if(session('error'))
        <div class="de-alert err">⛔ {{ session('error') }}</div>
    @endif

    @if(empty($fields))
        <div class="de-card"><div class="de-empty">
            Belum ada kolom yang diatur untuk instansi ini.
            <a href="{{ route('data.fields', ['slug' => $slug]) }}">Atur kolom dulu &raquo;</a>
        </div></div>
    @else
    <form id="de-form" action="{{ route('data.save', ['slug' => $slug]) }}" method="POST">
        @csrf
        <input type="hidden" name="tahun" value="{{ $tahun }}">
        <div class="de-card">
            <div class="de-scroll">
                <table class="de-grid">
                    <thead>
                        <tr>
                            <th>Bulan</th>
                            @foreach($fields as $f)
                                <th>{{ $f['label'] }}</th>
                            @endforeach
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($bulanList as $num => $namaBulan)
                            <tr>
                                <td>{{ $namaBulan }}</td>
                                @foreach($fields as $f)
                                    @php $val = $data[$num][$f['field_key']] ?? null; @endphp
                                    <td>
                                        <input class="de-cell" type="number" step="any" inputmode="decimal"
                                               data-cell
                                               name="data[{{ $num }}][{{ $f['field_key'] }}]"
                                               value="{{ $val }}" placeholder="—">
                                    </td>
                                @endforeach
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <div class="de-savebar">
            <span id="de-count" class="de-count">Belum ada perubahan</span>
            <button id="de-save" type="submit" class="de-btn" disabled>💾 Simpan Perubahan</button>
        </div>
    </form>

    <script>
        (function () {
            var form = document.getElementById('de-form');
            var btn = document.getElementById('de-save');
            var counter = document.getElementById('de-count');
            var cells = Array.prototype.slice.call(form.querySelectorAll('input[data-cell]'));
            var initial = {};
            cells.forEach(function (c) { initial[c.name] = c.value; });

            function refresh() {
                var changed = 0;
                cells.forEach(function (c) {
                    var isDiff = c.value !== initial[c.name];
                    c.classList.toggle('changed', isDiff);
                    if (isDiff) changed++;
                });
                btn.disabled = changed === 0;
                counter.textContent = changed === 0 ? 'Belum ada perubahan'
                    : (changed + ' perubahan belum disimpan');
                counter.classList.toggle('dirty', changed > 0);
                window.__deDirty = changed > 0;
            }

            form.addEventListener('input', function (e) {
                if (e.target && e.target.matches('input[data-cell]')) refresh();
            });
            form.addEventListener('submit', function () { window.__deDirty = false; });
            window.addEventListener('beforeunload', function (e) {
                if (window.__deDirty) { e.preventDefault(); e.returnValue = ''; }
            });
        })();
    </script>
    @endif
</div>
@endsection
