<x-app-layout title="Karyawan">

@push('styles')
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root {
    --p:#4f46e5;--pd:#3730a3;--pl:#eef2ff;--pm:rgba(79,70,229,.12);
    --ok:#059669;--okl:#ecfdf5;--err:#dc2626;--errl:#fef2f2;
    --warn:#d97706;--warnl:#fffbeb;--txt:#0f172a;--mut:#64748b;--mut2:#94a3b8;
    --bdr:#e2e8f0;--bg:#f0f4ff;--bg2:#f8fafc;--wh:#ffffff;
    --sh:0 1px 3px rgba(0,0,0,.06),0 4px 16px rgba(0,0,0,.05);
    --sh2:0 8px 32px rgba(0,0,0,.1),0 2px 8px rgba(0,0,0,.06);
    --r:14px;--rs:9px;--rl:20px;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--bg);color:var(--txt);}
.pg{max-width:1100px;margin:0 auto;padding:28px 28px 52px;}
.pg-hd{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px;margin-bottom:26px;}
.pg-hd-l{display:flex;align-items:center;gap:14px;}
.pg-ico{width:50px;height:50px;border-radius:var(--r);background:linear-gradient(135deg,var(--p),#818cf8);display:flex;align-items:center;justify-content:center;box-shadow:0 6px 18px var(--pm);flex-shrink:0;}
.pg-ico svg{width:24px;height:24px;stroke:white;}
.pg-title{font-size:1.45rem;font-weight:900;color:var(--txt);letter-spacing:-.03em;margin-bottom:2px;}
.pg-sub{font-size:.85rem;font-weight:500;color:var(--mut);}
.alert{display:flex;align-items:center;gap:10px;padding:13px 17px;border-radius:var(--r);margin-bottom:22px;font-size:.875rem;font-weight:600;animation:slideDown .3s ease;}
@keyframes slideDown{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.alert-ok{background:var(--okl);color:var(--ok);border:1px solid #a7f3d0;}
.alert-ok svg,.alert-err svg{width:15px;height:15px;flex-shrink:0;}
.alert-ok svg{stroke:var(--ok);}
.alert-err{background:var(--errl);color:var(--err);border:1px solid #fecaca;}
.alert-err svg{stroke:var(--err);}
.kpi-row{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:24px;}
.kpi{background:var(--wh);border:1px solid var(--bdr);border-radius:var(--r);padding:18px 20px;box-shadow:var(--sh);position:relative;overflow:hidden;transition:transform .2s,box-shadow .2s;}
.kpi:hover{transform:translateY(-2px);box-shadow:var(--sh2);}
.kpi::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:var(--r) var(--r) 0 0;}
.kpi.kp::before{background:linear-gradient(90deg,var(--p),#818cf8);}
.kpi.ks::before{background:linear-gradient(90deg,var(--ok),#34d399);}
.kpi.kw::before{background:linear-gradient(90deg,var(--warn),#fbbf24);}
.kpi-lbl{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--mut2);margin-bottom:8px;}
.kpi-val{font-size:2rem;font-weight:900;color:var(--txt);letter-spacing:-.04em;line-height:1;}
.kpi-sub{font-size:.78rem;color:var(--mut);font-weight:500;margin-top:3px;}
.card{background:var(--wh);border:1px solid var(--bdr);border-radius:var(--rl);box-shadow:var(--sh);overflow:hidden;}
.card-hd{padding:18px 24px;border-bottom:1px solid var(--bdr);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;}
.card-hd-l{display:flex;align-items:center;gap:10px;}
.card-title{font-size:.9rem;font-weight:800;color:var(--txt);}
.cnt-badge{background:var(--pl);color:var(--p);font-size:.72rem;font-weight:700;padding:2px 9px;border-radius:100px;}
.card-hd-r{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}
.search{position:relative;display:flex;align-items:center;}
.search svg{position:absolute;left:10px;width:15px;height:15px;stroke:var(--mut2);pointer-events:none;}
.search input{padding:8px 12px 8px 32px;border:1.5px solid var(--bdr);border-radius:var(--rs);font-size:.83rem;font-family:inherit;color:var(--txt);background:var(--bg2);outline:none;width:210px;transition:all .2s;}
.search input:focus{border-color:var(--p);background:var(--wh);box-shadow:0 0 0 3px var(--pm);width:250px;}
.btn-primary{display:inline-flex;align-items:center;gap:7px;padding:9px 18px;border-radius:var(--rs);background:var(--p);color:white;border:none;font-size:.875rem;font-weight:700;font-family:inherit;cursor:pointer;text-decoration:none;white-space:nowrap;box-shadow:0 2px 10px var(--pm);transition:all .2s;}
.btn-primary svg{width:15px;height:15px;stroke:white;}
.btn-primary:hover{background:var(--pd);transform:translateY(-1px);box-shadow:0 4px 16px var(--pm);}
.btn-ghost{display:inline-flex;align-items:center;gap:6px;padding:9px 16px;border-radius:var(--rs);background:transparent;color:var(--mut);border:1.5px solid var(--bdr);font-size:.875rem;font-weight:600;font-family:inherit;cursor:pointer;transition:all .2s;}
.btn-ghost:hover{background:var(--bg2);color:var(--txt);border-color:var(--mut2);}
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;}
.tbl{width:100%;border-collapse:collapse;min-width:700px;}
.tbl thead tr{background:#fafbff;}
.tbl thead th{padding:11px 18px;text-align:left;font-size:.7rem;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--mut2);border-bottom:1px solid var(--bdr);white-space:nowrap;}
.tbl tbody tr{border-bottom:1px solid #f1f5f9;transition:background .12s;}
.tbl tbody tr:last-child{border-bottom:none;}
.tbl tbody tr:hover{background:#fafbff;}
.tbl td{padding:13px 18px;font-size:.875rem;color:var(--txt);vertical-align:middle;}
.av-cell{display:flex;align-items:center;gap:10px;}
.av{width:36px;height:36px;border-radius:10px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:.8rem;font-weight:800;color:white;background:linear-gradient(135deg,var(--p),#818cf8);box-shadow:0 2px 8px var(--pm);}
.av-name{font-size:.875rem;font-weight:700;color:var(--txt);}
.av-nip{font-size:.72rem;color:var(--mut2);font-weight:500;margin-top:1px;}
.chip{display:inline-flex;align-items:center;padding:3px 10px;border-radius:100px;font-size:.73rem;font-weight:700;}
.chip-p{background:var(--pl);color:var(--p);border:1px solid #c7d2fe;}
.jam-main{font-size:.82rem;font-weight:700;color:var(--txt);}
.jam-sub{font-size:.72rem;color:var(--mut2);font-weight:500;margin-top:1px;}
.act-cell{display:flex;gap:6px;}
.act-btn{width:32px;height:32px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;border:none;cursor:pointer;transition:all .15s;text-decoration:none;}
.act-btn svg{width:14px;height:14px;}
.act-view{background:#ecfdf5;border:1px solid #a7f3d0;}
.act-view svg{stroke:#059669;}
.act-view:hover{background:#d1fae5;transform:scale(1.08);}
.act-edit{background:var(--pl);border:1px solid #c7d2fe;}
.act-edit svg{stroke:var(--p);}
.act-edit:hover{background:#e0e7ff;transform:scale(1.08);}
.act-del{background:var(--errl);border:1px solid #fecaca;}
.act-del svg{stroke:var(--err);}
.act-del:hover{background:#fee2e2;transform:scale(1.08);}
.empty{padding:56px 24px;text-align:center;}
.empty svg{stroke:#dde3ef;margin-bottom:14px;}
.empty p{font-size:.9rem;color:var(--mut2);font-weight:600;margin-bottom:16px;}
.modal{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;z-index:9000;padding:16px;}
.modal-bg{position:absolute;inset:0;background:rgba(15,23,42,.5);backdrop-filter:blur(8px);}
.modal-box{position:relative;background:var(--wh);border-radius:var(--rl);width:100%;max-width:560px;max-height:92vh;overflow-y:auto;box-shadow:0 24px 64px rgba(0,0,0,.18),0 8px 24px rgba(0,0,0,.1);animation:mIn .28s cubic-bezier(.34,1.4,.64,1);}
@keyframes mIn{from{opacity:0;transform:scale(.92) translateY(18px)}to{opacity:1;transform:scale(1) translateY(0)}}
.modal-hd{padding:22px 24px 18px;border-bottom:1px solid var(--bdr);display:flex;align-items:center;gap:13px;position:sticky;top:0;background:var(--wh);z-index:1;}
.modal-hd-ico{width:42px;height:42px;border-radius:12px;background:var(--pl);display:flex;align-items:center;justify-content:center;flex-shrink:0;}
.modal-hd-ico svg{width:20px;height:20px;stroke:var(--p);}
.modal-hd-title{font-size:1rem;font-weight:800;color:var(--txt);margin-bottom:2px;}
.modal-hd-sub{font-size:.78rem;color:var(--mut);font-weight:500;}
.modal-x{margin-left:auto;background:none;border:none;cursor:pointer;width:30px;height:30px;border-radius:7px;display:flex;align-items:center;justify-content:center;color:var(--mut2);font-size:20px;transition:all .15s;}
.modal-x:hover{background:var(--bg2);color:var(--txt);}
.modal-body{padding:22px 24px;}
.sec-lbl{font-size:.68rem;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--mut2);margin-bottom:12px;display:flex;align-items:center;gap:8px;}
.sec-lbl::after{content:'';flex:1;height:1px;background:var(--bdr);}
.fdiv{height:1px;background:var(--bdr);margin:18px 0;}
.frow{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.fg{display:flex;flex-direction:column;margin-bottom:14px;}
.fg:last-child{margin-bottom:0;}
.fg label{font-size:.8rem;font-weight:700;color:var(--txt);margin-bottom:6px;display:flex;align-items:center;gap:4px;}
.fg label .req{color:var(--err);font-size:.72rem;}
.fg input,.fg select,.fg textarea{padding:9px 13px;border:1.5px solid var(--bdr);border-radius:var(--rs);font-size:.875rem;font-family:inherit;color:var(--txt);background:var(--wh);outline:none;transition:all .2s;-webkit-appearance:none;}
.fg input:focus,.fg select:focus,.fg textarea:focus{border-color:var(--p);box-shadow:0 0 0 3px var(--pm);}
.fg input::placeholder,.fg textarea::placeholder{color:var(--mut2);}
.fg textarea{resize:vertical;min-height:72px;}
.pw-wrap{position:relative;}
.pw-wrap input{padding-right:40px;width:100%;}
.pw-toggle{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--mut2);padding:4px;transition:color .15s;}
.pw-toggle:hover{color:var(--txt);}
.pw-toggle svg{width:15px;height:15px;stroke:currentColor;display:block;}
.ferr{color:var(--err);font-size:.75rem;font-weight:600;margin-top:4px;display:flex;align-items:center;gap:4px;}
.ferr:not(:empty)::before{content:'⚠';}
.modal-ft{padding:16px 24px;border-top:1px solid var(--bdr);display:flex;justify-content:flex-end;gap:10px;background:var(--bg2);border-radius:0 0 var(--rl) var(--rl);}
.del-box{position:relative;background:var(--wh);border-radius:var(--rl);width:100%;max-width:360px;box-shadow:0 24px 64px rgba(0,0,0,.18);animation:mIn .24s cubic-bezier(.34,1.4,.64,1);padding:28px 26px 22px;text-align:center;}
.del-ico{width:54px;height:54px;border-radius:50%;background:var(--errl);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;border:6px solid #fee2e2;}
.del-ico svg{width:24px;height:24px;stroke:var(--err);}
.del-title{font-size:1rem;font-weight:800;color:var(--txt);margin-bottom:6px;}
.del-sub{font-size:.85rem;color:var(--mut);font-weight:500;line-height:1.5;margin-bottom:20px;}
.del-name{font-weight:700;color:var(--err);}
.del-btns{display:flex;gap:10px;justify-content:center;}
.btn-danger{display:inline-flex;align-items:center;gap:6px;padding:9px 20px;border-radius:var(--rs);background:var(--err);color:white;border:none;font-size:.875rem;font-weight:700;font-family:inherit;cursor:pointer;box-shadow:0 2px 10px rgba(220,38,38,.25);transition:all .2s;}
.btn-danger svg{width:14px;height:14px;stroke:white;}
.btn-danger:hover{background:#b91c1c;transform:translateY(-1px);}
.toast{position:fixed;bottom:28px;right:28px;z-index:9999;color:white;padding:12px 20px;border-radius:12px;font-size:.875rem;font-weight:600;display:flex;align-items:center;gap:10px;box-shadow:0 8px 32px rgba(0,0,0,.2);animation:toastIn .3s cubic-bezier(.34,1.4,.64,1);max-width:320px;}
.toast svg{width:16px;height:16px;flex-shrink:0;}
.toast.tok{background:#0f4c35;border-left:3px solid var(--ok);}
.toast.tok svg{stroke:#34d399;}
.toast.terr{background:#4c0f0f;border-left:3px solid var(--err);}
.toast.terr svg{stroke:#f87171;}
@keyframes toastIn{from{opacity:0;transform:translateY(16px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.fu1{animation:fadeUp .4s .00s ease both;}
.fu2{animation:fadeUp .4s .06s ease both;}
.fu3{animation:fadeUp .4s .12s ease both;}
@media(max-width:640px){
    .pg{padding:12px 12px 40px;}
    .kpi-row{grid-template-columns:repeat(2,1fr);gap:10px;}
    .kpi:last-child{grid-column:1/-1;}
    .frow{grid-template-columns:1fr;}
    .card-hd{flex-direction:column;align-items:stretch;gap:10px;padding:14px 16px;}
    .card-hd-r{flex-direction:column;align-items:stretch;width:100%;}
    .search input{width:100%!important;box-sizing:border-box;}
    .btn-primary{width:100%;justify-content:center;}
    .tbl-wrap{overflow:visible;}
    .tbl thead{display:none;}
    .tbl,.tbl tbody,.tbl tr,.tbl td{display:block;width:100%;}
    .tbl tbody tr{border:1px solid var(--bdr);border-radius:var(--r);margin:8px 12px;width:calc(100% - 24px);padding:12px;background:var(--wh);box-shadow:var(--sh);border-bottom:1px solid var(--bdr)!important;}
    .tbl td{padding:4px 0;border:none;font-size:.82rem;display:flex;align-items:center;gap:8px;}
    .tbl td:last-child{justify-content:flex-end;padding-top:8px;margin-top:4px;border-top:1px solid var(--bdr);}
    .modal{padding:0;align-items:flex-end;}
    .modal-box{max-width:100%;border-radius:var(--rl) var(--rl) 0 0;max-height:95vh;}
    .del-box{border-radius:var(--rl) var(--rl) 0 0;max-width:100%;width:100%;}
    .toast{left:12px;right:12px;bottom:16px;max-width:100%;}
}
</style>
@endpush

<div class="pg">

<div class="pg-hd fu1">
    <div class="pg-hd-l">
        <div class="pg-ico">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
        </div>
        <div>
            <h1 class="pg-title">Data Karyawan</h1>
            <p class="pg-sub">Kelola seluruh data karyawan instansi</p>
        </div>
    </div>
</div>

@if(session('success'))
<div class="alert alert-ok fu1">
    <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    {{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="alert alert-err fu1">
    <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
    {{ session('error') }}
</div>
@endif

<div class="kpi-row fu2">
    <div class="kpi kp">
        <div class="kpi-lbl">Total Karyawan</div>
        <div class="kpi-val">{{ $karyawan->count() }}</div>
        <div class="kpi-sub">Terdaftar</div>
    </div>
    <div class="kpi ks">
        <div class="kpi-lbl">Jabatan</div>
        <div class="kpi-val">{{ $jabatan->count() }}</div>
        <div class="kpi-sub">Posisi tersedia</div>
    </div>
    <div class="kpi kw">
        <div class="kpi-lbl">Shift Kerja</div>
        <div class="kpi-val">{{ $jamKerja->count() }}</div>
        <div class="kpi-sub">Jadwal aktif</div>
    </div>
</div>

<div class="card fu3">
    <div class="card-hd">
        <div class="card-hd-l">
            <span class="card-title">Daftar Karyawan</span>
            <span class="cnt-badge" id="cnt-badge">{{ $karyawan->count() }}</span>
        </div>
        <div class="card-hd-r">
            <div class="search">
                <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                <input type="text" id="search-input" placeholder="Cari nama atau NIP…" oninput="filterTable(this.value)">
            </div>
            <button class="btn-primary" onclick="openCreate()" style="padding:8px 14px;font-size:.82rem;">
                <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Tambah
            </button>
        </div>
    </div>
    <div class="tbl-wrap">
        <table class="tbl">
            <thead>
                <tr>
                    <th>Karyawan</th>
                    <th>Email</th>
                    <th>Jabatan</th>
                    <th>Jam Kerja</th>
                    <th>No. HP</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody id="tbl-body">
                @forelse($karyawan as $item)
                <tr id="row-{{ $item->id }}" data-search="{{ strtolower($item->nama . ' ' . $item->nip) }}">
                    <td>
                        <div class="av-cell">
                            <div class="av">{{ strtoupper(substr($item->nama,0,2)) }}</div>
                            <div>
                                <div class="av-name">{{ $item->nama }}</div>
                                <div class="av-nip">{{ $item->nip }}</div>
                            </div>
                        </div>
                    </td>
                    <td style="color:var(--mut);font-size:.82rem;">{{ $item->user->email ?? '-' }}</td>
                    <td>
                        @if($item->jabatan)
                            <span class="chip chip-p">{{ $item->jabatan->nama_jabatan }}</span>
                        @else<span style="color:var(--mut2)">—</span>@endif
                    </td>
                    <td>
                        @if($item->jamKerja)
                            <div class="jam-main">{{ \Carbon\Carbon::parse($item->jamKerja->jam_masuk)->format('H:i') }} – {{ \Carbon\Carbon::parse($item->jamKerja->jam_pulang)->format('H:i') }}</div>
                            <div class="jam-sub">Toleransi {{ $item->jamKerja->toleransi_menit }} menit</div>
                        @else<span style="color:var(--mut2)">—</span>@endif
                    </td>
                    <td style="color:var(--mut);font-size:.82rem;">{{ $item->no_hp ?? '—' }}</td>
                    <td>
                        <div class="act-cell">
                            <a href="{{ route('instansi.karyawan.show', $item->id) }}" class="act-btn act-view" title="Lihat Detail">
                                <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                            </a>
                            <button class="act-btn act-edit" onclick="openEdit({{ $item->id }})" title="Edit">
                                <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                            </button>
                            <button class="act-btn act-del" onclick="openDel({{ $item->id }}, '{{ addslashes($item->nama) }}')" title="Hapus">
                                <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
                            </button>
                        </div>
                    </td>
                </tr>
                @empty
                <tr id="empty-row"><td colspan="6">
                    <div class="empty">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
                        <p>Belum ada data karyawan</p>
                        <button class="btn-primary" onclick="openCreate()">
                            <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            Tambah Karyawan Pertama
                        </button>
                    </div>
                </td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

</div>

{{-- MODAL TAMBAH / EDIT --}}
<div id="modal-form" class="modal" style="display:none;">
    <div class="modal-bg" onclick="closeForm()"></div>
    <div class="modal-box">
        <div class="modal-hd">
            <div class="modal-hd-ico">
                <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg>
            </div>
            <div>
                <div class="modal-hd-title" id="mf-title">Tambah Karyawan</div>
                <div class="modal-hd-sub" id="mf-sub">Isi data karyawan baru dengan lengkap</div>
            </div>
            <button class="modal-x" onclick="closeForm()">×</button>
        </div>
        <div class="modal-body">
            <form id="form-kar" method="POST" action="{{ route('instansi.karyawan.store') }}">
                @csrf
                <input type="hidden" name="_method" id="f-method" value="POST">
                <div class="sec-lbl">Informasi Akun</div>
                <div class="frow">
                    <div class="fg">
                        <label>Email Login <span class="req">*</span></label>
                        <input type="email" name="email" id="f-email" placeholder="email@karyawan.com" required>
                        <span class="ferr" id="err-email"></span>
                    </div>
                    <div class="fg">
                        <label id="pw-lbl">Password <span class="req">*</span></label>
                        <div class="pw-wrap">
                            <input type="password" name="password" id="f-pw" placeholder="Min. 8 karakter">
                            <button type="button" class="pw-toggle" onclick="togglePw()">
                                <svg id="pw-eye" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                            </button>
                        </div>
                        <span class="ferr" id="err-password"></span>
                    </div>
                </div>
                <div class="fdiv"></div>
                <div class="sec-lbl">Data Diri</div>
                <div class="frow">
                    <div class="fg">
                        <label>NIP <span class="req">*</span></label>
                        <input type="text" name="nip" id="f-nip" placeholder="Nomor Induk Pegawai" required>
                        <span class="ferr" id="err-nip"></span>
                    </div>
                    <div class="fg">
                        <label>Nama Lengkap <span class="req">*</span></label>
                        <input type="text" name="nama" id="f-nama" placeholder="Nama lengkap" required>
                        <span class="ferr" id="err-nama"></span>
                    </div>
                </div>
                <div class="frow">
                    <div class="fg">
                        <label>No. HP</label>
                        <input type="text" name="no_hp" id="f-hp" placeholder="08xxxxxxxxxx">
                        <span class="ferr" id="err-no_hp"></span>
                    </div>
                    <div class="fg">
                        <label>Jabatan <span class="req">*</span></label>
                        <select name="jabatan_id" id="f-jab" required>
                            <option value="">— Pilih Jabatan —</option>
                            @foreach($jabatan as $jab)
                            <option value="{{ $jab->id }}">{{ $jab->nama_jabatan }}</option>
                            @endforeach
                        </select>
                        <span class="ferr" id="err-jabatan_id"></span>
                    </div>
                </div>
                <div class="fg">
                    <label>Jam Kerja <span class="req">*</span></label>
                    <select name="jam_kerja_id" id="f-jam" required>
                        <option value="">— Pilih Jam Kerja —</option>
                        @foreach($jamKerja as $jam)
                        <option value="{{ $jam->id }}">
                            {{ \Carbon\Carbon::parse($jam->jam_masuk)->format('H:i') }} – {{ \Carbon\Carbon::parse($jam->jam_pulang)->format('H:i') }}
                            (Toleransi {{ $jam->toleransi_menit }} menit)
                        </option>
                        @endforeach
                    </select>
                    <span class="ferr" id="err-jam_kerja_id"></span>
                </div>
                <div class="fg">
                    <label>Alamat</label>
                    <textarea name="alamat" id="f-alamat" placeholder="Alamat lengkap karyawan…"></textarea>
                    <span class="ferr" id="err-alamat"></span>
                </div>
            </form>
        </div>
        <div class="modal-ft">
            <button type="button" class="btn-ghost" onclick="closeForm()">Batal</button>
            <button type="button" class="btn-primary" id="btn-submit" onclick="submitForm()">
                <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                <span id="btn-lbl">Simpan Karyawan</span>
            </button>
        </div>
    </div>
</div>

{{-- MODAL DELETE --}}
<div id="modal-del" class="modal" style="display:none;">
    <div class="modal-bg" onclick="closeDel()"></div>
    <div class="del-box">
        <div class="del-ico">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>
        </div>
        <div class="del-title">Hapus Karyawan?</div>
        <div class="del-sub">Anda akan menghapus <span class="del-name" id="del-name-lbl"></span>.<br>Semua data absensi terkait ikut terhapus.<br>Tindakan ini <strong>tidak dapat dibatalkan</strong>.</div>
        <div class="del-btns">
            <button class="btn-ghost" onclick="closeDel()">Batal</button>
            <button class="btn-danger" id="btn-del-ok" onclick="doDelete()">
                <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>
                Ya, Hapus
            </button>
        </div>
    </div>
</div>

@push('scripts')
<script>
const CSRF = () => document.querySelector('meta[name="csrf-token"]')?.content;

function filterTable(q) {
    const rows = document.querySelectorAll('#tbl-body tr[data-search]');
    let vis = 0;
    rows.forEach(r => { const show = r.dataset.search.includes(q.toLowerCase()); r.style.display = show ? '' : 'none'; if (show) vis++; });
    document.getElementById('cnt-badge').textContent = vis;
}

function togglePw() {
    const inp = document.getElementById('f-pw');
    const isText = inp.type === 'text';
    inp.type = isText ? 'password' : 'text';
    document.getElementById('pw-eye').innerHTML = isText
        ? '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>'
        : '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/>';
}

function clearErrors() { document.querySelectorAll('.ferr').forEach(el => el.textContent = ''); }

function openCreate() {
    document.getElementById('mf-title').textContent = 'Tambah Karyawan';
    document.getElementById('mf-sub').textContent = 'Isi data karyawan baru dengan lengkap';
    document.getElementById('f-method').value = 'POST';
    document.getElementById('form-kar').action = '{{ route("instansi.karyawan.store") }}';
    document.getElementById('btn-lbl').textContent = 'Simpan Karyawan';
    document.getElementById('pw-lbl').innerHTML = 'Password <span class="req">*</span>';
    document.getElementById('f-pw').required = true;
    document.getElementById('form-kar').reset();
    clearErrors();
    document.getElementById('modal-form').style.display = 'flex';
    setTimeout(() => document.getElementById('f-email').focus(), 100);
}

function openEdit(id) {
    fetch(`/instansi/karyawan/${id}/edit-data`, { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' } })
    .then(r => r.json())
    .then(d => {
        if (!d.success) { showToast('terr', 'Gagal memuat data'); return; }
        const kar = d.karyawan;
        document.getElementById('mf-title').textContent = 'Edit Karyawan';
        document.getElementById('mf-sub').textContent = 'Perbarui data karyawan';
        document.getElementById('f-method').value = 'PUT';
        document.getElementById('form-kar').action = `/instansi/karyawan/${id}`;
        document.getElementById('btn-lbl').textContent = 'Update Karyawan';
        document.getElementById('pw-lbl').innerHTML = 'Password Baru <span style="font-size:.72rem;color:var(--mut2)">(kosongkan jika tidak diubah)</span>';
        document.getElementById('f-pw').required = false;
        document.getElementById('f-email').value  = kar.email || '';
        document.getElementById('f-pw').value     = '';
        document.getElementById('f-nip').value    = kar.nip || '';
        document.getElementById('f-nama').value   = kar.nama || '';
        document.getElementById('f-hp').value     = kar.no_hp || '';
        document.getElementById('f-jab').value    = kar.jabatan_id || '';
        document.getElementById('f-jam').value    = kar.jam_kerja_id || '';
        document.getElementById('f-alamat').value = kar.alamat || '';
        clearErrors();
        document.getElementById('modal-form').style.display = 'flex';
    })
    .catch(() => { window.location.href = `/instansi/karyawan/${id}/edit`; });
}

function closeForm() {
    const box = document.querySelector('#modal-form .modal-box');
    box.style.transition = 'opacity .18s,transform .18s';
    box.style.opacity = '0'; box.style.transform = 'scale(.95) translateY(10px)';
    setTimeout(() => { document.getElementById('modal-form').style.display = 'none'; box.style.transition = ''; box.style.opacity = ''; box.style.transform = ''; }, 200);
}

function submitForm() {
    const form = document.getElementById('form-kar');
    const fd = new FormData(form);
    const btn = document.getElementById('btn-submit');
    const lbl = document.getElementById('btn-lbl');
    const method = document.getElementById('f-method').value;
    btn.disabled = true; lbl.textContent = 'Menyimpan…';
    clearErrors();
    if (method !== 'POST') { fd.append('_method', method); }
    fetch(form.action, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF() }, body: fd })
    .then(async r => { const t = await r.text(); try { return JSON.parse(t); } catch { throw new Error('Server tidak mengembalikan JSON.'); } })
    .then(data => {
        if (data.success) {
            closeForm(); showToast('tok', data.message || 'Data berhasil disimpan');
            setTimeout(() => location.reload(), 900);
        } else if (data.errors) {
            const map = { email:'err-email', password:'err-password', nip:'err-nip', nama:'err-nama', no_hp:'err-no_hp', jabatan_id:'err-jabatan_id', jam_kerja_id:'err-jam_kerja_id', alamat:'err-alamat' };
            for (const [field, msgs] of Object.entries(data.errors)) { const el = document.getElementById(map[field]); if (el) el.textContent = msgs[0]; }
        } else { showToast('terr', data.message || 'Terjadi kesalahan'); }
    })
    .catch(err => showToast('terr', err.message || 'Gagal terhubung ke server'))
    .finally(() => { btn.disabled = false; lbl.textContent = method === 'POST' ? 'Simpan Karyawan' : 'Update Karyawan'; });
}

let _delId = null;
function openDel(id, nama) { _delId = id; document.getElementById('del-name-lbl').textContent = `"${nama}"`; document.getElementById('modal-del').style.display = 'flex'; }
function closeDel() { document.getElementById('modal-del').style.display = 'none'; _delId = null; }
function doDelete() {
    if (!_delId) return;
    const btn = document.getElementById('btn-del-ok');
    btn.disabled = true; btn.innerHTML = '<span>Menghapus…</span>';
    fetch(`/instansi/karyawan/${_delId}`, { method: 'DELETE', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF(), 'Accept': 'application/json' } })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            const row = document.getElementById(`row-${_delId}`);
            if (row) { row.style.transition = 'opacity .25s,transform .25s'; row.style.opacity = '0'; row.style.transform = 'translateX(20px)'; setTimeout(() => { row.remove(); const b = document.getElementById('cnt-badge'); b.textContent = Math.max(0, parseInt(b.textContent) - 1); }, 250); }
            closeDel(); showToast('tok', 'Karyawan berhasil dihapus');
        } else { showToast('terr', data.message || 'Gagal menghapus'); btn.disabled = false; }
    })
    .catch(() => { showToast('terr', 'Kesalahan jaringan'); btn.disabled = false; });
}

function showToast(type, msg) {
    const old = document.querySelector('.toast'); if (old) old.remove();
    const ico = type === 'tok' ? '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>' : '<circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>';
    const t = document.createElement('div');
    t.className = `toast ${type}`;
    t.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">${ico}</svg><span>${msg}</span>`;
    document.body.appendChild(t);
    setTimeout(() => { t.style.transition = 'opacity .3s'; t.style.opacity = '0'; setTimeout(() => t.remove(), 300); }, 3500);
}

document.addEventListener('keydown', e => { if (e.key === 'Escape') { closeForm(); closeDel(); } });
</script>
@endpush

</x-app-layout>