<?= $this->extend('layouts/main') ?>

<?= $this->section('css') ?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800&family=DM+Sans:wght@400;500;600&display=swap');

/* ══ CSS VARIABLES DI :root AGAR TERBACA DI SEMUA ELEMEN TERMASUK MODAL ══ */
:root {
    --accent:      #3b6ff5;
    --accent-soft: #eef3ff;
    --bg-side:     #ffffff;
    --bg-card2:    #fafbfe;
    --border:      #e5eaf5;
    --border2:     #cdd5e8;
    --text-main:   #0f1623;
    --text-muted:  #7a849e;
    --shadow:      0 2px 10px rgba(15,22,35,.05);
    --green:       #16a34a;
    --amber:       #d97706;
    --red:         #dc2626;
    --orange:      #f97316;
    --r:           16px;
    --r-sm:        10px;
}

.resep-wrap {
    font-family: 'DM Sans', sans-serif;
    color: var(--text-main);
}

/* ── Page Header ──────────────────────────────────── */
.resep-wrap .page-header {
    display: flex; align-items: flex-start; justify-content: space-between;
    flex-wrap: wrap; gap: 16px; margin-bottom: 28px;
}
.resep-wrap .page-title {
    font-family: 'Sora', sans-serif;
    font-size: 1.4rem; font-weight: 800; color: var(--text-main);
    display: flex; align-items: center; gap: 10px; margin: 0;
    letter-spacing: -0.5px;
}
.resep-wrap .page-title i { color: var(--accent); }
.resep-wrap .page-sub { font-size: 12px; color: var(--text-muted); margin-top: 5px; }
.resep-wrap .header-btns { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }

/* ── Alert Flash ──────────────────────────────────── */
.resep-wrap .alert-ok {
    background: #dcfce7; border: 1.5px solid #86efac; color: #166534;
    border-radius: var(--r-sm); padding: 12px 16px; margin-bottom: 16px;
    font-family: 'DM Sans', sans-serif;
    display: flex; align-items: center; gap: 10px; font-size: 13px;
}
.resep-wrap .alert-err {
    background: #fee2e2; border: 1.5px solid #fca5a5; color: #991b1b;
    border-radius: var(--r-sm); padding: 12px 16px; margin-bottom: 16px;
    font-family: 'DM Sans', sans-serif;
    display: flex; align-items: center; gap: 10px; font-size: 13px;
}

/* ── Card ─────────────────────────────────────────── */
.resep-wrap .card {
    background: var(--bg-side); border: 1px solid var(--border);
    border-radius: var(--r); overflow: hidden; margin-bottom: 20px;
    box-shadow: var(--shadow);
}
.resep-wrap .card-head {
    padding: 15px 22px; border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between; gap: 12px;
    background: var(--bg-card2);
}
.resep-wrap .card-title {
    display: flex; align-items: center; gap: 8px;
    font-family: 'Sora', sans-serif; font-size: .9rem; font-weight: 700; color: var(--text-main);
}
.resep-wrap .count-badge {
    font-size: 11px; color: var(--text-muted);
    background: #f0f2f9; padding: 3px 10px; border-radius: 20px; font-weight: 600;
}

