{{--
    Kaynak maliyet başlıkları repeater'ı (create + edit ortak).

    Beklenen değişkenler:
      $costTitles — daha önce kullanılmış başlıklar (autocomplete önerisi)
      $resource   — yalnızca edit'te; yoksa boş satırla başlar

    Gönderim: cost_items[i][title], cost_items[i][amount]
--}}
@php
    $existing = old('cost_items', isset($resource)
        ? $resource->costItems->map(fn ($i) => ['title' => $i->title, 'amount' => $i->amount])->all()
        : []);
@endphp

<div class="ci-wrap" id="cost-items">
    <datalist id="cost-title-options">
        @foreach($costTitles ?? [] as $t)
            <option value="{{ $t }}"></option>
        @endforeach
    </datalist>

    <div class="ci-head">
        <span class="ci-h-title">Başlık</span>
        <span class="ci-h-amount">Tutar</span>
        <span class="ci-h-spacer"></span>
    </div>

    <div id="ci-rows">
        @forelse($existing as $i => $item)
            <div class="ci-row">
                <div class="ci-c-title">
                    <input type="text" name="cost_items[{{ $i }}][title]" class="f-input ci-title"
                           list="cost-title-options" placeholder="ör. Sigorta Maliyeti"
                           value="{{ $item['title'] ?? '' }}" maxlength="150">
                    @error("cost_items.$i.title")<div class="f-error">{{ $message }}</div>@enderror
                </div>
                <div class="ci-c-amount">
                    <div class="f-input-group">
                        <div class="prefix">₺</div>
                        <input type="number" step="0.01" min="0" name="cost_items[{{ $i }}][amount]"
                               class="f-input ci-amount" placeholder="0.00" value="{{ $item['amount'] ?? '' }}">
                    </div>
                    @error("cost_items.$i.amount")<div class="f-error">{{ $message }}</div>@enderror
                </div>
                <button type="button" class="ci-del" onclick="ciRemoveRow(this)" title="Satırı sil">
                    <i class="fas fa-xmark"></i>
                </button>
            </div>
        @empty
            <div class="ci-row">
                <div class="ci-c-title">
                    <input type="text" name="cost_items[0][title]" class="f-input ci-title"
                           list="cost-title-options" placeholder="ör. Sigorta Maliyeti" maxlength="150">
                </div>
                <div class="ci-c-amount">
                    <div class="f-input-group">
                        <div class="prefix">₺</div>
                        <input type="number" step="0.01" min="0" name="cost_items[0][amount]"
                               class="f-input ci-amount" placeholder="0.00">
                    </div>
                </div>
                <button type="button" class="ci-del" onclick="ciRemoveRow(this)" title="Satırı sil">
                    <i class="fas fa-xmark"></i>
                </button>
            </div>
        @endforelse
    </div>

    <div class="ci-foot">
        <button type="button" class="ci-add" onclick="ciAddRow()">
            <i class="fas fa-plus me-1"></i> Maliyet Ekle
        </button>
        <div class="ci-total">Toplam: <strong id="ci-total-val">₺0,00</strong></div>
    </div>

    <div class="ci-hint">
        <i class="fas fa-circle-info me-1"></i>
        Bu başlıklar operasyonda kaynak atarken varsayılan olarak gelir; atama sırasında tutarlar düzenlenebilir.
    </div>
</div>

@once
@push('styles')
<style>
    .ci-head { display:grid; grid-template-columns:1fr 200px 38px; gap:10px; padding:0 2px 6px;
               font-size:11px; font-weight:700; letter-spacing:.04em; text-transform:uppercase; color:#94a3b8; }
    .ci-row  { display:grid; grid-template-columns:1fr 200px 38px; gap:10px; align-items:start; margin-bottom:10px; }
    .ci-del  { width:38px; height:42px; border:1px solid #fecaca; background:#fef2f2; color:#dc2626;
               border-radius:10px; cursor:pointer; transition:.15s; }
    .ci-del:hover { background:#dc2626; color:#fff; border-color:#dc2626; }
    .ci-foot { display:flex; align-items:center; justify-content:space-between; margin-top:4px; }
    .ci-add  { border:1px dashed #cbd5e1; background:#f8fafc; color:#475569; font-weight:600; font-size:13px;
               padding:9px 16px; border-radius:10px; cursor:pointer; transition:.15s; }
    .ci-add:hover { border-color:#f59e0b; color:#b45309; background:#fffbeb; }
    .ci-total { font-size:13px; color:#64748b; }
    .ci-total strong { color:#0f172a; font-size:15px; }
    .ci-hint { margin-top:10px; font-size:12px; color:#94a3b8; }
    @media (max-width: 640px) {
        .ci-head { display:none; }
        .ci-row  { grid-template-columns:1fr 38px; grid-template-areas:"title del" "amount amount"; }
        .ci-c-title { grid-area:title; } .ci-c-amount { grid-area:amount; } .ci-del { grid-area:del; }
    }
</style>
@endpush

@push('scripts')
<script>
// Maliyet başlıkları repeater'ı. Satır adları (cost_items[i][...]) silme sonrası
// yeniden indekslenir; PHP boşluklu indeksleri de kabul eder ama sıralı tutmak
// doğrulama hatalarının doğru satıra düşmesini sağlar.
function ciReindex() {
    document.querySelectorAll('#ci-rows .ci-row').forEach((row, i) => {
        const t = row.querySelector('.ci-title');
        const a = row.querySelector('.ci-amount');
        if (t) t.name = `cost_items[${i}][title]`;
        if (a) a.name = `cost_items[${i}][amount]`;
    });
    ciUpdateTotal();
}

function ciUpdateTotal() {
    let sum = 0;
    document.querySelectorAll('#ci-rows .ci-amount').forEach(el => {
        const v = parseFloat(el.value);
        if (!isNaN(v)) sum += v;
    });
    const out = document.getElementById('ci-total-val');
    if (out) out.textContent = '₺' + sum.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function ciAddRow() {
    const rows = document.getElementById('ci-rows');
    const i = rows.querySelectorAll('.ci-row').length;
    const row = document.createElement('div');
    row.className = 'ci-row';
    row.innerHTML = `
        <div class="ci-c-title">
            <input type="text" name="cost_items[${i}][title]" class="f-input ci-title"
                   list="cost-title-options" placeholder="ör. Sigorta Maliyeti" maxlength="150">
        </div>
        <div class="ci-c-amount">
            <div class="f-input-group">
                <div class="prefix">₺</div>
                <input type="number" step="0.01" min="0" name="cost_items[${i}][amount]"
                       class="f-input ci-amount" placeholder="0.00">
            </div>
        </div>
        <button type="button" class="ci-del" onclick="ciRemoveRow(this)" title="Satırı sil">
            <i class="fas fa-xmark"></i>
        </button>`;
    rows.appendChild(row);
    row.querySelector('.ci-title').focus();
    ciUpdateTotal();
}

function ciRemoveRow(btn) {
    const rows = document.getElementById('ci-rows');
    btn.closest('.ci-row').remove();
    // Son satır da silinirse form boş kalmasın; temiz bir satır bırak.
    if (!rows.querySelectorAll('.ci-row').length) {
        ciAddRow();
        return;
    }
    ciReindex();
}

document.addEventListener('input', e => {
    if (e.target.classList.contains('ci-amount')) ciUpdateTotal();
});
document.addEventListener('DOMContentLoaded', ciUpdateTotal);
</script>
@endpush
@endonce
