<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tambah Kartu Keluarga</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<style>
  :root {
    --primary: #0d9488;       /* teal-600 — warna utama sidebar */
    --primary-dark: #0f766e;  /* teal-700 — hover */
    --primary-light: #f0fdfa; /* teal-50 */
    --primary-mid: #99f6e4;   /* teal-200 */
    --accent: #14b8a6;        /* teal-500 */
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --bg: #f1f5f9;
    --card: #ffffff;
    --border: #e2e8f0;
    --text: #0f172a;
    --muted: #64748b;
    --radius: 12px;
    --shadow: 0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.05);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    background: var(--bg);
    font-family: 'Segoe UI', system-ui, sans-serif;
    color: var(--text);
    min-height: 100vh;
    padding: 20px 16px 40px;
  }

  /* ─── WRAPPER ─────────────────────────── */
  .page-wrap {
    max-width: 1300px;       /* lebih lebar di desktop */
    margin: 0 auto;
  }

  /* ─── CARD ────────────────────────────── */
  .kk-card {
    background: var(--card);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
  }

  .kk-header {
    background: linear-gradient(135deg, #0f766e 0%, #0d9488 55%, #14b8a6 100%);
    padding: 20px 28px 18px;
    display: flex;
    align-items: flex-start;
    gap: 14px;
  }
  .kk-header-icon {
    width: 44px; height: 44px; flex-shrink: 0;
    background: rgba(255,255,255,.18);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.4rem; color: #fff;
  }
  .kk-header h5 { color: #fff; font-size: 1.15rem; font-weight: 700; margin-bottom: 2px; }
  .back-link {
    color: rgba(255,255,255,.75); font-size: .8rem; text-decoration: none;
    display: inline-flex; align-items: center; gap: 4px; margin-bottom: 4px;
    transition: color .15s;
  }
  .back-link:hover { color: #fff; }

  .kk-body { padding: 24px 28px; }

  /* ─── ALERT ───────────────────────────── */
  .alert-err {
    background: #fef2f2; border: 1px solid #fecaca;
    color: #991b1b; border-radius: 8px; padding: 10px 14px;
    display: flex; align-items: flex-start; gap: 8px;
    font-size: .86rem; margin-bottom: 20px;
  }

  /* ─── SECTION BLOCK ───────────────────── */
  .form-block { margin-bottom: 24px; }
  .form-block-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 10px 16px;
    background: var(--primary-light);
    border: 1px solid var(--primary-mid);
    border-radius: 8px 8px 0 0;
    gap: 10px;
  }
  .block-label {
    font-weight: 700; font-size: .88rem; color: var(--primary);
    display: flex; align-items: center; gap: 7px;
  }
  .block-label .sub { font-weight: 400; color: var(--muted); font-size: .75rem; }
  .form-block-body {
    border: 1px solid var(--border); border-top: none;
    border-radius: 0 0 8px 8px; padding: 20px 16px;
  }

  /* ─── FORM CONTROLS ───────────────────── */
  .form-label { font-size: .82rem; font-weight: 600; color: var(--muted); margin-bottom: 5px; display: block; }
  .form-control, .form-select {
    width: 100%; padding: 8px 11px; font-size: .875rem;
    border: 1px solid var(--border); border-radius: 7px;
    background: #fff; color: var(--text);
    transition: border-color .15s, box-shadow .15s;
    outline: none;
    font-family: inherit;
  }
  .form-control:focus, .form-select:focus {
    border-color: var(--primary); box-shadow: 0 0 0 3px rgba(13,148,136,.12);
  }
  textarea.form-control { resize: vertical; }

  .row { display: flex; flex-wrap: wrap; gap: 14px; }
  .col-full { flex: 1 1 100%; }
  .col-half { flex: 1 1 calc(50% - 7px); min-width: 160px; }
  .col-third { flex: 1 1 calc(33.33% - 10px); min-width: 140px; }
  .col-quarter { flex: 1 1 calc(25% - 11px); min-width: 130px; }
  .col-mini { flex: 1 1 calc(12% - 11px); min-width: 90px; }

  /* ─── INFO BOX ────────────────────────── */
  .info-box {
    background: #f0fdfa; border: 1px solid #99f6e4;
    border-radius: 8px; padding: 10px 14px;
    display: flex; gap: 10px; align-items: flex-start;
    font-size: .82rem; color: #134e4a; margin-top: 14px;
  }
  .info-box i { color: #0d9488; flex-shrink: 0; margin-top: 1px; }

  /* ─── ADD ROW BTN ─────────────────────── */
  .btn-add {
    display: inline-flex; align-items: center; gap: 6px;
    background: var(--primary); color: #fff;
    border: none; border-radius: 7px;
    padding: 7px 14px; font-size: .82rem; font-weight: 600;
    cursor: pointer; transition: background .15s, transform .1s;
    white-space: nowrap;
  }
  .btn-add:hover { background: var(--primary-dark); }
  .btn-add:active { transform: scale(.97); }

  /* ─── FOOTER ──────────────────────────── */
  .form-footer {
    display: flex; justify-content: flex-end; gap: 10px;
    padding: 16px 28px; border-top: 1px solid var(--border);
    background: #fafafa;
  }
  .btn-cancel {
    display: inline-flex; align-items: center; gap: 6px;
    background: #fff; border: 1px solid var(--border);
    color: var(--muted); border-radius: 8px;
    padding: 9px 18px; font-size: .875rem; font-weight: 600;
    cursor: pointer; text-decoration: none;
    transition: background .15s, border-color .15s;
  }
  .btn-cancel:hover { background: #f1f5f9; border-color: #cbd5e1; }
  .btn-submit {
    display: inline-flex; align-items: center; gap: 7px;
    background: var(--primary); color: #fff;
    border: none; border-radius: 8px;
    padding: 9px 22px; font-size: .875rem; font-weight: 700;
    cursor: pointer; transition: background .15s, transform .1s;
  }
  .btn-submit:hover { background: var(--primary-dark); }
  .btn-submit:active { transform: scale(.98); }

  /* ═══════════════════════════════════════
     DESKTOP TABLE VIEW
  ═══════════════════════════════════════ */
  .table-wrap {
    overflow-x: auto;
    border-radius: 8px;
    border: 1px solid var(--border);
  }
  .anggota-table {
    width: 100%; border-collapse: collapse;
    font-size: .82rem; min-width: 900px;
  }
  .anggota-table thead tr {
    background: #f8fafc;
    border-bottom: 2px solid var(--border);
  }
  .anggota-table th {
    padding: 9px 10px; text-align: left;
    font-weight: 700; color: var(--muted); white-space: nowrap;
    font-size: .78rem; text-transform: uppercase; letter-spacing: .03em;
  }
  .anggota-table td {
    padding: 7px 8px; vertical-align: middle;
    border-bottom: 1px solid var(--border);
  }
  .anggota-table tr:last-child td { border-bottom: none; }
  .anggota-table tr:hover td { background: var(--primary-light); }

  .anggota-table .form-control,
  .anggota-table .form-select {
    padding: 5px 8px; font-size: .8rem; border-radius: 6px;
  }
  .badge-kk {
    display: inline-flex; align-items: center; justify-content: center;
    background: var(--primary); color: #fff;
    border-radius: 5px; font-size: .68rem; font-weight: 800;
    padding: 2px 6px; letter-spacing: .04em;
  }
  .nik-status { font-size: .68rem; display: block; margin-top: 2px; }
  .btn-del {
    background: #fee2e2; border: 1px solid #fecaca;
    color: #991b1b; border-radius: 6px;
    padding: 4px 8px; font-size: .75rem; cursor: pointer;
    transition: background .15s;
  }
  .btn-del:hover { background: #fecaca; }

  /* ═══════════════════════════════════════
     MOBILE CARD VIEW
  ═══════════════════════════════════════ */
  .mobile-cards { display: none; }
  .anggota-card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 10px; padding: 14px;
    margin-bottom: 12px;
    position: relative;
    box-shadow: 0 1px 4px rgba(0,0,0,.06);
    animation: slideIn .2s ease;
  }
  @keyframes slideIn { from { opacity:0; transform: translateY(8px); } to { opacity:1; transform: none; } }

  .anggota-card.is-kepala {
    border-color: var(--primary); border-width: 2px;
    background: linear-gradient(135deg, var(--primary-light) 0%, #fff 60%);
  }
  .card-badge {
    display: inline-flex; align-items: center; gap: 5px;
    font-size: .72rem; font-weight: 700;
    padding: 3px 10px; border-radius: 20px;
    margin-bottom: 12px;
  }
  .card-badge.kepala { background: var(--primary); color: #fff; }
  .card-badge.anggota { background: #f1f5f9; color: var(--muted); }
  .card-del {
    position: absolute; top: 12px; right: 12px;
    background: #fee2e2; border: 1px solid #fecaca;
    color: #991b1b; border-radius: 7px;
    width: 30px; height: 30px;
    display: flex; align-items: center; justify-content: center;
    font-size: .85rem; cursor: pointer;
    transition: background .15s;
  }
  .card-del:hover { background: #fecaca; }

  .card-row { display: flex; flex-wrap: wrap; gap: 10px; }
  .card-field { display: flex; flex-direction: column; gap: 4px; }
  .card-field .form-label { margin-bottom: 0; }
  .cf-full { flex: 1 1 100%; }
  .cf-half { flex: 1 1 calc(50% - 5px); }
  .cf-third { flex: 1 1 calc(33% - 7px); min-width: 90px; }

  /* ═══════════════════════════════════════
     RESPONSIVE BREAKPOINTS
  ═══════════════════════════════════════ */
  @media (max-width: 767px) {
    body { padding: 12px 12px 40px; }
    .kk-body { padding: 16px 14px; }
    .form-footer { padding: 14px 16px; }
    .table-wrap, .anggota-table { display: none !important; }
    .mobile-cards { display: block; }
    .col-half { flex: 1 1 calc(50% - 7px); }
    .col-third { flex: 1 1 calc(50% - 7px); }
    .col-quarter { flex: 1 1 calc(50% - 7px); }
    .col-mini { flex: 1 1 calc(50% - 7px); }
    .btn-submit, .btn-cancel { padding: 9px 14px; font-size: .83rem; }
  }

  @media (min-width: 768px) and (max-width: 1199px) {
    .page-wrap { max-width: 100%; }
  }
</style>
</head>
<body>

<div class="page-wrap">
  <div class="kk-card">

    <!-- HEADER -->
    <div class="kk-header">
      <div class="kk-header-icon"><i class="bi bi-house-door-fill"></i></div>
      <div>
        <a href="<?php echo base_url('kartu-keluarga'); ?>" class="back-link">
          <i class="bi bi-arrow-left"></i> Kembali ke Daftar KK
        </a>
        <h5>Tambah Kartu Keluarga</h5>
      </div>
    </div>

    <div class="kk-body">

      <!-- ALERTS -->
      <?php echo validation_errors('<div class="alert-err"><i class="bi bi-exclamation-circle-fill"></i><span>', '</span></div>'); ?>
      <?php if($this->session->flashdata('error')): ?>
      <div class="alert-err">
        <i class="bi bi-exclamation-circle-fill"></i>
        <span><?php echo $this->session->flashdata('error'); ?></span>
      </div>
      <?php endif; ?>

      <form action="<?php echo base_url('kartu-keluarga/tambah'); ?>" method="post" id="formKK">

        <!-- ─── DATA KK ───────────────────────────── -->
        <div class="form-block">
          <div class="form-block-header">
            <div class="block-label"><i class="bi bi-card-text"></i> Data Kartu Keluarga</div>
          </div>
          <div class="form-block-body">
            <div class="row">
              <div class="col-half" style="min-width:220px;">
                <label class="form-label">Nomor KK <span style="color:var(--danger)">*</span></label>
                <input type="text" name="no_kk" class="form-control" maxlength="16" required
                       value="<?php echo set_value('no_kk'); ?>" placeholder="16 digit nomor KK">
              </div>
              <div class="col-mini">
                <label class="form-label">RT</label>
                <input type="text" name="rt" class="form-control" maxlength="3"
                       value="<?php echo set_value('rt'); ?>" placeholder="001">
              </div>
              <div class="col-mini">
                <label class="form-label">RW</label>
                <input type="text" name="rw" class="form-control" maxlength="3"
                       value="<?php echo set_value('rw'); ?>" placeholder="001">
              </div>
              <div class="col-full">
                <label class="form-label">Alamat <span style="color:var(--danger)">*</span></label>
                <textarea name="alamat" class="form-control" rows="2" required
                          placeholder="Jalan, gang, nomor rumah..."><?php echo set_value('alamat'); ?></textarea>
              </div>
              <div class="col-quarter" style="min-width:130px;">
                <label class="form-label">Desa / Kelurahan</label>
                <input type="text" name="desa" class="form-control" value="<?php echo set_value('desa'); ?>">
              </div>
              <div class="col-quarter" style="min-width:130px;">
                <label class="form-label">Kecamatan</label>
                <input type="text" name="kecamatan" class="form-control" value="<?php echo set_value('kecamatan'); ?>">
              </div>
              <div class="col-quarter" style="min-width:130px;">
                <label class="form-label">Kabupaten / Kota</label>
                <input type="text" name="kabupaten" class="form-control" value="<?php echo set_value('kabupaten'); ?>">
              </div>
              <div class="col-quarter" style="min-width:100px;">
                <label class="form-label">Kode Pos</label>
                <input type="text" name="kode_pos" class="form-control" maxlength="5"
                       value="<?php echo set_value('kode_pos'); ?>" placeholder="12345">
              </div>
            </div>
          </div>
        </div>

        <!-- ─── ANGGOTA KELUARGA ───────────────────── -->
        <div class="form-block">
          <div class="form-block-header">
            <div class="block-label">
              <i class="bi bi-people-fill"></i> Anggota Keluarga
              <span class="sub">— baris pertama otomatis jadi Kepala Keluarga</span>
            </div>
            <button type="button" class="btn-add" onclick="tambahBaris()">
              <i class="bi bi-plus-circle"></i> Tambah Anggota
            </button>
          </div>
          <div class="form-block-body" style="padding-bottom:14px;">

            <!-- DESKTOP TABLE -->
            <div class="table-wrap">
              <table class="anggota-table" id="tabelAnggota">
                <thead>
                  <tr>
                    <th style="width:42px;">#</th>
                    <th style="width:160px;">NIK <span style="color:var(--danger)">*</span></th>
                    <th style="min-width:180px;">Nama Lengkap <span style="color:var(--danger)">*</span></th>
                    <th style="width:65px;">L/P</th>
                    <th style="width:140px;">Tgl Lahir</th>
                    <th style="width:155px;">Status Hub. <span style="color:var(--danger)">*</span></th>
                    <th style="width:120px;">Domisili</th>
                    <th style="width:140px;">Role <span style="color:var(--danger)">*</span></th>
                    <th style="width:40px;"></th>
                  </tr>
                </thead>
                <tbody id="bodyAnggota"></tbody>
              </table>
            </div>

            <!-- MOBILE CARDS -->
            <div class="mobile-cards" id="mobileCards"></div>

            <div class="info-box">
              <i class="bi bi-info-circle-fill"></i>
              <div>
                Setiap anggota otomatis mendapat akun login dengan
                <strong>Username = NIK</strong> dan <strong>Password = <code>password</code></strong>.
                Role default: <strong>Warga</strong>.
              </div>
            </div>
          </div>
        </div>

      </form>
    </div>

    <!-- FOOTER -->
    <div class="form-footer">
      <a href="<?php echo base_url('kartu-keluarga'); ?>" class="btn-cancel">
        <i class="bi bi-x-lg"></i> Batal
      </a>
      <button type="submit" form="formKK" class="btn-submit">
        <i class="bi bi-save"></i> Simpan KK & Buat User
      </button>
    </div>

  </div>
</div>

<script>
const optHub = {
  <?php foreach($status_hubungan as $k => $v): ?>
  '<?php echo $k; ?>': '<?php echo $v; ?>',
  <?php endforeach; ?>
};
const optDom = {
  <?php foreach($status_domisili as $k => $v): ?>
  '<?php echo $k; ?>': '<?php echo $v; ?>',
  <?php endforeach; ?>
};
const optRole = {
  'warga': 'Warga',
  'admin': 'Administrator',
  'ketua_rt': 'Ketua RT',
  'sekretaris': 'Sekretaris',
  'bendahara': 'Bendahara'
};

let barisCount = 0;

function selHub(idx, isKepala) {
  if (isKepala) {
    return `<select class="form-select" name="anggota[${idx}][status_hubungan]" required disabled>
              <option value="kepala_keluarga" selected>Kepala Keluarga</option>
            </select>
            <input type="hidden" name="anggota[${idx}][status_hubungan]" value="kepala_keluarga">`;
  }
  let o = '<option value="">-- Pilih --</option>';
  Object.entries(optHub).forEach(([k,v]) => {
    if (k !== 'kepala_keluarga') o += `<option value="${k}">${v}</option>`;
  });
  return `<select class="form-select" name="anggota[${idx}][status_hubungan]" required>${o}</select>`;
}

function selDom(idx) {
  let o = '';
  Object.entries(optDom).forEach(([k,v]) => {
    o += `<option value="${k}"${k==='tetap'?' selected':''}>${v}</option>`;
  });
  return `<select class="form-select" name="anggota[${idx}][status_domisili]">${o}</select>`;
}

function selRole(idx) {
  let o = '';
  Object.entries(optRole).forEach(([k,v]) => {
    o += `<option value="${k}"${k==='warga'?' selected':''}>${v}</option>`;
  });
  return `<select class="form-select" name="anggota[${idx}][role]" required>${o}</select>`;
}

function nikStatus(input) {
  const n = input.value.trim();
  const s = input.nextElementSibling;
  if (!s) return;
  if (n.length === 16) s.innerHTML = '<span style="color:var(--success)"><i class="bi bi-check-circle"></i> Valid</span>';
  else if (n.length > 0) s.innerHTML = '<span style="color:var(--warning)"><i class="bi bi-exclamation-triangle"></i> Harus 16 digit</span>';
  else s.innerHTML = '';
}

function tambahBaris() {
  const idx     = barisCount++;
  const no      = idx + 1;
  const isKepala = (idx === 0);

  /* ── Desktop row ── */
  const tr = document.createElement('tr');
  tr.id = 'tr_' + idx;
  const badge   = isKepala ? `<span class="badge-kk">KK</span>` : `<span style="color:var(--muted);font-size:.8rem;">${no}</span>`;
  const delBtn  = isKepala ? `<span style="color:var(--border)">—</span>`
    : `<button type="button" class="btn-del" onclick="hapusBaris(${idx})" title="Hapus"><i class="bi bi-x-lg"></i></button>`;

  tr.innerHTML = `
    <td class="text-center">${badge}</td>
    <td>
      <input type="text" name="anggota[${idx}][nik]" class="form-control nik-input"
             maxlength="16" required placeholder="16 digit" onblur="nikStatus(this)">
      <small class="nik-status"></small>
    </td>
    <td><input type="text" name="anggota[${idx}][nama_lengkap]" class="form-control" required placeholder="Nama lengkap"></td>
    <td>
      <select class="form-select" name="anggota[${idx}][jenis_kelamin]">
        <option value="">-</option>
        <option value="L">L</option>
        <option value="P">P</option>
      </select>
    </td>
    <td><input type="date" name="anggota[${idx}][tanggal_lahir]" class="form-control"></td>
    <td>${selHub(idx, isKepala)}</td>
    <td>${selDom(idx)}</td>
    <td>${selRole(idx)}</td>
    <td class="text-center">${delBtn}</td>`;
  document.getElementById('bodyAnggota').appendChild(tr);

  /* ── Mobile card ── */
  const card = document.createElement('div');
  card.id = 'card_' + idx;
  card.className = 'anggota-card' + (isKepala ? ' is-kepala' : '');

  const cardBadge = isKepala
    ? `<span class="card-badge kepala"><i class="bi bi-house-door-fill"></i> Kepala Keluarga</span>`
    : `<span class="card-badge anggota"><i class="bi bi-person"></i> Anggota ${no}</span>`;
  const cardDel = isKepala ? ''
    : `<button type="button" class="card-del" onclick="hapusBaris(${idx})" title="Hapus"><i class="bi bi-x-lg"></i></button>`;

  card.innerHTML = `
    ${cardDel}
    ${cardBadge}
    <div class="card-row">
      <div class="card-field cf-full">
        <label class="form-label">NIK <span style="color:var(--danger)">*</span></label>
        <input type="text" class="form-control nik-input-mobile" maxlength="16" required
               placeholder="16 digit" oninput="syncNik(this,${idx})" onblur="nikStatusMobile(this)">
        <small class="nik-status-mobile" style="font-size:.7rem;"></small>
      </div>
      <div class="card-field cf-full">
        <label class="form-label">Nama Lengkap <span style="color:var(--danger)">*</span></label>
        <input type="text" class="form-control" required placeholder="Nama lengkap"
               oninput="syncField(this, 'anggota[${idx}][nama_lengkap]')">
      </div>
      <div class="card-field cf-third">
        <label class="form-label">L/P</label>
        <select class="form-select" oninput="syncField(this, 'anggota[${idx}][jenis_kelamin]')">
          <option value="">-</option>
          <option value="L">Laki-laki</option>
          <option value="P">Perempuan</option>
        </select>
      </div>
      <div class="card-field cf-half" style="flex:1 1 60%;">
        <label class="form-label">Tanggal Lahir</label>
        <input type="date" class="form-control" oninput="syncField(this, 'anggota[${idx}][tanggal_lahir]')">
      </div>
      <div class="card-field cf-full">
        <label class="form-label">Status Hubungan <span style="color:var(--danger)">*</span></label>
        ${isKepala
          ? `<select class="form-select" disabled><option value="kepala_keluarga" selected>Kepala Keluarga</option></select>`
          : `<select class="form-select" required oninput="syncField(this, 'anggota[${idx}][status_hubungan]')">
               <option value="">-- Pilih --</option>
               ${Object.entries(optHub).filter(([k])=>k!=='kepala_keluarga').map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
             </select>`}
      </div>
      <div class="card-field cf-half">
        <label class="form-label">Domisili</label>
        <select class="form-select" oninput="syncField(this, 'anggota[${idx}][status_domisili]')">
          ${Object.entries(optDom).map(([k,v])=>`<option value="${k}"${k==='tetap'?' selected':''}>${v}</option>`).join('')}
        </select>
      </div>
      <div class="card-field cf-half">
        <label class="form-label">Role <span style="color:var(--danger)">*</span></label>
        <select class="form-select" required oninput="syncField(this, 'anggota[${idx}][role]')">
          ${Object.entries(optRole).map(([k,v])=>`<option value="${k}"${k==='warga'?' selected':''}>${v}</option>`).join('')}
        </select>
      </div>
    </div>`;

  document.getElementById('mobileCards').appendChild(card);

  /* focus NIK pada mode aktif */
  if (window.innerWidth < 768) card.querySelector('.nik-input-mobile').focus();
  else tr.querySelector('.nik-input').focus();
}

/* ─── Sync mobile → hidden table fields ─── */
function syncNik(mobileInput, idx) {
  const tableInput = document.querySelector(`#tr_${idx} .nik-input`);
  if (tableInput) tableInput.value = mobileInput.value;
}
function syncField(mobileSelect, fieldName) {
  const tableEl = document.querySelector(`[name="${fieldName}"]`);
  if (tableEl) tableEl.value = mobileSelect.value;
}
function nikStatusMobile(input) {
  const n = input.value.trim();
  const s = input.nextElementSibling;
  if (!s) return;
  if (n.length === 16) s.innerHTML = '<span style="color:var(--success)"><i class="bi bi-check-circle"></i> Valid</span>';
  else if (n.length > 0) s.innerHTML = '<span style="color:var(--warning)"><i class="bi bi-exclamation-triangle"></i> Harus 16 digit</span>';
  else s.innerHTML = '';
}

function hapusBaris(idx) {
  const tr   = document.getElementById('tr_'   + idx);
  const card = document.getElementById('card_' + idx);
  if (tr)   tr.remove();
  if (card) card.remove();
}

document.getElementById('formKK').addEventListener('submit', function(e) {
  const rows = document.querySelectorAll('#bodyAnggota tr');
  if (rows.length === 0) {
    e.preventDefault();
    alert('Minimal harus ada 1 anggota (Kepala Keluarga)');
    return;
  }
  const niks = [];
  let dup = false;
  document.querySelectorAll('.nik-input').forEach(inp => {
    const nik = inp.value.trim();
    if (niks.includes(nik) && nik !== '') {
      dup = true; inp.style.borderColor = 'var(--danger)';
    } else {
      niks.push(nik); inp.style.borderColor = '';
    }
  });
  if (dup) {
    e.preventDefault();
    alert('NIK tidak boleh duplikat dalam satu KK!');
  }
});

document.addEventListener('DOMContentLoaded', function() { tambahBaris(); });
</script>
</body>
</html>