/* ── Table ────────────────────────────────────────── */
.resep-wrap .tbl-wrap { overflow-x: auto; }
.resep-wrap table { width: 100%; border-collapse: collapse; }
.resep-wrap thead th {
    background: var(--bg-card2); color: var(--text-muted);
    font-size: 11px; text-transform: uppercase; letter-spacing: .05em;
    padding: 12px 18px; border-bottom: 1px solid var(--border);
    font-weight: 600; white-space: nowrap;
}
.resep-wrap thead th.text-center { text-align: center; }
.resep-wrap tbody td {
    padding: 14px 18px; border-bottom: 1px solid #f0f2f9;
    font-size: 13px; color: var(--text-main);
    vertical-align: middle;
}
.resep-wrap tbody tr:last-child td { border-bottom: none; }
.resep-wrap tbody tr:hover td { background: #f6f9ff; }
.resep-wrap .td-center { text-align: center; }

/* ── Badges (tabel utama) ─────────────────────────── */
.resep-wrap .badge-blue  { background: #dbeafe; color: #1d4ed8; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.resep-wrap .badge-green { background: #dcfce7; color: #15803d; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.resep-wrap .badge-amber { background: #fef3c7; color: #92400e; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }

/* ── Badges (global — dipakai di dalam modal juga) ── */
.badge-blue  { background: #dbeafe; color: #1d4ed8; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.badge-green { background: #dcfce7; color: #15803d; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }
.badge-amber { background: #fef3c7; color: #92400e; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; }

/* ── Buttons (tabel utama) ────────────────────────── */
.resep-wrap .btn-primary {
    background: var(--accent); color: #fff; border: none;
    border-radius: var(--r-sm); padding: 9px 18px;
    font-size: 13px; font-weight: 600; cursor: pointer;
    display: inline-flex; align-items: center; gap: 7px;
    font-family: 'DM Sans', sans-serif; transition: all .2s; white-space: nowrap;
}
.resep-wrap .btn-primary:hover { background: #2859e0; box-shadow: 0 4px 14px rgba(59,111,245,.28); }

.resep-wrap .btn-toggle {
    background: transparent; border: 1px solid var(--border);
    color: var(--text-muted); padding: 6px 10px;
    border-radius: var(--r-sm); font-size: 12px; font-weight: 600;
    cursor: pointer; transition: all .2s;
    display: inline-flex; align-items: center; gap: 4px;
    font-family: 'DM Sans', sans-serif;
}
.resep-wrap .btn-toggle:hover        { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.resep-wrap .btn-toggle.edit:hover   { border-color: var(--amber); color: var(--amber); background: #fef3c7; }
.resep-wrap .btn-toggle.danger:hover { border-color: var(--red); color: var(--red); background: #fee2e2; }

/* btn-toggle juga dipakai di dalam modal header */
.btn-toggle {
    background: transparent; border: 1px solid var(--border);
    color: var(--text-muted); padding: 6px 10px;
    border-radius: var(--r-sm); font-size: 12px; font-weight: 600;
    cursor: pointer; transition: all .2s;
    display: inline-flex; align-items: center; gap: 4px;
    font-family: 'DM Sans', sans-serif;
}
.btn-toggle:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }

/* ── Empty State ──────────────────────────────────── */
.resep-wrap .empty-state { text-align: center; padding: 60px 24px; color: var(--text-muted); }
.resep-wrap .empty-state i { font-size: 2.2rem; opacity: .2; display: block; margin-bottom: 12px; }
.resep-wrap .empty-state h5 { font-family: 'Sora', sans-serif; color: var(--text-main); margin-bottom: 8px; font-size: .95rem; }
.resep-wrap .empty-state p  { font-size: 13px; margin: 0; }

/* ══════════════════════════════════════════════════
   MODAL SYSTEM
══════════════════════════════════════════════════ */
.resep-overlay {
    display: none; position: fixed; inset: 0; z-index: 600;
    background: rgba(15,22,35,.42); backdrop-filter: blur(4px);
    align-items: center; justify-content: center;
    opacity: 0; transition: opacity .22s ease;
    padding: 20px; box-sizing: border-box;
}
.resep-overlay.visible       { display: flex; }
.resep-overlay.visible.shown { opacity: 1; }
.resep-overlay.closing       { opacity: 0; transition: opacity .18s ease-in; }

/* ── Modal: flex-column agar footer SELALU terlihat ── */
.resep-modal {
    background: #ffffff;
    border: 1px solid var(--border);
    border-radius: 20px;
    max-width: 680px; width: 100%;
    max-height: 90vh;
    min-height: 300px;
    box-shadow: 0 20px 60px rgba(15,22,35,.14);
    transform: scale(.93) translateY(14px); opacity: 0;
    transition: transform .28s cubic-bezier(.34,1.38,.64,1), opacity .22s ease;
    /* KUNCI: flex column supaya footer sticky di bawah */
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 0;
}
#modal-show .resep-modal,
#modal-edit .resep-modal { max-width: 780px; }

.resep-overlay.shown   .resep-modal { transform: scale(1) translateY(0); opacity: 1; }
.resep-overlay.closing .resep-modal {
    transform: scale(.95) translateY(8px); opacity: 0;
    transition: transform .16s ease-in, opacity .15s ease-in;
}

/* ── Area konten yang bisa di-scroll ─────────────── */
.modal-scrollable {
    flex: 1 1 auto;
    overflow-y: auto;
    padding: 28px 30px 16px 30px;
    min-height: 0; /* penting agar flex child bisa shrink */
}
.modal-scrollable::-webkit-scrollbar { width: 5px; }
.modal-scrollable::-webkit-scrollbar-track { background: transparent; }
.modal-scrollable::-webkit-scrollbar-thumb { background: #dde2f0; border-radius: 10px; }
.modal-scrollable::-webkit-scrollbar-thumb:hover { background: #c5cde0; }

/* ── Modal Header ─────────────────────────────────── */
.m-head { display: flex; align-items: center; gap: 14px; margin-bottom: 24px; }
.m-ico {
    width: 44px; height: 44px; border-radius: 12px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center; font-size: 18px;
}
.m-ico.blue   { background: var(--accent-soft); color: var(--accent); }
.m-ico.orange { background: #fff7ed; color: var(--orange); }
.m-title { font-family: 'Sora', sans-serif; font-size: 1.05rem; font-weight: 700; color: var(--text-main); margin: 0; }
.m-sub   { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
.m-head-actions { margin-left: auto; display: flex; gap: 8px; align-items: center; flex-shrink: 0; }

/* ── Modal Divider ────────────────────────────────── */
.m-divider { border: none; border-top: 1px solid var(--border); margin: 18px 0; }

/* ── Modal Footer — SELALU di bawah, tidak pernah terpotong ── */
.m-footer {
    display: flex;
    gap: 10px;
    padding: 14px 30px 22px 30px;
    border-top: 1px solid var(--border);
    background: #ffffff;
    flex-shrink: 0; /* tidak boleh menyusut */
    flex-grow: 0;
}

/* ── Tombol Cancel (abu) ──────────────────────────── */
.btn-mc {
    flex: 1;
    padding: 11px 16px;
    border-radius: var(--r-sm);
    border: 1.5px solid var(--border2);
    background: #f2f5fb;
    color: #4b5675;
    font-size: 13px; font-weight: 600;
    cursor: pointer;
    font-family: 'DM Sans', sans-serif;
    transition: all .18s;
    display: inline-flex; align-items: center; justify-content: center; gap: 7px;
}
.btn-mc:hover { background: #e5eaf5; color: var(--text-main); }

/* ── Tombol Simpan (warna) ────────────────────────── */
.btn-ms {
    flex: 2;
    padding: 11px 16px;
    border-radius: var(--r-sm);
    border: none;
    color: #fff;
    font-size: 13px; font-weight: 700;
    cursor: pointer;
    font-family: 'DM Sans', sans-serif;
    display: inline-flex; align-items: center; justify-content: center; gap: 7px;
    position: relative; overflow: hidden;
    transition: background .2s, box-shadow .2s, transform .15s;
}
.btn-ms:active:not(:disabled) { transform: scale(.96); }
.btn-ms:disabled { cursor: not-allowed; opacity: .72; }

/* label & spinner di dalam tombol */
.btn-ms .btn-label { display: inline-flex; align-items: center; gap: 7px; transition: opacity .15s, transform .15s; }
.btn-ms .btn-spin {
    display: none; position: absolute;
    width: 19px; height: 19px; border-radius: 50%;
    border: 2.5px solid rgba(255,255,255,.3); border-top-color: #fff;
    animation: bspin .5s linear infinite;
}
@keyframes bspin { to { transform: rotate(360deg); } }

.btn-ms.loading .btn-label { opacity: 0; transform: scale(.8); }
.btn-ms.loading .btn-spin  { display: block; }
.btn-ms.done    .btn-label { opacity: 0; }
.btn-ms.done::after {
    content: '✓'; position: absolute;
    font-size: 1.15rem; font-weight: 700; color: #fff;
    animation: tickPop .28s cubic-bezier(.34,1.6,.64,1) forwards;
}
@keyframes tickPop { from { transform:scale(.3); opacity:0; } to { transform:scale(1); opacity:1; } }

/* Warna tiap varian tombol simpan */
.btn-ms.green  { background: var(--green); }
.btn-ms.green:not(:disabled):hover  { background: #138638; box-shadow: 0 4px 14px rgba(22,163,74,.28); }
.btn-ms.orange { background: var(--orange); }
.btn-ms.orange:not(:disabled):hover { background: #ea6b0a; box-shadow: 0 4px 14px rgba(249,115,22,.28); }
.btn-ms.blue   { background: var(--accent); }
.btn-ms.blue:not(:disabled):hover   { background: #2859e0; box-shadow: 0 4px 14px rgba(59,111,245,.28); }

/* Ripple effect */
.ripple {
    position: absolute; border-radius: 50%;
    background: rgba(255,255,255,.28); transform: scale(0);
    animation: rippleAnim .55s ease-out forwards; pointer-events: none;
}
@keyframes rippleAnim { to { transform: scale(4.5); opacity: 0; } }

/* Shake on error */
@keyframes shake {
    0%,100% { transform: translateX(0); }
    20%     { transform: translateX(-5px); }
    40%     { transform: translateX(5px); }
    60%     { transform: translateX(-3px); }
    80%     { transform: translateX(3px); }
}
.shake { animation: shake .32s ease; }

/* ── Form Fields ──────────────────────────────────── */
.f-row      { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 14px; }
.f-row.full { grid-template-columns: 1fr; }
.f-grp      { display: flex; flex-direction: column; gap: 6px; }
.f-grp label {
    font-size: 11px; font-weight: 600; text-transform: uppercase;
    letter-spacing: .07em; color: var(--text-muted);
}
.f-grp input, .f-grp select, .f-grp textarea {
    padding: 10px 13px; border: 1.5px solid var(--border);
    border-radius: var(--r-sm); background: #f8faff;
    color: var(--text-main); font-family: 'DM Sans', sans-serif; font-size: 14px;
    outline: none; transition: border-color .18s, background .18s, box-shadow .18s;
    box-sizing: border-box; width: 100%;
}
.f-grp input:focus, .f-grp select:focus, .f-grp textarea:focus {
    border-color: var(--accent); background: #fff;
    box-shadow: 0 0 0 3px rgba(59,111,245,.1);
}
.f-grp textarea { resize: vertical; min-height: 72px; }
.f-grp input.invalid, .f-grp select.invalid {
    border-color: var(--red) !important; background: #fff5f5 !important;
    box-shadow: 0 0 0 3px rgba(220,38,38,.1) !important;
}
.form-error { font-size: 11px; color: var(--red); margin-top: 4px; display: none; }
.form-error.show { display: block; }

/* ── Items Section ────────────────────────────────── */
.items-section {
    border: 1.5px solid var(--border); border-radius: 12px;
    overflow: hidden; margin-bottom: 12px;
}
.items-head {
    background: var(--bg-card2); padding: 10px 16px;
    display: flex; align-items: center; justify-content: space-between;
    border-bottom: 1px solid var(--border);
}
.items-head span {
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .07em; color: var(--text-muted);
}
.item-row-header {
    display: grid; grid-template-columns: 2fr 1fr 1fr 80px 32px;
    gap: 8px; padding: 8px 14px; background: #f5f7fc;
    border-bottom: 1px solid var(--border);
}
.item-row-header span {
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .06em; color: var(--text-muted);
}
.item-row {
    display: grid; grid-template-columns: 2fr 1fr 1fr 80px 32px;
    gap: 8px; padding: 8px 14px; align-items: center;
    border-bottom: 1px solid #f0f2f9;
}
.item-row:last-child { border-bottom: none; }
.item-row input, .item-row select {
    padding: 7px 10px; border: 1.5px solid var(--border);
    border-radius: var(--r-sm); background: #f8faff;
    color: var(--text-main); font-family: 'DM Sans', sans-serif; font-size: 13px;
    outline: none; width: 100%; transition: border-color .18s, background .18s;
    box-sizing: border-box;
}
.item-row input:focus, .item-row select:focus { border-color: var(--accent); background: #fff; }
.item-row input.invalid, .item-row select.invalid {
    border-color: var(--red) !important; background: #fff5f5 !important;
}
.item-subtotal {
    font-family: 'Courier New', monospace; font-size: 12px; font-weight: 600;
    color: var(--green); text-align: right; white-space: nowrap;
}
.btn-rm-item {
    background: #fee2e2; border: none; border-radius: var(--r-sm);
    width: 32px; height: 32px; cursor: pointer; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center;
    color: var(--red); font-size: 12px; transition: all .18s;
}
.btn-rm-item:hover { background: #fca5a5; }
.btn-add-item {
    background: var(--accent-soft); border: 1.5px dashed #93c5fd;
    border-radius: var(--r-sm); padding: 9px; width: 100%;
    color: var(--accent); font-size: 13px; font-weight: 600;
    cursor: pointer; font-family: 'DM Sans', sans-serif;
    display: flex; align-items: center; justify-content: center; gap: 6px;
    transition: all .18s; margin-bottom: 14px;
    box-sizing: border-box;
}
.btn-add-item:hover { background: #dde8ff; border-color: var(--accent); }

/* ── Change Pill ──────────────────────────────────── */
.change-pill {
    display: none; background: #fef3c7; border: 1.5px solid #fcd34d; color: #92400e;
    border-radius: 20px; padding: 3px 10px; font-size: 11px; font-weight: 700;
    align-items: center; gap: 5px;
}
.change-pill.show { display: inline-flex; }

/* ── Show Modal: Summary Strip ────────────────────── */
.summary-strip { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 20px; }
.strip-item {
    flex: 1; min-width: 120px;
    background: var(--bg-side); border: 1px solid var(--border);
    border-radius: var(--r); padding: 14px 16px;
    display: flex; flex-direction: column; gap: 4px;
}
.strip-ico {
    width: 36px; height: 36px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 14px; margin-bottom: 6px;
}
.strip-ico.ic-b { background: var(--accent-soft); color: var(--accent); }
.strip-ico.ic-g { background: #dcfce7; color: var(--green); }
.strip-ico.ic-a { background: #fef3c7; color: var(--amber); }
.strip-val { font-family: 'Sora', sans-serif; font-size: 1.3rem; font-weight: 800; color: var(--text-main); letter-spacing: -1px; }
.strip-val.sm { font-size: .9rem; letter-spacing: 0; margin-top: 4px; }
.strip-lbl { font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: .06em; }

/* ── Section Card (di dalam modal) ───────────────── */
.section-card { border: 1.5px solid var(--border); border-radius: 12px; overflow: hidden; margin-bottom: 16px; }
.section-card-head {
    background: var(--bg-card2); padding: 10px 16px;
    display: flex; align-items: center; gap: 8px;
    border-bottom: 1px solid var(--border);
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .07em; color: var(--text-muted);
}
.section-card-body { padding: 16px; }

.info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; }
.info-item { display: flex; flex-direction: column; gap: 4px; }
.info-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); }
.info-value { font-size: 14px; font-weight: 600; color: var(--text-main); }

.catatan-box {
    background: #fafbff; border: 1.5px solid var(--border);
    border-radius: 10px; padding: 14px 16px; font-size: 13px;
    color: var(--text-main); line-height: 1.6; white-space: pre-wrap;
}
.catatan-box.empty { color: var(--text-muted); font-style: italic; }

/* ── Bahan Table (di dalam modal show) ───────────── */
.bahan-table { width: 100%; border-collapse: collapse; }
.bahan-table thead { background: var(--bg-card2); border-bottom: 1px solid var(--border); }
.bahan-table th {
    padding: 10px 14px; text-align: left;
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .06em; color: var(--text-muted);
}
.bahan-table td {
    padding: 12px 14px; border-bottom: 1px solid #f0f2f9;
    font-size: 13px; color: var(--text-main); vertical-align: middle;
}
.bahan-table tbody tr:last-child td { border-bottom: none; }
.bahan-table tbody tr:hover td { background: #f6f9ff; }
.bahan-table .no-col { width: 44px; text-align: center; color: var(--text-muted); }
.bahan-table .jumlah-col { font-family: 'Courier New', monospace; font-size: 13px; font-weight: 700; color: var(--green); }
.bahan-ico {
    width: 28px; height: 28px; border-radius: 8px;
    background: var(--accent-soft); color: var(--accent);
    display: inline-flex; align-items: center; justify-content: center;
    font-size: 12px; margin-right: 8px; vertical-align: middle;
}

/* ── Toast ────────────────────────────────────────── */
#resep-toast {
    position: fixed; bottom: 24px; right: 24px; z-index: 9999;
    padding: 14px 18px; border-radius: 14px; font-size: 13px; font-weight: 600;
    display: flex; align-items: center; gap: 10px;
    transform: translateY(80px) scale(.94); opacity: 0;
    transition: all .34s cubic-bezier(.34,1.45,.64,1);
    max-width: 320px; pointer-events: none;
    box-shadow: 0 10px 30px rgba(0,0,0,.12); font-family: 'DM Sans', sans-serif;
}
#resep-toast.show    { transform: translateY(0) scale(1); opacity: 1; }
#resep-toast.success { background: #fff; border: 1.5px solid #86efac; color: #166534; }
#resep-toast.error   { background: #fff; border: 1.5px solid #fca5a5; color: #991b1b; }
.t-ico { width: 28px; height: 28px; border-radius: 8px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 14px; }
#resep-toast.success .t-ico { background: #dcfce7; }
#resep-toast.error   .t-ico { background: #fee2e2; }

/* ── Responsive ───────────────────────────────────── */
@media (max-width: 768px) {
    .resep-overlay { padding: 12px; }
    .resep-modal   { border-radius: 16px; max-height: 95vh; }
    .modal-scrollable { padding: 18px 16px 12px 16px; }
    .m-footer { padding: 12px 16px 18px 16px; }
    .item-row-header { grid-template-columns: 2fr 1fr 1fr 32px; gap: 6px; }
    .item-row        { grid-template-columns: 2fr 1fr 1fr 32px; gap: 6px; }
    .item-row-header span:nth-child(4),
    .item-row-header span:nth-child(5) { display: none; }
    .item-row .item-subtotal { display: none; }
    .f-row { grid-template-columns: 1fr; }
    .m-head-actions { display: none; }
    .summary-strip { gap: 8px; }
    .strip-item { min-width: 100px; padding: 12px; }
}
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<!-- Toast -->
<div id="resep-toast"><div class="t-ico" id="rt-ico"></div><span id="rt-msg"></span></div>

<!-- ════════════════════════════════════════════════
     MODAL: TAMBAH RESEP
════════════════════════════════════════════════ -->
<div class="resep-overlay" id="modal-resep">
    <div class="resep-modal">

        <div class="modal-scrollable">
            <div class="m-head">
                <div class="m-ico blue"><i class="bi bi-book-fill"></i></div>
                <div>
                    <p class="m-title">Tambah Resep Baru</p>
                    <p class="m-sub">Buat resep untuk produk Anda dengan daftar bahan detail</p>
                </div>
            </div>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Nama Resep</label>
                    <input id="resep-nama" type="text" placeholder="Contoh: Resep Bumbu Rawon">
                    <div class="form-error" id="err-nama"></div>
                </div>
            </div>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Produk</label>
                    <select id="resep-produk"><option value="">-- Pilih Produk --</option></select>
                    <div class="form-error" id="err-produk"></div>
                </div>
            </div>

            <hr class="m-divider">

            <div class="items-section">
                <div class="items-head">
                    <span><i class="bi bi-basket2-fill"></i> Bahan – Bahan dalam Resep</span>
                    <span id="item-count-label" style="color:var(--accent);font-weight:700"></span>
                </div>
                <div class="item-row-header">
                    <span>Nama Bahan</span><span>Jumlah</span><span>Satuan</span>
                    <span style="text-align:right">Total</span><span></span>
                </div>
                <div id="items-body"></div>
            </div>

            <button class="btn-add-item" id="btn-add-item" type="button">
                <i class="bi bi-plus-lg"></i> Tambah Bahan Lain
            </button>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Catatan</label>
                    <textarea id="resep-catatan" placeholder="Opsional: Cara pembuatan, tips khusus, dll…" rows="3"></textarea>
                </div>
            </div>
        </div><!-- /.modal-scrollable -->

        <!-- Footer selalu terlihat -->
        <div class="m-footer">
            <button class="btn-mc" id="btn-batal-resep" type="button">
                <i class="bi bi-x-circle"></i> Batal
            </button>
            <button class="btn-ms green" id="btn-submit-resep" type="button">
                <span class="btn-label"><i class="bi bi-check-circle-fill"></i> Simpan</span>
                <span class="btn-spin"></span>
            </button>
        </div>

    </div>
</div>

<!-- ════════════════════════════════════════════════
     MODAL: SHOW (Detail Resep)
════════════════════════════════════════════════ -->
<div class="resep-overlay" id="modal-show">
    <div class="resep-modal">

        <div class="modal-scrollable">
            <div class="m-head">
                <div class="m-ico blue"><i class="bi bi-book-fill"></i></div>
                <div>
                    <p class="m-title">Detail Resep</p>
                    <p class="m-sub">Informasi lengkap resep &amp; daftar bahan</p>
                </div>
                <div class="m-head-actions">
                    <button class="btn-toggle" id="btn-show-to-edit-head" type="button">
                        <i class="bi bi-pencil-fill"></i> Edit
                    </button>
                    <button class="btn-mc" id="btn-close-show" type="button" style="flex:none;padding:7px 13px;">
                        <i class="bi bi-x-lg"></i> Tutup
                    </button>
                </div>
            </div>

            <div class="summary-strip">
                <div class="strip-item">
                    <div class="strip-ico ic-b"><i class="bi bi-basket2-fill"></i></div>
                    <div class="strip-val" id="show-jumlah-bahan">0</div>
                    <div class="strip-lbl">Total Bahan</div>
                </div>
                <div class="strip-item">
                    <div class="strip-ico ic-g"><i class="bi bi-jar-fill"></i></div>
                    <div class="strip-val sm" id="show-nama-produk">-</div>
                    <div class="strip-lbl">Produk</div>
                </div>
                <div class="strip-item">
                    <div class="strip-ico ic-a"><i class="bi bi-bookmark-fill"></i></div>
                    <div class="strip-val sm" id="show-nama-resep">-</div>
                    <div class="strip-lbl">Nama Resep</div>
                </div>
            </div>

            <div class="section-card">
                <div class="section-card-head"><i class="bi bi-info-circle-fill"></i> Informasi Resep</div>
                <div class="section-card-body">
                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">Nama Resep</span>
                            <span class="info-value" id="show-info-nama">-</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Produk</span>
                            <span class="badge-blue" id="show-info-produk">-</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Jumlah Bahan</span>
                            <span class="badge-green" id="show-info-jml">-</span>
                        </div>
                    </div>
                    <div id="show-catatan-wrap" style="display:none;">
                        <hr class="m-divider">
                        <div class="info-label" style="margin-bottom:8px;">Catatan</div>
                        <div class="catatan-box" id="show-catatan-box"></div>
                    </div>
                </div>
            </div>

            <div class="section-card">
                <div class="section-card-head"><i class="bi bi-list-check"></i> Daftar Bahan</div>
                <div id="show-bahan-wrap">
                    <div style="text-align:center;padding:40px;color:var(--text-muted);">
                        <i class="bi bi-arrow-clockwise" style="font-size:2rem;display:block;margin-bottom:10px;animation:bspin 1s linear infinite;"></i>
                        <p style="font-size:13px;margin:0">Memuat data bahan...</p>
                    </div>
                </div>
            </div>
        </div><!-- /.modal-scrollable -->

        <div class="m-footer">
            <button class="btn-mc" id="btn-close-show2" type="button">
                <i class="bi bi-x-circle"></i> Tutup
            </button>
            <button class="btn-ms blue" id="btn-show-to-edit-foot" type="button">
                <span class="btn-label"><i class="bi bi-pencil-fill"></i> Edit Resep</span>
                <span class="btn-spin"></span>
            </button>
        </div>

    </div>
</div>

<!-- ════════════════════════════════════════════════
     MODAL: EDIT RESEP
════════════════════════════════════════════════ -->
<div class="resep-overlay" id="modal-edit">
    <div class="resep-modal">

        <div class="modal-scrollable">
            <div class="m-head">
                <div class="m-ico orange"><i class="bi bi-pencil-square"></i></div>
                <div>
                    <p class="m-title">Edit Resep</p>
                    <p class="m-sub">Perbarui informasi resep &amp; komposisi bahan</p>
                </div>
                <div class="m-head-actions">
                    <span class="change-pill" id="change-pill"><i class="bi bi-pencil-fill"></i> Ada perubahan</span>
                    <button class="btn-toggle" id="btn-edit-to-show-head" type="button">
                        <i class="bi bi-eye"></i> Lihat Detail
                    </button>
                    <button class="btn-mc" id="btn-close-edit" type="button" style="flex:none;padding:7px 13px;">
                        <i class="bi bi-x-lg"></i> Tutup
                    </button>
                </div>
            </div>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Nama Resep</label>
                    <input id="edit-nama" type="text" placeholder="Contoh: Resep Bumbu Rawon">
                    <div class="form-error" id="edit-err-nama"></div>
                </div>
            </div>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Produk</label>
                    <select id="edit-produk"><option value="">-- Pilih Produk --</option></select>
                    <div class="form-error" id="edit-err-produk"></div>
                </div>
            </div>

            <hr class="m-divider">

            <div class="items-section">
                <div class="items-head">
                    <span><i class="bi bi-basket2-fill"></i> Bahan – Bahan dalam Resep</span>
                    <span id="edit-item-count" style="color:var(--accent);font-weight:700"></span>
                </div>
                <div class="item-row-header">
                    <span>Nama Bahan</span><span>Jumlah</span><span>Satuan</span>
                    <span style="text-align:right">Total</span><span></span>
                </div>
                <div id="edit-items-body"></div>
            </div>

            <button class="btn-add-item" id="edit-btn-add-item" type="button">
                <i class="bi bi-plus-lg"></i> Tambah Bahan Lain
            </button>

            <div class="f-row full">
                <div class="f-grp">
                    <label>Catatan</label>
                    <textarea id="edit-catatan" placeholder="Opsional: Cara pembuatan, tips khusus, dll…" rows="3"></textarea>
                </div>
            </div>
        </div><!-- /.modal-scrollable -->

        <div class="m-footer">
            <button class="btn-mc" id="btn-close-edit2" type="button">
                <i class="bi bi-x-circle"></i> Batal
            </button>
            <button class="btn-ms orange" id="btn-submit-edit" type="button">
                <span class="btn-label"><i class="bi bi-floppy-fill"></i> Simpan</span>
                <span class="btn-spin"></span>
            </button>
        </div>

    </div>
</div>

<!-- ════════════════════════════════════════════════
     KONTEN UTAMA
════════════════════════════════════════════════ -->
<div class="resep-wrap">

    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert-ok"><i class="bi bi-check-circle-fill"></i> <?= session()->getFlashdata('success') ?></div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert-err"><i class="bi bi-exclamation-circle-fill"></i> <?= session()->getFlashdata('error') ?></div>
    <?php endif; ?>

    <div class="page-header">
        <div>
            <h1 class="page-title"><i class="bi bi-book-fill"></i> Daftar Resep</h1>
            <p class="page-sub">Kelola resep produk dengan bahan dan komposisi</p>
        </div>
        <div class="header-btns">
            <button class="btn-primary" id="btn-open-resep" type="button">
                <i class="bi bi-plus-lg"></i> Buat Resep Baru
            </button>
        </div>
    </div>

    <div class="card">
        <div class="card-head">
            <div class="card-title">
                <i class="bi bi-list-check" style="color:var(--accent)"></i> Daftar Resep
            </div>
            <span class="count-badge"><?= count($resep) ?> resep</span>
        </div>
        <div class="tbl-wrap">
            <?php if (!empty($resep)): ?>
                <table>
                    <thead>
                        <tr>
                            <th style="width:50px">#</th>
                            <th>Nama Resep</th>
                            <th>Produk</th>
                            <th class="text-center">Jumlah Bahan</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no = 1; foreach ($resep as $r): ?>
                            <tr>
                                <td class="td-center" style="color:var(--text-muted);font-size:12px"><?= $no++ ?></td>
                                <td style="font-weight:600"><?= esc($r['nama_resep']) ?></td>
                                <td>
                                    <?php if (!empty($r['nama_produk'])): ?>
                                        <span class="badge-blue"><i class="bi bi-box-seam"></i> <?= esc($r['nama_produk']) ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted);font-size:13px">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="td-center">
                                    <?php if (isset($r['jumlah_bahan']) && $r['jumlah_bahan'] > 0): ?>
                                        <span class="badge-green"><i class="bi bi-layers"></i> <?= $r['jumlah_bahan'] ?> bahan</span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted);font-size:13px">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="display:flex;gap:6px;flex-wrap:wrap;">
                                        <button type="button" class="btn-toggle"
                                                onclick="openModalShow(<?= (int)$r['id_resep'] ?>)">
                                            <i class="bi bi-eye"></i> Lihat
                                        </button>
                                        <button type="button" class="btn-toggle edit"
                                                onclick="openModalEdit(<?= (int)$r['id_resep'] ?>)">
                                            <i class="bi bi-pencil"></i> Edit
                                        </button>
                                        <button type="button" class="btn-toggle danger"
                                                onclick="deleteResep(<?= (int)$r['id_resep'] ?>)">
                                            <i class="bi bi-trash"></i> Hapus
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <i class="bi bi-inbox"></i>
                    <h5>Belum Ada Resep</h5>
                    <p>Mulai tambahkan resep produk Anda sekarang</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div><!-- /.resep-wrap -->

<?= $this->endSection() ?>

<?= $this->section('js') ?>
<script>
const RESEP_BASE = '<?= base_url() ?>';
let allProduk      = [];
let allBahan       = [];
let resepToastT;
let addItemIdx     = 0;
let editItemIdx    = 0;
let currentResepId = null;
let isDirty        = false;

const escHtml = s => String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const fmtN    = n => (parseFloat(n) || 0).toLocaleString('id-ID');

function getCsrf() {
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
}

/* ── Toast ──────────────────────────────────────── */
function showToast(msg, type = 'success') {
    const el = document.getElementById('resep-toast');
    document.getElementById('rt-ico').textContent = type === 'success' ? '✓' : '✕';
    document.getElementById('rt-msg').textContent = msg;
    el.className = 'show ' + type;
    clearTimeout(resepToastT);
    resepToastT = setTimeout(() => { el.className = ''; }, 3600);
}

/* ── Modal open/close ───────────────────────────── */
function openModal(id) {
    const el = document.getElementById(id);
    el.classList.add('visible');
    requestAnimationFrame(() => requestAnimationFrame(() => el.classList.add('shown')));
}
function closeModal(id) {
    const el = document.getElementById(id);
    el.classList.add('closing');
    el.classList.remove('shown');
    setTimeout(() => el.classList.remove('visible', 'closing'), 210);
}
// Klik di luar modal = tutup
document.querySelectorAll('.resep-overlay').forEach(el => {
    el.addEventListener('click', e => { if (e.target === el) closeModal(el.id); });
});

/* ── Ripple + button state ──────────────────────── */
document.addEventListener('click', e => {
    const btn = e.target.closest('.btn-ms');
    if (!btn || btn.disabled) return;
    const r = document.createElement('span');
    r.className = 'ripple';
    const rect = btn.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    r.style.cssText = `width:${size}px;height:${size}px;left:${e.clientX - rect.left - size/2}px;top:${e.clientY - rect.top - size/2}px`;
    btn.appendChild(r);
    setTimeout(() => r.remove(), 650);
});
function btnLoading(btn) { btn.disabled = true; btn.classList.add('loading'); }
function btnSuccess(btn) {
    btn.classList.remove('loading'); btn.classList.add('done');
    setTimeout(() => { btn.classList.remove('done'); btn.disabled = false; }, 950);
}
function btnError(btn) {
    btn.classList.remove('loading'); btn.disabled = false;
    btn.classList.add('shake');
    setTimeout(() => btn.classList.remove('shake'), 380);
}

/* ── Build select options ───────────────────────── */
function buildProdukOptions(targetId, selectedId = '') {
    const sel = document.getElementById(targetId);
    if (!sel) return;
    sel.innerHTML = '<option value="">-- Pilih Produk --</option>' +
        allProduk.map(p =>
            `<option value="${p.id}" ${String(p.id) === String(selectedId) ? 'selected' : ''}>${escHtml(p.nama)}</option>`
        ).join('');
}

function buildBahanOptions(selectedId = 0) {
    return '<option value="">-- Pilih Bahan --</option>' +
        allBahan.filter(b => b.status_bahan === 'aktif').map(b =>
            `<option value="${b.id_bahan}" data-satuan="${escHtml(b.satuan_bahan)}"
             ${String(b.id_bahan) === String(selectedId) ? 'selected' : ''}>${escHtml(b.nama_bahan)}</option>`
        ).join('');
}

/* ── Item row (tambah) ──────────────────────────── */
function addItemRow(data = {}) {
    addItemIdx++;
    const row = document.createElement('div');
    row.className = 'item-row';
    row.dataset.idx = addItemIdx;
    row.innerHTML = `
        <select class="item-bahan">${buildBahanOptions(data.id_bahan || 0)}</select>
        <input  class="item-jumlah" type="number" step="0.001" min="0.001" placeholder="0" value="${data.jumlah_bahan || ''}">
        <input  class="item-satuan" type="text" placeholder="Satuan" readonly value="">
        <div class="item-subtotal">—</div>
        <button class="btn-rm-item" type="button"><i class="bi bi-trash3-fill"></i></button>`;
    wireItemRow(row, 'items-body', 'item-count-label', false);
    document.getElementById('items-body').appendChild(row);
    // Set satuan dari data jika ada
    if (data.satuan_bahan) row.querySelector('.item-satuan').value = data.satuan_bahan;
    recalcRow(row);
    recalcTotalOf('items-body', 'item-count-label');
}

/* ── Item row (edit) ────────────────────────────── */
function addEditItemRow(data = {}) {
    editItemIdx++;
    const row = document.createElement('div');
    row.className = 'item-row';
    row.dataset.idx = editItemIdx;
    row.innerHTML = `
        <select class="item-bahan">${buildBahanOptions(data.id_bahan || 0)}</select>
        <input  class="item-jumlah" type="number" step="0.001" min="0.001" placeholder="0" value="${data.jumlah_bahan || ''}">
        <input  class="item-satuan" type="text" placeholder="Satuan" readonly value="">
        <div class="item-subtotal">—</div>
        <button class="btn-rm-item" type="button"><i class="bi bi-trash3-fill"></i></button>`;
    wireItemRow(row, 'edit-items-body', 'edit-item-count', true);
    document.getElementById('edit-items-body').appendChild(row);
    // Set satuan: dari data, atau dari option yang sudah selected
    if (data.satuan_bahan) {
        row.querySelector('.item-satuan').value = data.satuan_bahan;
    } else {
        const opt = row.querySelector('.item-bahan').selectedOptions[0];
        if (opt && opt.dataset.satuan) row.querySelector('.item-satuan').value = opt.dataset.satuan;
    }
    recalcRow(row);
    recalcTotalOf('edit-items-body', 'edit-item-count');
}

function wireItemRow(row, bodyId, countId, dirty) {
    const sel = row.querySelector('.item-bahan');
    const inp = row.querySelector('.item-jumlah');
    const sat = row.querySelector('.item-satuan');

    sel.addEventListener('change', function () {
        const opt = this.selectedOptions[0];
        sat.value = opt?.dataset.satuan || '';
        recalcRow(row); recalcTotalOf(bodyId, countId);
        if (dirty) markDirty();
    });
    inp.addEventListener('input', () => {
        recalcRow(row); recalcTotalOf(bodyId, countId);
        if (dirty) markDirty();
    });
    row.querySelector('.btn-rm-item').addEventListener('click', () => {
        row.remove(); recalcTotalOf(bodyId, countId);
        if (dirty) markDirty();
    });
}

function recalcRow(row) {
    const j = parseFloat(row.querySelector('.item-jumlah')?.value) || 0;
    row.querySelector('.item-subtotal').textContent = j > 0 ? fmtN(j) : '—';
}
function recalcTotalOf(bodyId, countId) {
    const n = document.querySelectorAll(`#${bodyId} .item-row`).length;
    const el = document.getElementById(countId);
    if (el) el.textContent = n ? `${n} bahan` : '';
}

/* ── Error helpers ──────────────────────────────── */
function clearErrors(...ids) {
    ids.forEach(id => {
        const el = document.getElementById(id);
        if (el) { el.textContent = ''; el.classList.remove('show'); }
    });
}
function showError(id, msg) {
    const el = document.getElementById(id);
    if (el) { el.textContent = msg; el.classList.add('show'); }
}

/* ══════════════════════════════════════════════════
   MODAL TAMBAH
══════════════════════════════════════════════════ */
document.getElementById('btn-open-resep').addEventListener('click', openModalResep);
document.getElementById('btn-batal-resep').addEventListener('click', () => closeModal('modal-resep'));

function openModalResep() {
    if (allBahan.length === 0) {
        showToast('Sedang memuat data bahan, silakan tunggu...', 'success');
        setTimeout(openModalResep, 600);
        return;
    }
    document.getElementById('resep-nama').value    = '';
    document.getElementById('resep-catatan').value = '';
    clearErrors('err-nama', 'err-produk');
    addItemIdx = 0;
    document.getElementById('items-body').innerHTML = '';
    buildProdukOptions('resep-produk');
    addItemRow();
    openModal('modal-resep');
}

document.getElementById('btn-add-item').addEventListener('click', () => addItemRow());

document.getElementById('btn-submit-resep').addEventListener('click', function () {
    submitResep(this);
});

async function submitResep(btn) {
    clearErrors('err-nama', 'err-produk');
    const nama     = document.getElementById('resep-nama').value.trim();
    const idProduk = document.getElementById('resep-produk').value;
    const items    = [];
    let   hasErr   = false;

    if (!nama)     { showError('err-nama',   'Nama resep harus diisi'); hasErr = true; }
    if (!idProduk) { showError('err-produk', 'Pilih produk untuk resep ini'); hasErr = true; }

    document.querySelectorAll('#items-body .item-row').forEach(row => {
        const id_bahan = row.querySelector('.item-bahan')?.value;
        const jumlah   = parseFloat(row.querySelector('.item-jumlah')?.value) || 0;
        const selEl    = row.querySelector('.item-bahan');
        const jEl      = row.querySelector('.item-jumlah');
        let ok = true;
        if (!id_bahan)  { selEl.classList.add('invalid'); ok = false; }
        else             selEl.classList.remove('invalid');
        if (jumlah <= 0) { jEl.classList.add('invalid'); ok = false; }
        else              jEl.classList.remove('invalid');
        if (!ok) { hasErr = true; return; }
        items.push({ id_bahan, jumlah_bahan: jumlah });
    });

    if (hasErr)          { showToast('Lengkapi semua field yang diperlukan.', 'error'); return; }
    if (!items.length)   { showToast('Tambahkan minimal 1 bahan ke resep.', 'error'); return; }

    btnLoading(btn);
    try {
        const r   = await fetch(RESEP_BASE + '/resep/store', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': getCsrf()
            },
            body: JSON.stringify({
                nama_resep:    nama,
                id_produk:     idProduk,
                catatan_resep: document.getElementById('resep-catatan').value,
                items
            })
        });
        const res = await r.json();
        if (res.success) {
            btnSuccess(btn);
            setTimeout(() => closeModal('modal-resep'), 300);
            setTimeout(() => {
                showToast(res.message || 'Resep berhasil disimpan');
                setTimeout(() => window.location.reload(), 500);
            }, 550);
        } else {
            btnError(btn);
            showToast(res.error || 'Terjadi kesalahan', 'error');
        }
    } catch (e) {
        btnError(btn);
        showToast('Koneksi gagal: ' + e.message, 'error');
    }
}

/* ══════════════════════════════════════════════════
   MODAL SHOW
══════════════════════════════════════════════════ */
async function openModalShow(id) {
    currentResepId = id;

    // Bind tombol
    const goEdit = () => { closeModal('modal-show'); setTimeout(() => openModalEdit(id), 240); };
    document.getElementById('btn-show-to-edit-head').onclick  = goEdit;
    document.getElementById('btn-show-to-edit-foot').onclick  = goEdit;
    document.getElementById('btn-close-show').onclick  = () => closeModal('modal-show');
    document.getElementById('btn-close-show2').onclick = () => closeModal('modal-show');

    // Reset isi
    ['show-jumlah-bahan','show-nama-produk','show-nama-resep','show-info-nama'].forEach(i => {
        document.getElementById(i).textContent = '…';
    });
    document.getElementById('show-info-produk').textContent = '…';
    document.getElementById('show-info-jml').textContent    = '…';
    document.getElementById('show-catatan-wrap').style.display = 'none';
    document.getElementById('show-bahan-wrap').innerHTML = `
        <div style="text-align:center;padding:40px;color:var(--text-muted);">
            <i class="bi bi-arrow-clockwise" style="font-size:2rem;display:block;margin-bottom:10px;animation:bspin 1s linear infinite;"></i>
            <p style="font-size:13px;margin:0">Memuat data bahan...</p>
        </div>`;

    openModal('modal-show');

    try {
        const r   = await fetch(`${RESEP_BASE}/resep/detail/${id}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const res = await r.json();
        if (!res.success) { showToast(res.error || 'Gagal memuat detail', 'error'); return; }

        const d     = res.data;
        const bahan = d.items || [];
        const n     = bahan.length;

        document.getElementById('show-jumlah-bahan').textContent = n;
        document.getElementById('show-nama-produk').textContent  = d.nama_produk || '-';
        document.getElementById('show-nama-resep').textContent   = d.nama_resep  || '-';
        document.getElementById('show-info-nama').textContent    = d.nama_resep  || '-';
        document.getElementById('show-info-produk').innerHTML    = `<i class="bi bi-box-seam"></i> ${escHtml(d.nama_produk || '-')}`;
        document.getElementById('show-info-jml').innerHTML       = `<i class="bi bi-layers"></i> ${n} bahan`;

        if (d.catatan_resep) {
            document.getElementById('show-catatan-box').textContent    = d.catatan_resep;
            document.getElementById('show-catatan-wrap').style.display = 'block';
        }

        if (n === 0) {
            document.getElementById('show-bahan-wrap').innerHTML = `
                <div style="text-align:center;padding:40px;color:var(--text-muted);">
                    <i class="bi bi-inbox" style="font-size:2.5rem;display:block;margin-bottom:10px;opacity:.2;"></i>
                    <p style="font-size:13px;margin:0">Tidak ada bahan dalam resep ini</p>
                </div>`;
        } else {
            const rows = bahan.map((b, i) => `
                <tr>
                    <td class="no-col">${i + 1}</td>
                    <td><span class="bahan-ico"><i class="bi bi-droplet-half"></i></span>${escHtml(b.nama_bahan || '-')}</td>
                    <td class="jumlah-col">${Number(b.jumlah_bahan || 0).toLocaleString('id-ID', {minimumFractionDigits:2, maximumFractionDigits:2})}</td>
                    <td><span class="badge-amber">${escHtml(b.satuan_bahan || '-')}</span></td>
                </tr>`).join('');
            document.getElementById('show-bahan-wrap').innerHTML = `
                <table class="bahan-table">
                    <thead><tr>
                        <th class="no-col">#</th>
                        <th>Nama Bahan</th>
                        <th>Jumlah</th>
                        <th>Satuan</th>
                    </tr></thead>
                    <tbody>${rows}</tbody>
                </table>`;
        }
    } catch (e) {
        showToast('Gagal memuat detail: ' + e.message, 'error');
    }
}

/* ══════════════════════════════════════════════════
   MODAL EDIT
══════════════════════════════════════════════════ */
function markDirty() {
    isDirty = true;
    document.getElementById('change-pill').classList.add('show');
}
document.getElementById('edit-nama').addEventListener('input', markDirty);
document.getElementById('edit-catatan').addEventListener('input', markDirty);
document.getElementById('edit-produk').addEventListener('change', markDirty);
document.getElementById('edit-btn-add-item').addEventListener('click', () => {
    addEditItemRow(); markDirty();
});

async function openModalEdit(id) {
    currentResepId = id;
    isDirty        = false;
    document.getElementById('change-pill').classList.remove('show');

    // Bind tombol
    document.getElementById('btn-edit-to-show-head').onclick = () => { closeModal('modal-edit'); setTimeout(() => openModalShow(id), 240); };
    document.getElementById('btn-close-edit').onclick  = () => closeModal('modal-edit');
    document.getElementById('btn-close-edit2').onclick = () => closeModal('modal-edit');

    // Reset form
    document.getElementById('edit-nama').value    = '';
    document.getElementById('edit-catatan').value = '';
    document.getElementById('edit-items-body').innerHTML = '';
    editItemIdx = 0;
    buildProdukOptions('edit-produk');
    clearErrors('edit-err-nama', 'edit-err-produk');

    openModal('modal-edit');

    try {
        const r   = await fetch(`${RESEP_BASE}/resep/detail/${id}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const res = await r.json();
        if (!res.success) { showToast(res.error || 'Gagal memuat data edit', 'error'); return; }

        const d = res.data;
        document.getElementById('edit-nama').value    = d.nama_resep    || '';
        document.getElementById('edit-catatan').value = d.catatan_resep || '';
        buildProdukOptions('edit-produk', d.id_produk);

        const bahan = d.items || [];
        if (bahan.length > 0) bahan.forEach(b => addEditItemRow(b));
        else addEditItemRow();
    } catch (e) {
        showToast('Gagal memuat data: ' + e.message, 'error');
    }
}

document.getElementById('btn-submit-edit').addEventListener('click', function () {
    submitEdit(this);
});

async function submitEdit(btn) {
    clearErrors('edit-err-nama', 'edit-err-produk');
    const nama     = document.getElementById('edit-nama').value.trim();
    const idProduk = document.getElementById('edit-produk').value;
    const items    = [];
    let   hasErr   = false;

    if (!nama)     { showError('edit-err-nama',   'Nama resep harus diisi'); hasErr = true; }
    if (!idProduk) { showError('edit-err-produk', 'Pilih produk untuk resep ini'); hasErr = true; }

    document.querySelectorAll('#edit-items-body .item-row').forEach(row => {
        const id_bahan = row.querySelector('.item-bahan')?.value;
        const jumlah   = parseFloat(row.querySelector('.item-jumlah')?.value) || 0;
        const selEl    = row.querySelector('.item-bahan');
        const jEl      = row.querySelector('.item-jumlah');
        let ok = true;
        if (!id_bahan)  { selEl.classList.add('invalid'); ok = false; }
        else              selEl.classList.remove('invalid');
        if (jumlah <= 0) { jEl.classList.add('invalid'); ok = false; }
        else              jEl.classList.remove('invalid');
        if (!ok) { hasErr = true; return; }
        items.push({ id_bahan, jumlah_bahan: jumlah });
    });

    if (hasErr)        { showToast('Lengkapi semua field yang diperlukan.', 'error'); return; }
    if (!items.length) { showToast('Tambahkan minimal 1 bahan ke resep.', 'error'); return; }

    btnLoading(btn);
    try {
        const r   = await fetch(`${RESEP_BASE}/resep/update/${currentResepId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': getCsrf()
            },
            body: JSON.stringify({
                nama_resep:    nama,
                id_produk:     idProduk,
                catatan_resep: document.getElementById('edit-catatan').value,
                items
            })
        });
        const res = await r.json();
        if (res.success) {
            btnSuccess(btn);
            isDirty = false;
            document.getElementById('change-pill').classList.remove('show');
            showToast(res.message || 'Resep berhasil diperbarui');
            setTimeout(() => { closeModal('modal-edit'); openModalShow(currentResepId); }, 800);
        } else {
            btnError(btn);
            showToast(res.error || 'Terjadi kesalahan', 'error');
        }
    } catch (e) {
        btnError(btn);
        showToast('Koneksi gagal: ' + e.message, 'error');
    }
}

/* ══════════════════════════════════════════════════
   DELETE
══════════════════════════════════════════════════ */
async function deleteResep(id) {
    if (!confirm('Yakin ingin menghapus resep ini? Tindakan ini tidak bisa dibatalkan.')) return;
    try {
        const r   = await fetch(`${RESEP_BASE}/resep/delete/${id}`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': getCsrf()
            }
        });
        const res = await r.json();
        if (res.success) {
            showToast(res.message || 'Resep berhasil dihapus');
            setTimeout(() => window.location.reload(), 700);
        } else {
            showToast(res.error || 'Terjadi kesalahan', 'error');
        }
    } catch (e) {
        showToast('Koneksi gagal: ' + e.message, 'error');
    }
}

/* ══════════════════════════════════════════════════
   LOAD MASTER DATA (produk + bahan)
══════════════════════════════════════════════════ */
async function loadData() {
    try {
        const rp = await fetch(RESEP_BASE + '/produk/data', {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        if (rp.ok) {
            const dp = await rp.json();
            if (dp.success && dp.list) {
                allProduk = dp.list;
                buildProdukOptions('resep-produk');
            }
        }
    } catch (e) { console.error('Gagal load produk:', e); }

    try {
        const rb = await fetch(RESEP_BASE + '/bahan/data', {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        if (rb.ok) {
            const db = await rb.json();
            allBahan = db.list || db.data || [];
        }
    } catch (e) { console.error('Gagal load bahan:', e); }
}

loadData();
</script>
<?= $this->endSection() ?>