/* ============================================================
   TernakPro — versi tanpa build (langsung jalan di browser)
   React, ReactDOM, dan Babel dimuat dari CDN pada index.html.
   Helper API & hook usePersistentState digabung di bagian atas file ini.
   ============================================================ */
const { useState, useEffect, useCallback, useRef } = React;

/* ============================================================
   LAPISAN DATA — helper API + hook penyimpanan (digabung di sini
   agar hanya ada SATU script Babel, mencegah deklarasi ganda).
   ============================================================ */
const API_BASE = "api/";   // lokasi backend PHP, relatif terhadap halaman ini

async function apiList(table) {
  const res = await fetch(`${API_BASE}?table=${encodeURIComponent(table)}`);
  if (!res.ok) throw new Error(`GET ${table} gagal (${res.status})`);
  return res.json();
}
async function apiBulkSave(table, rows) {
  const res = await fetch(`${API_BASE}?table=${encodeURIComponent(table)}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(rows),
  });
  if (!res.ok) throw new Error(`PUT ${table} gagal (${res.status})`);
  return res.json();
}

// Pengganti useState yang otomatis tersimpan ke MySQL:
// 1) mount -> ambil data server; jika kosong -> seed dari data bawaan.
// 2) setiap berubah -> kirim seluruh array ke server (debounce 700ms).
function usePersistentState(table, initial) {
  const [data, setData] = useState(initial);
  const [loaded, setLoaded] = useState(false);
  const skipNextSave = useRef(true);
  const timer = useRef(null);

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const rows = await apiList(table);
        if (!alive) return;
        if (Array.isArray(rows) && rows.length > 0) {
          skipNextSave.current = true; setData(rows);
        } else {
          await apiBulkSave(table, initial);          // seed run pertama
          skipNextSave.current = true; setData(initial);
        }
      } catch (e) {
        console.error(`Gagal memuat '${table}':`, e.message); // offline: pakai initial
      } finally {
        if (alive) setLoaded(true);
      }
    })();
    return () => { alive = false; };
  }, []);

  useEffect(() => {
    if (skipNextSave.current) { skipNextSave.current = false; return; }
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      apiBulkSave(table, data).catch((e) =>
        console.error(`Gagal menyimpan '${table}':`, e.message));
    }, 700);
    return () => { if (timer.current) clearTimeout(timer.current); };
  }, [data]);

  return [data, setData, loaded];
}

/* ================================================================
   ERROR BOUNDARY — Cegah app crash total karena 1 komponen error
================================================================ */
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error("TernakPro Error:", error, info);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{padding:24,background:"#07090e",minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"}}>
          <div style={{background:"#ef444415",border:"2px solid #ef444440",borderRadius:16,padding:32,maxWidth:500,textAlign:"center"}}>
            <div style={{fontSize:32,marginBottom:12}}>⚠️</div>
            <div style={{color:"#ef4444",fontSize:18,fontWeight:800,marginBottom:8}}>Terjadi Error</div>
            <div style={{color:"#9097a8",fontSize:13,marginBottom:16,fontFamily:"monospace",background:"#0f1118",padding:12,borderRadius:8,textAlign:"left",maxHeight:120,overflow:"auto"}}>
              {String(this.state.error?.message || this.state.error || "Unknown error")}
            </div>
            <button onClick={()=>this.setState({hasError:false,error:null})}
              style={{background:"#ef444418",border:"1px solid #ef444440",borderRadius:9,padding:"10px 24px",cursor:"pointer",color:"#ef4444",fontWeight:700,fontSize:14,marginRight:8}}>
              🔄 Coba Lagi
            </button>
            <button onClick={()=>window.location.reload()}
              style={{background:"#60a5fa18",border:"1px solid #60a5fa40",borderRadius:9,padding:"10px 24px",cursor:"pointer",color:"#60a5fa",fontWeight:700,fontSize:14}}>
              🔃 Reload
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

/* ===== WARNA TEMA ===== */
const C = {
  bg: "#07090e", sidebar: "#0a0c16", card: "#0f1118",
  border: "#1c1e2b", border2: "#252535", text: "#e2e4f0",
  muted: "#9097a8", dim: "#555a6a", subtle: "#1a1d28",
  sapi: "#f5c842", domba: "#a3e635", sell: "#22c55e",
  buy: "#f59e0b", health: "#ec4899", breed: "#a855f7",
  expense: "#ef4444", report: "#8b5cf6", info: "#3b82f6",
};

/* ================================================================
   DATA RAS SAPI — Karakteristik, Asal, Keunggulan
================================================================ */
const RAS_SAPI = {
  // ── SAPI IMPOR / PERSILANGAN ──
  "Simental": {
    asal:"Swiss (Swiss-Simmental)", tipe:"Potong & Perah Dwi Guna", warna:"Kuning-Keemasan dengan bercak putih",
    bbDewasa:{jantan:"800–1.100 kg",betina:"600–750 kg"}, adg:"0.8–1.5 kg/hari (feedlot intensif)",
    keunggulan:["Pertumbuhan sangat cepat — ADG tertinggi di antara ras impor","Karkas besar, rendemen 52–58%","Adaptasi baik di dataran tinggi Jawa","Populasi terbesar sapi impor di Indonesia"],
    kekurangan:["Sensitif panas — perlu ventilasi kandang baik","Kebutuhan pakan tinggi — FCR 6–7","Harga bibit mahal"],
    harga:"Rp 20–45 juta/ekor bakalan (2025)", popularitas:"⭐⭐⭐⭐⭐ — Paling populer feedlot Indonesia",
    catatan:"SimPO (Simental × PO) = ras persilangan paling banyak di Jawa. Adaptasi lebih baik dari Simental murni",
  },
  "Limousin": {
    asal:"Prancis (Limousin)", tipe:"Sapi Potong Premium", warna:"Merah-Coklat Keemasan",
    bbDewasa:{jantan:"900–1.100 kg",betina:"600–700 kg"}, adg:"0.9–1.4 kg/hari",
    keunggulan:["Kualitas daging premium — lemak marbling rendah","Rendemen karkas tinggi 55–60%","Masa hidup panjang","Frame besar — bobot potong ideal 500–600 kg"],
    kekurangan:["Pertumbuhan sedikit lebih lambat dari Simental","Kurang toleran suhu panas ekstrem","Harga bibit mahal"],
    harga:"Rp 22–50 juta/ekor (2025)", popularitas:"⭐⭐⭐⭐⭐ — Runner-up setelah Simental",
    catatan:"LimPO (Limousin × PO) populer di Jabar & Jateng. Daging Limousin diekspor ke Malaysia & Timur Tengah",
  },
  "Angus": {
    asal:"Skotlandia (Aberdeen Angus)", tipe:"Sapi Potong Premium Dunia", warna:"Hitam pekat (Black Angus) atau Merah (Red Angus)",
    bbDewasa:{jantan:"750–1.000 kg",betina:"500–600 kg"}, adg:"0.8–1.2 kg/hari",
    keunggulan:["Marbling (lemak intramuskular) terbaik dunia — steak grade A","Temperamen jinak","Fertilitas betina tinggi","Tahan berbagai iklim"],
    kekurangan:["Kurang populer di Indonesia — lebih banyak di Australia/NZ","Harga bibit sangat mahal (import)","Adaptasi tropis perlu waktu"],
    harga:"Rp 35–80 juta/ekor impor (2025)", popularitas:"⭐⭐⭐ — Premium, belum umum peternak rakyat",
    catatan:"Wagyu × Angus = Japanese premium beef. Dipakai Santori & GGL untuk produk beef premium Indonesia",
  },
  "Brahman": {
    asal:"India → Amerika Serikat (Bos indicus)", tipe:"Sapi Potong Tropis", warna:"Abu-Abu atau Merah, punuk besar",
    bbDewasa:{jantan:"700–900 kg",betina:"450–550 kg"}, adg:"0.6–1.1 kg/hari",
    keunggulan:["Tahan panas & caplak — ideal daerah tropis","Efisien pakan kualitas rendah","Daya tahan parasit sangat baik","Banyak dipakai di peternakan ekstensif Sumatra & Kalimantan"],
    kekurangan:["Kualitas daging di bawah Simental/Limousin","ADG lebih rendah di kandang intensif"],
    harga:"Rp 15–30 juta/ekor (2025)", popularitas:"⭐⭐⭐⭐ — Sangat populer dataran rendah tropis",
    catatan:"BrahmanCross (Brahman × sapi lokal) banyak diternakkan di Sumatra, Kalimantan, Sulawesi",
  },
  "Wagyu (Kobe)": {
    asal:"Jepang (Wa = Jepang, Gyu = Sapi)", tipe:"Sapi Beef Premium Tertinggi Dunia", warna:"Hitam (Japanese Black — paling umum)",
    bbDewasa:{jantan:"700–900 kg",betina:"450–550 kg"}, adg:"0.5–0.8 kg/hari (sengaja lambat untuk marbling)",
    keunggulan:["Marbling lemak intramuskular tertinggi — BMS (Beef Marbling Score) 5–12","Harga jual daging Rp 500.000–3.000.000/kg","Program feedlot khusus 300–600 hari","Pasar ekspor sangat premium"],
    kekurangan:["Sangat mahal — bibit F1 Rp 50–150 juta","Butuh pakan khusus (jagung + jerami jepang)","Masa pemeliharaan 2–3 tahun","Pasar lokal masih kecil"],
    harga:"Rp 50–150 juta/ekor F1 Wagyu (2025)", popularitas:"⭐⭐ — Niche premium, bukan untuk peternak rakyat",
    catatan:"Santori (Japfa) & beberapa farm premium sudah mulai Wagyu di Indonesia. Potensial untuk HORECA hotel bintang 5",
  },
  // ── SAPI LOKAL INDONESIA ──
  "Sapi Bali": {
    asal:"Bali, Indonesia (Bos sondaicus/javanicus)", tipe:"Sapi Potong Lokal Unggul", warna:"Merah bata (betina) / Hitam (jantan dewasa), ada garis hitam di punggung",
    bbDewasa:{jantan:"300–450 kg",betina:"200–300 kg"}, adg:"0.3–0.6 kg/hari",
    keunggulan:["Adaptasi sangat baik di semua wilayah Indonesia","Tahan penyakit & parasit lokal","Fertilitas tinggi — beranak tiap 12–14 bulan","Kualitas daging baik — serat halus, rendemen 52–56%","Pakan hijauan lokal cukup tanpa konsentrat mahal"],
    kekurangan:["Bobot kecil — tidak cocok feedlot intensif","Sensitif Penyakit Jembrana (endemik Bali)","Pertumbuhan lambat vs sapi impor"],
    harga:"Rp 8–18 juta/ekor (2025)", popularitas:"⭐⭐⭐⭐⭐ — Populasi terbesar sapi lokal Indonesia",
    catatan:"Tersebar luas di Bali, NTB, NTT, Sulawesi. Ekspor hidup ke Malaysia, Brunei. Sapi nasional yang dilindungi pemerintah",
  },
  "Sapi Madura": {
    asal:"Pulau Madura, Jawa Timur (Bos indicus × Bos javanicus)", tipe:"Sapi Potong & Kerapan", warna:"Merah-Coklat, punuk kecil, tanduk melengkung khas",
    bbDewasa:{jantan:"250–350 kg",betina:"150–250 kg"}, adg:"0.2–0.5 kg/hari",
    keunggulan:["Tahan kekeringan & pakan miskin","Nilai budaya tinggi — sapi kerapan (karapan sapi)","Adaptasi sempurna iklim Madura yang panas","Fertilitas cukup baik"],
    kekurangan:["Bobot sangat kecil — tidak ekonomis untuk feedlot","Pertumbuhan sangat lambat","Populasi menurun karena tergeser sapi impor"],
    harga:"Rp 6–15 juta/ekor (kerapan berkualitas bisa ratusan juta)", popularitas:"⭐⭐⭐ — Khas Madura, nilainya budaya & ekonomi",
    catatan:"Sapi Kerapan = simbol budaya Madura. Kontes Karapan Sapi April–Oktober, pemenang senilai Rp 100 juta+. Dilindungi Perda Madura",
  },
  "PO (Peranakan Ongole)": {
    asal:"India → Jawa (persilangan Ongole × Jawa)", tipe:"Sapi Potong Lokal Dominan Jawa", warna:"Putih keabu-abuan, punuk besar, telinga lebar menggantung",
    bbDewasa:{jantan:"400–600 kg",betina:"280–400 kg"}, adg:"0.4–0.8 kg/hari",
    keunggulan:["Populasi terbesar di Jawa Tengah & Jawa Timur","Adaptasi sangat baik iklim Jawa","Sering disilangkan dengan Simental (SimPO) & Limousin (LimPO)","Tenaga kerja — dahulu sebagai sapi pekerja sawah","Tahan panas & penyakit lokal"],
    kekurangan:["Bobot sedang — kalah jauh dari Simental/Limousin","ADG rendah tanpa konsentrat intensif"],
    harga:"Rp 10–22 juta/ekor (2025)", popularitas:"⭐⭐⭐⭐⭐ — Paling banyak di Jawa",
    catatan:"SimPO & LimPO = sapi persilangan paling populer Indonesia. Rumpun PO murni mulai langka — dilindungi sebagai plasma nutfah nasional",
  },
  "Sapi Pasundan": {
    asal:"Jawa Barat (plasma nutfah asli Jabar)", tipe:"Sapi Potong Lokal Jabar", warna:"Coklat Kehitaman, ada garis hitam di punggung (mirip Bali)",
    bbDewasa:{jantan:"250–380 kg",betina:"170–270 kg"}, adg:"0.25–0.5 kg/hari",
    keunggulan:["Adaptasi sempurna iklim pegunungan Jabar","Tahan pakan kasar & miskin","Fertilitas baik","Cita rasa daging lezat — serat halus khas"],
    kekurangan:["Bobot kecil","Populasi sangat sedikit — hampir punah","Kurang dikenal peternak komersial"],
    harga:"Rp 8–16 juta/ekor", popularitas:"⭐⭐ — Langka, dilindungi pemerintah Jabar",
    catatan:"SK Mentan 2014 — Sapi Pasundan ditetapkan sebagai Rumpun Sapi Lokal Indonesia. Konservasi di BPTU HPT Ciamis & Tasikmalaya",
  },
  "Sapi Aceh": {
    asal:"Aceh (Bos indicus, keturunan sapi India kuno)", tipe:"Sapi Potong & Kerja Lokal Aceh", warna:"Hitam atau Coklat kehitaman, bertubuh kecil-sedang",
    bbDewasa:{jantan:"200–350 kg",betina:"150–250 kg"}, adg:"0.2–0.5 kg/hari",
    keunggulan:["Adaptasi sempurna kondisi Aceh — tropis basah","Tahan penyakit lokal","Populasi >400.000 ekor — terbesar di Sumatera","Menjadi sapi kurban unggulan di Aceh & Sumatera"],
    kekurangan:["Bobot kecil","Pertumbuhan lambat","Kurang tepat untuk feedlot intensif"],
    harga:"Rp 8–20 juta/ekor", popularitas:"⭐⭐⭐⭐ — Dominan di Aceh",
    catatan:"SK Mentan 2011 — Rumpun Sapi Aceh ditetapkan sebagai rumpun lokal. Penting untuk ketahanan pangan Aceh & ekspor ke Malaysia",
  },
  "Sapi Pesisir (Sumbar)": {
    asal:"Sumatera Barat — pantai barat Sumatera", tipe:"Sapi Mini Lokal Sumbar", warna:"Coklat Kehitaman, sangat kecil",
    bbDewasa:{jantan:"150–200 kg",betina:"100–150 kg"}, adg:"0.15–0.35 kg/hari",
    keunggulan:["Terkecil di Indonesia — unik dan langka","Adaptasi sempurna padang alang-alang","Tahan panas ekstrem pantai","Niche market — kolektor & konservasi"],
    kekurangan:["Bobot sangat kecil — tidak ekonomis produksi daging","Pertumbuhan sangat lambat","Populasi sangat terbatas"],
    harga:"Rp 3–8 juta/ekor", popularitas:"⭐⭐ — Langka, nilai konservasi tinggi",
    catatan:"Terancam punah — < 5.000 ekor tersisa. SK Mentan 2011. Penelitian di Universitas Andalas Padang",
  },
  "Sapi Jabres (Jateng)": {
    asal:"Jawa Tengah (Bantarbolang-Brebes)", tipe:"Sapi Potong Lokal Jateng", warna:"Kuning Kecoklatan, ada varian putih",
    bbDewasa:{jantan:"300–450 kg",betina:"200–300 kg"}, adg:"0.3–0.6 kg/hari",
    keunggulan:["Adaptasi sangat baik dataran rendah Jateng","Tahan pakan lokal","Fertilitas baik","Lebih besar dari Bali — potensial untuk penggemukan lokal"],
    kekurangan:["Kurang dikenal di luar Jawa Tengah","Harga lebih murah dari sapi impor"],
    harga:"Rp 9–18 juta/ekor", popularitas:"⭐⭐⭐ — Lokal Jateng",
    catatan:"Jabres = Jawa-Brebes. Pengembangan oleh Dinas Peternakan Jateng & Universitas Jenderal Soedirman",
  },
  "FH Afkir": {
    asal:"Frisien Holland → Belanda (Bos taurus)", tipe:"Sapi Perah Afkir untuk Potong", warna:"Hitam-Putih khas (Holstein)",
    bbDewasa:{jantan:"700–900 kg",betina:"500–700 kg"}, adg:"0.5–0.9 kg/hari (penggemukan afkir)",
    keunggulan:["Bobot besar — karkas > sapi lokal","Murah — harga afkir Rp 15–25 juta","Cocok untuk disembelih setelah masa produktif habis","Populasi banyak di sentra susu (Lembang, Batu, Boyolali)"],
    kekurangan:["Kualitas daging kurang premium — lebih banyak lemak","Perlu adaptasi pakan untuk penggemukan","Bukan sapi potong murni"],
    harga:"Rp 15–28 juta/ekor afkir", popularitas:"⭐⭐⭐⭐ — Sumber daging sapi perah yang ekonomis",
    catatan:"FH Afkir banyak dipotong di RPH Jabar & Jateng dari peternakan susu Lembang & Batu. Daging umumnya untuk bakso & olahan",
  },
  "Sapi Perah FH": {
    asal:"Frisien Holland — Belanda", tipe:"Sapi Perah Unggulan Dunia", warna:"Hitam-Putih Holstein khas",
    bbDewasa:{jantan:"800–1.000 kg",betina:"550–700 kg"}, produksiSusu:"15–35 liter/hari (puncak laktasi)",
    keunggulan:["Produksi susu tertinggi","Laktasi 305 hari/tahun","Adaptasi baik di dataran tinggi Jabar (Lembang, Pangalengan)","Harga susu Rp 5.500–7.500/liter dari Greenfields/Indolakto"],
    kekurangan:["Tidak tahan panas — butuh kandang sejuk","Kebutuhan pakan konsentrat sangat tinggi","Investasi awal besar","Sensitif penyakit (mastitis, ketosis)"],
    harga:"Rp 25–60 juta/ekor (2025)", popularitas:"⭐⭐⭐⭐ — Dominan di peternakan susu Jabar",
    catatan:"KPBS Pangalengan, KUD Cikaret, Greenfields Malang = sentra sapi perah FH Indonesia. Susu FH = 95% pasokan susu segar nasional",
  },
};

const JADWAL_VAKSIN_BROILER = [
  {hari:1,  vaksin:"ND Clone 45 + IB H120",  cara:"Tetes mata",    dosis:"1 tetes/ekor",  catatan:"Segera saat chick-in"},
  {hari:10, vaksin:"Gumboro",                cara:"Air minum",     dosis:"1 ampul/1000",  catatan:"Berikan pagi hari sebelum makan"},
  {hari:18, vaksin:"ND Lasota",              cara:"Spray/tetes",   dosis:"1 tetes/ekor",  catatan:"Booster ND — penting!"},
  {hari:21, vaksin:"IB Booster",             cara:"Air minum",     dosis:"1 ampul/1000",  catatan:"Opsional jika serangan IB tinggi"},
];
const JADWAL_VAKSIN_LAYER = [
  {minggu:1,  vaksin:"ND+IB Primer",          cara:"Tetes mata",   dosis:"1 tetes",       catatan:"Hari pertama"},
  {minggu:2,  vaksin:"Gumboro",               cara:"Air minum",    dosis:"",              catatan:""},
  {minggu:4,  vaksin:"ND Lasota Booster",     cara:"Spray",        dosis:"",              catatan:""},
  {minggu:8,  vaksin:"ND+IB+AI H5N1",        cara:"Injeksi IM",   dosis:"0.5ml/ekor",    catatan:"AI WAJIB untuk layer komersial"},
  {minggu:12, vaksin:"EDS + ND Oil",          cara:"Injeksi SC",   dosis:"0.5ml/ekor",    catatan:"Sebelum puncak produksi"},
  {minggu:16, vaksin:"AI H5N1 Booster",       cara:"Injeksi IM",   dosis:"0.5ml/ekor",    catatan:"4 minggu sebelum lay"},
  {minggu:44, vaksin:"ND+IB+AI Booster",      cara:"Injeksi",      dosis:"0.5ml/ekor",    catatan:"Mid-lay booster"},
];
const JADWAL_VAKSIN_SAPI = [
  {bulan:0,   vaksin:"Anthrax (daerah enzootik)", cara:"Subkutan",  dosis:"1ml/ekor",     catatan:"Wajib daerah tertentu"},
  {bulan:1,   vaksin:"SE (Septicemia Epizootic)",  cara:"Subkutan",  dosis:"2ml/ekor",     catatan:"Sapi impor/feedlot"},
  {bulan:6,   vaksin:"PMK (wajib pemerintah)",     cara:"Subkutan",  dosis:"2ml/ekor",     catatan:"Program nasional — gratis dari Dinas"},
  {bulan:12,  vaksin:"Brucellosis (betina <8bln)", cara:"Oral/IM",   dosis:"1 dosis",      catatan:"Khusus betina muda"},
];


/* ===== DATA AWAL ===== */
const initialCattle = [
  { id:"S001",name:"Simental-01",type:"sapi",breed:"Simental",gender:"Jantan",age:24,weightBuy:280,weightCurrent:340,priceBuy:17500000,status:"Penggemukan",buyDate:"2026-02-10",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Bandar H. Rahman",kandang:"A1",vaksin:"Lengkap",notes:"" },
  { id:"S002",name:"Limosin-02",type:"sapi",breed:"Limousin",gender:"Jantan",age:30,weightBuy:320,weightCurrent:392,priceBuy:19000000,status:"Siap Jual",buyDate:"2026-01-15",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Pasar Ciawi",kandang:"A2",vaksin:"Lengkap",notes:"" },
  { id:"S003",name:"PO-Betina-03",type:"sapi",breed:"PO",gender:"Betina",age:60,weightBuy:250,weightCurrent:290,priceBuy:11000000,status:"Breeding",buyDate:"2025-12-01",health:"Sehat",feedType:"Hijauan",supplier:"Peternak Garut",kandang:"B1",vaksin:"Lengkap",notes:"" },
  { id:"S004",name:"Simental-04",type:"sapi",breed:"Simental",gender:"Jantan",age:18,weightBuy:220,weightCurrent:270,priceBuy:14000000,status:"Penggemukan",buyDate:"2026-03-05",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Bandar H. Rahman",kandang:"A3",vaksin:"Lengkap",notes:"" },
  { id:"S005",name:"FH-Afkir-05",type:"sapi",breed:"FH Afkir",gender:"Betina",age:84,weightBuy:300,weightCurrent:346,priceBuy:10500000,status:"Siap Jual",buyDate:"2026-02-20",health:"Sehat",feedType:"Konsentrat",supplier:"Lembang Farm",kandang:"B2",vaksin:"Lengkap",notes:"" },
  { id:"S006",name:"PO-Sakit-06",type:"sapi",breed:"PO",gender:"Jantan",age:22,weightBuy:240,weightCurrent:254,priceBuy:13500000,status:"Sakit",buyDate:"2026-03-10",health:"Sakit",feedType:"Hijauan",supplier:"Pasar Singaparna",kandang:"C1",vaksin:"Belum",notes:"Demam 3 hari" },
  { id:"S007",name:"Bali-07",type:"sapi",breed:"Bali",gender:"Jantan",age:20,weightBuy:200,weightCurrent:242,priceBuy:12000000,status:"Penggemukan",buyDate:"2026-03-15",health:"Sehat",feedType:"Hijauan",supplier:"NTB Supplier",kandang:"A4",vaksin:"Lengkap",notes:"" },
];
const initialSheep = [
  { id:"D001",name:"Garut-J-01",type:"domba",breed:"Domba Garut",gender:"Jantan",age:18,weightBuy:28,weightCurrent:38,priceBuy:2500000,status:"Penggemukan",buyDate:"2026-02-15",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Pasar Wanaraja",kandang:"D1",vaksin:"Lengkap",notes:"" },
  { id:"D002",name:"Garut-J-02",type:"domba",breed:"Domba Garut",gender:"Jantan",age:24,weightBuy:35,weightCurrent:46,priceBuy:3200000,status:"Siap Jual",buyDate:"2026-01-20",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Pasar Wanaraja",kandang:"D2",vaksin:"Lengkap",notes:"" },
  { id:"D003",name:"Garut-B-03",type:"domba",breed:"Domba Garut",gender:"Betina",age:30,weightBuy:25,weightCurrent:30,priceBuy:1800000,status:"Breeding",buyDate:"2025-11-10",health:"Sehat",feedType:"Hijauan",supplier:"Peternak Bayongbong",kandang:"E1",vaksin:"Lengkap",notes:"" },
  { id:"D004",name:"Lokal-J-04",type:"domba",breed:"Domba Lokal",gender:"Jantan",age:14,weightBuy:20,weightCurrent:27,priceBuy:900000,status:"Penggemukan",buyDate:"2026-03-01",health:"Sehat",feedType:"Hijauan",supplier:"Pasar Cigembor",kandang:"D3",vaksin:"Belum",notes:"" },
  { id:"D005",name:"Garut-Muda-05",type:"domba",breed:"Domba Garut",gender:"Jantan",age:12,weightBuy:15,weightCurrent:19,priceBuy:1200000,status:"Penggemukan",buyDate:"2026-04-01",health:"Sehat",feedType:"Konsentrat+Hijauan",supplier:"Peternak Rancakalong",kandang:"D4",vaksin:"Belum",notes:"Lepas sapih" },
  { id:"D006",name:"Merino-B-06",type:"domba",breed:"Domba Merino",gender:"Betina",age:20,weightBuy:30,weightCurrent:35,priceBuy:2200000,status:"Breeding",buyDate:"2026-02-01",health:"Sehat",feedType:"Hijauan",supplier:"Import",kandang:"E2",vaksin:"Lengkap",notes:"" },
  { id:"D007",name:"Garut-Sakit-07",type:"domba",breed:"Domba Garut",gender:"Jantan",age:16,weightBuy:22,weightCurrent:23,priceBuy:1500000,status:"Sakit",buyDate:"2026-03-20",health:"Sakit",feedType:"Hijauan",supplier:"Pasar Tanjungsari",kandang:"D5",vaksin:"Belum",notes:"Cacingan" },
  { id:"D008",name:"Garut-B-08",type:"domba",breed:"Domba Garut",gender:"Betina",age:28,weightBuy:27,weightCurrent:32,priceBuy:1900000,status:"Breeding",buyDate:"2026-01-10",health:"Sehat",feedType:"Hijauan",supplier:"Pasar Wanaraja",kandang:"E3",vaksin:"Lengkap",notes:"" },
];
const initialPurchases = [
  { id:"BL001",animalId:"S001",animalName:"Simental-01",animalType:"sapi",supplier:"Bandar H. Rahman",supplierPhone:"081320000",date:"2026-02-10",weight:280,pricePerKg:62500,totalPrice:17500000,payMethod:"Tunai",notes:"Pasar Ciawi" },
  { id:"BL002",animalId:"D001",animalName:"Garut-J-01",animalType:"domba",supplier:"Pasar Wanaraja",supplierPhone:"081398888",date:"2026-02-15",weight:28,pricePerKg:89286,totalPrice:2500000,payMethod:"Transfer",notes:"" },
  { id:"BL003",animalId:"S002",animalName:"Limosin-02",animalType:"sapi",supplier:"Pasar Ciawi",supplierPhone:"081345555",date:"2026-01-15",weight:320,pricePerKg:59375,totalPrice:19000000,payMethod:"Tunai",notes:"Dari bandar langsung" },
  { id:"BL004",animalId:"BR001",animalName:"DOC Cobb 500 - 2000 ekor",animalType:"broiler",supplier:"PT Japfa Comfeed",supplierPhone:"02145678901",date:"2026-05-08",weight:0,pricePerKg:0,totalPrice:15000000,payMethod:"Transfer",notes:"Harga DOC Rp7500/ekor, chick-in OK" },
  { id:"BL005",animalId:"BR002",animalName:"DOC Ross 308 - 1900 ekor",animalType:"broiler",supplier:"PT Malindo Feedmill",supplierPhone:"02198765432",date:"2026-04-30",weight:0,pricePerKg:0,totalPrice:14820000,payMethod:"Transfer",notes:"Rp7800/ekor, mortalitas 2 ekor saat tiba" },
  { id:"BL006",animalId:"PT001",animalName:"DOC Layer Lohmann Brown - 500 ekor",animalType:"petelur",supplier:"PT Sierad Produce",supplierPhone:"02156789012",date:"2025-08-01",weight:0,pricePerKg:0,totalPrice:7500000,payMethod:"Transfer",notes:"Rp15000/ekor pullet umur 1 hari" },
  { id:"BL007",animalId:"PT002",animalName:"DOC Layer ISA Brown - 700 ekor",animalType:"petelur",supplier:"PT Malindo Feedmill",supplierPhone:"02198765432",date:"2025-07-15",weight:0,pricePerKg:0,totalPrice:11200000,payMethod:"Transfer",notes:"Rp16000/ekor, kualitas A" },
  { id:"BL008",animalId:"",animalName:"Pakan Broiler Starter 2 ton",animalType:"broiler",supplier:"PT Charoen Pokhpand",supplierPhone:"02187654321",date:"2026-05-08",weight:2000,pricePerKg:8500,totalPrice:17000000,payMethod:"Transfer",notes:"Untuk Kandang D periode 12" },
  { id:"BL009",animalId:"",animalName:"Pakan Layer Mash 1.5 ton",animalType:"petelur",supplier:"PT Japfa Comfeed",supplierPhone:"02145678901",date:"2026-05-10",weight:1500,pricePerKg:7800,totalPrice:11700000,payMethod:"Transfer",notes:"Kandang A+B, stok 30 hari" },
  { id:"BL010",animalId:"",animalName:"Vaksin ND + Gumboro paket",animalType:"broiler",supplier:"PT Medion",supplierPhone:"022765432",date:"2026-05-09",weight:0,pricePerKg:0,totalPrice:850000,payMethod:"Tunai",notes:"Untuk 2000 ekor Kandang D" },
];
const initialHealth = [
  { id:"KS001",animalId:"S006",animalName:"PO-Sakit-06",animalType:"sapi",date:"2026-03-15",type:"Sakit",diagnosis:"Demam & Batuk",treatment:"Antibiotik Enrofloxacin + Vit B",cost:185000,vet:"drh. Hasan",status:"Dalam Perawatan",notes:"Cek ulang 3 hari lagi" },
  { id:"KS002",animalId:"D007",animalName:"Garut-Sakit-07",animalType:"domba",date:"2026-04-02",type:"Sakit",diagnosis:"Cacingan Berat",treatment:"Albendazole 3ml + Vitamin",cost:75000,vet:"Mantri Dede",status:"Dalam Perawatan",notes:"Isolasi dari kandang lain" },
  { id:"KS003",animalId:"S001",animalName:"Simental-01",animalType:"sapi",date:"2026-03-01",type:"Vaksin",diagnosis:"-",treatment:"Vaksin Anthrax + Jembrana",cost:120000,vet:"drh. Hasan",status:"Selesai",notes:"Rutin 6 bulanan" },
  { id:"KS004",animalId:"D002",animalName:"Garut-J-02",animalType:"domba",date:"2026-03-10",type:"Vaksin",diagnosis:"-",treatment:"Vaksin Scabies",cost:45000,vet:"Mantri Dede",status:"Selesai",notes:"" },
  { id:"KS005",animalId:"S004",animalName:"Simental-04",animalType:"sapi",date:"2026-04-15",type:"Rutin",diagnosis:"-",treatment:"Ivermectin obat cacing",cost:90000,vet:"drh. Hasan",status:"Selesai",notes:"Rutin 3 bulan" },
  { id:"KS006",animalId:"BR001",animalName:"Kandang D Cobb 500 (2000 ekor)",animalType:"broiler",date:"2026-05-09",type:"Vaksin",diagnosis:"-",treatment:"Vaksin ND (Newcastle Disease) tetes mata",cost:320000,vet:"Mantri Agus",status:"Selesai",notes:"Umur 4 hari, vaksin pertama" },
  { id:"KS007",animalId:"BR001",animalName:"Kandang D Cobb 500 (2000 ekor)",animalType:"broiler",date:"2026-05-15",type:"Vaksin",diagnosis:"-",treatment:"Vaksin Gumboro IBD tetes air minum",cost:280000,vet:"Mantri Agus",status:"Selesai",notes:"Umur 10 hari" },
  { id:"KS008",animalId:"BR002",animalName:"Kandang E Ross 308 (1900 ekor)",animalType:"broiler",date:"2026-05-06",type:"Sakit",diagnosis:"CRD (Chronic Respiratory Disease)",treatment:"Tylosin + Vitamin C air minum 5 hari",cost:450000,vet:"drh. Sinta",status:"Selesai",notes:"Mortalitas 12 ekor selama sakit" },
  { id:"KS009",animalId:"PT001",animalName:"Kandang A Lohmann Brown (500 ekor)",animalType:"petelur",date:"2026-04-20",type:"Vaksin",diagnosis:"-",treatment:"Vaksin AI (Avian Influenza) H5N1",cost:375000,vet:"drh. Hasan",status:"Selesai",notes:"Vaksin 6 bulanan, wajib" },
  { id:"KS010",animalId:"PT002",animalName:"Kandang B ISA Brown (700 ekor)",animalType:"petelur",date:"2026-05-05",type:"Rutin",diagnosis:"-",treatment:"Pemberian Vitamin AD3E + obat cacing Piperazine",cost:210000,vet:"Mantri Agus",status:"Selesai",notes:"Produksi menurun 3%, recovery 1 minggu" },
  { id:"KS011",animalId:"PT003",animalName:"Kandang C Layer Afkir (200 ekor)",animalType:"petelur",date:"2026-05-20",type:"Sakit",diagnosis:"Egg Drop Syndrome (EDS)",treatment:"Supportif Vitamin + Elektrolit",cost:150000,vet:"Mantri Agus",status:"Dalam Perawatan",notes:"Produksi telur drop 30%, kandang perlu desinfeksi" },
  { id:"KS012",animalId:"BR002",animalName:"Kandang E Ross 308 (1850 ekor)",animalType:"broiler",date:"2026-06-01",type:"Vaksin",diagnosis:"-",treatment:"Vaksin ND IB (Infectious Bronchitis) spray",cost:340000,vet:"drh. Sinta",status:"Selesai",notes:"Umur 14 hari, booster" },
];
const initialFeed = [
  { id:"PK001",type:"Konsentrat Sapi",brand:"Charoen CP",unit:"Kg",stock:500,pricePerUnit:4500,usagePerDay:25,forAnimal:"sapi",date:"2026-05-01",supplier:"Toko Pertanian Tasik" },
  { id:"PK002",type:"Hijauan Segar",brand:"Lokal",unit:"Kg",stock:1200,pricePerUnit:500,usagePerDay:120,forAnimal:"semua",date:"2026-05-01",supplier:"Petani Sekitar" },
  { id:"PK003",type:"Dedak Padi",brand:"Lokal",unit:"Kg",stock:300,pricePerUnit:3000,usagePerDay:15,forAnimal:"semua",date:"2026-05-05",supplier:"Penggilingan Padi" },
  { id:"PK004",type:"Ampas Tahu",brand:"Lokal",unit:"Kg",stock:200,pricePerUnit:1500,usagePerDay:20,forAnimal:"semua",date:"2026-05-08",supplier:"Pabrik Tahu Singaparna" },
  { id:"PK005",type:"Molases",brand:"Rajawali",unit:"Liter",stock:50,pricePerUnit:8000,usagePerDay:3,forAnimal:"sapi",date:"2026-05-10",supplier:"Distributor Molases" },
  { id:"PK006",type:"Konsentrat Domba",brand:"Wonosari",unit:"Kg",stock:80,pricePerUnit:5000,usagePerDay:8,forAnimal:"domba",date:"2026-05-12",supplier:"Toko Ternak Garut" },
  { id:"PK007",type:"Obat Cacing",brand:"Wormectin",unit:"Botol",stock:5,pricePerUnit:45000,usagePerDay:0.1,forAnimal:"domba",date:"2026-05-01",supplier:"Apotek Hewan" },
  { id:"PK008",type:"Mineral Block",brand:"Medion",unit:"Blok",stock:10,pricePerUnit:35000,usagePerDay:0.3,forAnimal:"semua",date:"2026-05-03",supplier:"Apotek Hewan" },
  { id:"PK009",type:"Broiler Starter",brand:"Charoen CP-511",unit:"Kg",stock:1850,pricePerUnit:8500,usagePerDay:56,forAnimal:"broiler",date:"2026-05-08",supplier:"PT Charoen Pokhpand" },
  { id:"PK010",type:"Broiler Grower",brand:"Charoen CP-512",unit:"Kg",stock:620,pricePerUnit:8200,usagePerDay:112,forAnimal:"broiler",date:"2026-05-15",supplier:"PT Charoen Pokhpand" },
  { id:"PK011",type:"Broiler Finisher",brand:"Japfa BR-2",unit:"Kg",stock:2100,pricePerUnit:7900,usagePerDay:280,forAnimal:"broiler",date:"2026-05-20",supplier:"PT Japfa Comfeed" },
  { id:"PK012",type:"Layer Mash Pre-layer",brand:"Malindo Layer-1",unit:"Kg",stock:480,pricePerUnit:8000,usagePerDay:30,forAnimal:"petelur",date:"2026-05-10",supplier:"PT Malindo Feedmill" },
  { id:"PK013",type:"Layer Mash Peak",brand:"Malindo Layer-2",unit:"Kg",stock:1250,pricePerUnit:7800,usagePerDay:120,forAnimal:"petelur",date:"2026-05-10",supplier:"PT Malindo Feedmill" },
  { id:"PK014",type:"Limestone (Kapur)",brand:"Lokal",unit:"Kg",stock:150,pricePerUnit:1200,usagePerDay:6,forAnimal:"petelur",date:"2026-05-05",supplier:"Toko Bahan Bangunan" },
  { id:"PK015",type:"Premix Vitamin Ayam",brand:"Vitachick",unit:"Kg",stock:18,pricePerUnit:65000,usagePerDay:0.5,forAnimal:"broiler",date:"2026-05-08",supplier:"Apotek Hewan" },
  { id:"PK016",type:"Probiotik EM4 Ternak",brand:"EM4",unit:"Liter",stock:12,pricePerUnit:35000,usagePerDay:0.2,forAnimal:"semua",date:"2026-05-12",supplier:"Toko Pertanian" },
  { id:"PK017",type:"Grit/Kerikil Kasar",brand:"Lokal",unit:"Kg",stock:40,pricePerUnit:2500,usagePerDay:1,forAnimal:"petelur",date:"2026-05-15",supplier:"Toko Pertanian" },
];
const initialBreeding = [
  { id:"BR001",indukId:"S003",indukName:"PO-Betina-03",animalType:"sapi",pejantan:"Simental (IB)",method:"IB",date:"2026-03-15",status:"Bunting",estimasiLahir:"2026-12-20",anakLahir:0,notes:"Bunting konfirmasi bulan ke-2" },
  { id:"BR002",indukId:"D003",indukName:"Garut-B-03",animalType:"domba",pejantan:"Garut Super",method:"Kawin Alam",date:"2026-03-01",status:"Bunting",estimasiLahir:"2026-08-01",anakLahir:0,notes:"Estimasi kembar 2 ekor" },
  { id:"BR003",indukId:"D006",indukName:"Merino-B-06",animalType:"domba",pejantan:"Garut (IB)",method:"IB",date:"2026-04-10",status:"Menunggu",estimasiLahir:"2026-09-10",anakLahir:0,notes:"Baru diinseminasi" },
  { id:"BR004",indukId:"D008",indukName:"Garut-B-08",animalType:"domba",pejantan:"Garut Lokal",method:"Kawin Alam",date:"2026-02-10",status:"Melahirkan",estimasiLahir:"2026-07-10",anakLahir:2,notes:"Lahir 2 ekor jantan, sehat" },
  { id:"BR005",indukId:"PT001",indukName:"Kandang A Lohmann Brown (500 ekor)",animalType:"petelur",pejantan:"—",method:"Tetasan",date:"2026-04-01",status:"Menetas",estimasiLahir:"2026-04-22",anakLahir:210,telurDitetaskan:250,fertilitasPct:92,daya_tetas_pct:84,notes:"Batch penetasan pertama, HE (Hatching Egg) dari induk terbaik" },
  { id:"BR006",indukId:"PT002",indukName:"Kandang B ISA Brown (700 ekor)",animalType:"petelur",pejantan:"—",method:"Tetasan",date:"2026-05-01",status:"Menetas",estimasiLahir:"2026-05-22",anakLahir:318,telurDitetaskan:380,fertilitasPct:90,daya_tetas_pct:84,notes:"DOC betina dikembangkan, jantan dijual" },
  { id:"BR007",indukId:"BR001",indukName:"Kandang D Cobb 500 (2000 ekor)",animalType:"broiler",pejantan:"Cobb 500 Rooster",method:"Kawin Alam (Kandang)",date:"2026-05-08",status:"Bertelur",estimasiLahir:"2026-06-15",anakLahir:0,telurDitetaskan:0,fertilitasPct:88,daya_tetas_pct:0,notes:"Parent stock — telur fertile untuk hatchery mitra" },
  { id:"BR008",indukId:"",indukName:"Penetasan DOC Layer Batch 3",animalType:"petelur",pejantan:"—",method:"Mesin Tetas",date:"2026-05-15",status:"Inkubasi",estimasiLahir:"2026-06-05",anakLahir:0,telurDitetaskan:450,fertilitasPct:91,daya_tetas_pct:0,notes:"Inkubator 450 butir HE, suhu 37.8°C, kelembaban 60%" },
];
const initialExpenses = [
  { id:"OP001",category:"Pakan",description:"Konsentrat Sapi 500kg",amount:2250000,date:"2026-05-01",animalType:"sapi",notes:"" },
  { id:"OP002",category:"Kesehatan",description:"Obat & Vaksin rutin",amount:415000,date:"2026-05-03",animalType:"semua",notes:"" },
  { id:"OP003",category:"Tenaga Kerja",description:"Gaji kandang 2 orang",amount:4000000,date:"2026-05-01",animalType:"semua",notes:"Bulanan" },
  { id:"OP004",category:"Transportasi",description:"Angkut sapi dari Ciawi",amount:500000,date:"2026-04-15",animalType:"sapi",notes:"" },
  { id:"OP005",category:"Pakan",description:"Hijauan 1200kg",amount:600000,date:"2026-05-01",animalType:"semua",notes:"" },
  { id:"OP006",category:"Kandang",description:"Perbaikan atap kandang B",amount:750000,date:"2026-04-20",animalType:"semua",notes:"" },
  { id:"OP007",category:"Pakan",description:"Konsentrat Domba 80kg",amount:400000,date:"2026-05-12",animalType:"domba",notes:"" },
  { id:"OP008",category:"Pakan",description:"Broiler Starter CP-511 2ton Kandang D",amount:17000000,date:"2026-05-08",animalType:"broiler",notes:"Untuk 2000 ekor 14 hari pertama" },
  { id:"OP009",category:"Pakan",description:"Layer Mash Malindo 1.5ton Kandang A+B",amount:11700000,date:"2026-05-10",animalType:"petelur",notes:"Stok 30 hari" },
  { id:"OP010",category:"Kesehatan",description:"Vaksin ND+Gumboro+AI paket Kandang D",amount:850000,date:"2026-05-09",animalType:"broiler",notes:"Termasuk jasa vaksinasi" },
  { id:"OP011",category:"Kesehatan",description:"Obat CRD Tylosin+VitC Kandang E",amount:450000,date:"2026-05-06",animalType:"broiler",notes:"" },
  { id:"OP012",category:"DOC",description:"DOC Cobb 500 2000 ekor Kandang D",amount:15000000,date:"2026-05-08",animalType:"broiler",notes:"Rp7500/ekor PT Japfa" },
  { id:"OP013",category:"Listrik",description:"Listrik pemanas brooder+blower Mei",amount:1850000,date:"2026-05-31",animalType:"broiler",notes:"2 kandang aktif" },
  { id:"OP014",category:"Listrik",description:"Listrik ventilasi+lampu kandang layer Mei",amount:980000,date:"2026-05-31",animalType:"petelur",notes:"3 kandang layer" },
  { id:"OP015",category:"Kandang",description:"Disinfektan+sekam baru persiapan Kandang G",amount:620000,date:"2026-05-25",animalType:"broiler",notes:"Washing+desinfeksi sebelum chick-in" },
  { id:"OP016",category:"Tenaga Kerja",description:"Bonus panen Kandang F - FCR bagus",amount:500000,date:"2026-05-15",animalType:"broiler",notes:"Insentif FCR ≤1.70" },
  { id:"OP017",category:"Pakan",description:"Premix Vitachick 20kg",amount:1300000,date:"2026-05-08",animalType:"broiler",notes:"Suplemen 2000 ekor" },
  { id:"OP018",category:"Pakan",description:"Limestone 150kg + Grit layer",amount:555000,date:"2026-05-15",animalType:"petelur",notes:"Kalsium cangkang telur" },
];

const HARGA_KG = {
  "Simental":62000,"Limousin":60000,"PO":50000,"FH Afkir":42000,"Bali":48000,"Brahman":52000,
  "Domba Garut":90000,"Domba Lokal":75000,"Domba Merino":85000,"Domba Ekor Gemuk":80000,"Kambing PE":70000,"Kambing Lokal":65000,
};

/* ===== HELPERS ===== */
const rp = n => "Rp " + new Intl.NumberFormat("id-ID").format(Math.round(Number(n) || 0));
const adg = (wC, wB, tgl) => { if(!wC||!wB||!tgl) return 0; const d = Math.floor((Date.now() - new Date(tgl)) / 86400000); return d > 0 ? ((wC - wB) / d).toFixed(2) : "0.00"; };
const nilaiEst = a => (a&&a.weightCurrent ? a.weightCurrent * (HARGA_KG[a.breed] || (a.type === "domba" ? 80000 : 50000)) : 0);
const todayStr = () => new Date().toISOString().split("T")[0];
const newId = (prefix, list) => {
  const mx = list.reduce((m, x) => { const n = parseInt(x.id.replace(prefix, "")) || 0; return n > m ? n : m; }, 0);
  return prefix + String(mx + 1).padStart(3, "0");
};

/* ===== ICONS ===== */
const SVG = ({ d, size = 16, color = "currentColor", fill = "none", sw = "2" }) => (
  <svg width={size} height={size} fill={fill} stroke={color} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24">
    {typeof d === "string" ? <path d={d} /> : d}
  </svg>
);
const Ico = ({ n, size = 16, color = "currentColor" }) => {
  const map = {
    dash: "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z",
    sapi: <>
      <path d="M3 12C3 7 7 4 12 4s9 3 9 8" /><path d="M12 20c-4 0-7-2-7-6h14c0 4-3 6-7 6z" />
      <circle cx="9" cy="10" r="1" fill={color} /><circle cx="15" cy="10" r="1" fill={color} />
    </>,
    domba: <>
      <ellipse cx="12" cy="10" rx="7" ry="5" />
      <path d="M7 14c0 3 2 5 5 5s5-2 5-5" />
      <path d="M8 5c-1-2-3-2-3 0M16 5c1-2 3-2 3 0" />
      <circle cx="10" cy="10" r="1" fill={color} /><circle cx="14" cy="10" r="1" fill={color} />
    </>,
    beli: <>
      <circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" />
      <path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6" />
    </>,
    jual: "M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6",
    pakan: <>
      <path d="M3 6h18M3 12h18M3 18h18" />
      <circle cx="8" cy="6" r="2" fill={color} /><circle cx="16" cy="12" r="2" fill={color} /><circle cx="8" cy="18" r="2" fill={color} />
    </>,
    sehat: "M22 12h-4l-3 9L9 3l-3 9H2",
    kawin: "M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z",
    biaya: "M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H7",
    laporan: <>
      <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" /><polyline points="14,2 14,8 20,8" />
      <line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" />
    </>,
    chart: <>
      <line x1="18" y1="20" x2="18" y2="10" /><line x1="12" y1="20" x2="12" y2="4" />
      <line x1="6" y1="20" x2="6" y2="14" /><line x1="2" y1="20" x2="22" y2="20" />
    </>,
    warn: <>
      <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
      <line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
    </>,
    plus: <>
      <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
    </>,
    x: <>
      <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
    </>,
    edit: <>
      <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" />
      <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" />
    </>,
    del: <>
      <polyline points="3,6 5,6 21,6" />
      <path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2" />
    </>,
    srch: <>
      <circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
    </>,
    eye: <>
      <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" />
    </>,
    chev_l: "M15 18l-6-6 6-6",
    chev_r: "M9 18l6-6-6-6",
    rph: "M14.5 3.5a1 1 0 00-1-1h-7a1 1 0 00-1 1V20a1 1 0 001 1h11a1 1 0 001-1V9.5m-5-6L20 9.5m-5.5-6H20",
    petelur: "M12 2a6 6 0 016 6c0 4-3 7-6 10C9 15 6 12 6 8a6 6 0 016-6zM8 20h8M10 23h4",
    broiler: "M12 3C8 3 5 6 5 10c0 2 1 4 2 5l-1 4h12l-1-4c1-1 2-3 2-5 0-4-3-7-7-7z",
  };
  const d = map[n];
  if (!d) return null;
  return (
    <svg width={size} height={size} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24">
      {typeof d === "string" ? <path d={d} /> : d}
    </svg>
  );
};

/* ===== BASE UI ===== */
const S = {
  row: { display: "flex", alignItems: "center", gap: 8 },
  col: { display: "flex", flexDirection: "column", gap: 8 },
  grid2: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 },
  input: { background: "#13161f", border: `1px solid ${C.border2}`, borderRadius: 9, padding: "9px 12px", color: C.text, fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" },
  select: { background: "#13161f", border: `1px solid ${C.border2}`, borderRadius: 9, padding: "9px 12px", color: C.text, fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" },
  label: { fontSize: 10, color: C.dim, textTransform: "uppercase", letterSpacing: 1.2, fontWeight: 700, display: "block", marginBottom: 5 },
  th: { padding: "10px 12px", textAlign: "left", fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: 0.8, whiteSpace: "nowrap" },
  td: { padding: "10px 12px", fontSize: 12 },
};

const KartuStat = ({ label, value, sub, color, icon }) => (
  <div style={{ background: color + "0c", border: `1px solid ${color}28`, borderRadius: 14, padding: "16px 18px", position: "relative", overflow: "hidden", minWidth: 0 }}>
    <div style={{ position: "absolute", top: 10, right: 10, opacity: 0.1 }}><Ico n={icon} size={36} color={color} /></div>
    <div style={{ fontSize: 10, color: C.dim, textTransform: "uppercase", letterSpacing: 1.5, fontWeight: 700, marginBottom: 6 }}>{label}</div>
    <div style={{ fontSize: 20, fontWeight: 800, color, lineHeight: 1.1, fontFamily: "'DM Serif Display', serif", marginBottom: 4 }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: C.muted }}>{sub}</div>}
    <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 2, background: `linear-gradient(90deg,${color},transparent)` }} />
  </div>
);

const Badge = ({ text }) => {
  const t = String(text || "");
  const map = {
    "Sehat": "#22c55e", "Sakit": "#ef4444", "Pemulihan": "#f59e0b",
    "Penggemukan": "#f5c842", "Siap Jual": "#3b82f6", "Breeding": "#a855f7",
    "Bunting": "#a855f7", "Melahirkan": "#22c55e", "Menunggu": "#f59e0b", "Gagal": "#ef4444",
    "Jantan": "#60a5fa", "Betina": "#f472b6",
    "sapi": "#f5c842", "domba": "#a3e635",
    "Pasar": "#3b82f6", "Jagal": "#ef4444", "Kurban": "#f59e0b",
    "Perusahaan": "#22c55e", "BAZNAS": "#a855f7", "Aqiqah": "#ec4899", "Online": "#60a5fa",
    "Lengkap": "#22c55e", "Belum": "#ef4444", "Sebagian": "#f59e0b",
    "Selesai": "#22c55e", "Dalam Perawatan": "#f59e0b",
    "Vaksin": "#3b82f6", "Rutin": "#9097a8", "Operasi": "#a855f7", "Cedera": "#f59e0b",
    "IB": "#a855f7", "Kawin Alam": "#22c55e", "ET": "#3b82f6",
    "Tunai": "#22c55e", "Transfer": "#3b82f6", "DP+Pelunasan": "#f59e0b", "Kredit": "#ef4444",
    "semua": "#9097a8",
  };
  const c = map[t] || "#666";
  return <span style={{ background: c + "14", color: c, border: `1px solid ${c}30`, borderRadius: 20, padding: "2px 9px", fontSize: 10, fontWeight: 700, whiteSpace: "nowrap" }}>{t || "-"}</span>;
};

const Modal = ({ title, onClose, children, wide }) => (
  <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.82)", zIndex: 999, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
    <div style={{ background: "#0e1120", border: `1px solid ${C.border2}`, borderRadius: 18, padding: 26, maxWidth: wide ? 800 : 620, width: "100%", maxHeight: "92vh", overflowY: "auto", boxShadow: "0 24px 80px rgba(0,0,0,0.6)" }}>
      <div style={{ ...S.row, justifyContent: "space-between", marginBottom: 20, paddingBottom: 16, borderBottom: `1px solid ${C.border}` }}>
        <h3 style={{ color: C.sapi, fontFamily: "'DM Serif Display',serif", fontSize: 18, margin: 0 }}>{title}</h3>
        <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: C.dim, padding: 4, borderRadius: 6 }}><Ico n="x" size={18} /></button>
      </div>
      {children}
    </div>
  </div>
);

const Inp = ({ label, value, onChange, type = "text", options, span, placeholder, required }) => (
  <div style={{ gridColumn: span ? "1/-1" : undefined }}>
    <label style={S.label}>{label}{required && <span style={{ color: C.expense }}>*</span>}</label>
    {options ? (
      <select value={value} onChange={e => onChange(e.target.value)} style={S.select}>
        {options.map(o => <option key={o.v ?? o} value={o.v ?? o}>{o.l ?? o}</option>)}
      </select>
    ) : (
      <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder || ""} style={S.input} />
    )}
  </div>
);

const Textarea = ({ label, value, onChange, span }) => (
  <div style={{ gridColumn: span ? "1/-1" : undefined }}>
    <label style={S.label}>{label}</label>
    <textarea value={value} onChange={e => onChange(e.target.value)} rows={2} style={{ ...S.input, resize: "vertical" }} />
  </div>
);

const BtnPrimary = ({ children, onClick, color = C.sapi, full }) => (
  <button onClick={onClick} style={{ background: color, color: ["#f5c842", "#a3e635"].includes(color) ? "#000" : "#fff", border: "none", borderRadius: 10, padding: "10px 18px", cursor: "pointer", fontWeight: 700, fontSize: 13, display: "flex", alignItems: "center", justifyContent: "center", gap: 6, width: full ? "100%" : "auto", marginTop: full ? 18 : 0 }}>
    {children}
  </button>
);

const BtnSec = ({ children, onClick, color = C.sapi, small = false, full = false, style: extraStyle = {} }) => (
  <button onClick={onClick} style={{ background: color + "14", color, border: `1px solid ${color}30`, borderRadius: small?6:9, padding: small?"3px 9px":"7px 14px", cursor: "pointer", fontWeight: 700, fontSize: small?10:12, display: "flex", alignItems: "center", gap: 5, whiteSpace: "nowrap", width: full?"100%":"auto", justifyContent: full?"center":"flex-start", ...extraStyle }}>
    {children}
  </button>
);

const Cari = ({ value, onChange, placeholder }) => (
  <div style={{ position: "relative", minWidth: 200 }}>
    <div style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)" }}><Ico n="srch" size={13} color={C.dim} /></div>
    <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder || "Cari..."} style={{ ...S.input, paddingLeft: 30 }} />
  </div>
);

const FilterBar = ({ active, items, onChange, color }) => (
  <div style={{ ...S.row, flexWrap: "wrap" }}>
    {items.map(f => (
      <button key={f.v || f} onClick={() => onChange(f.v || f)} style={{ background: active === (f.v || f) ? color : "#ffffff0a", color: active === (f.v || f) ? (["#f5c842", "#a3e635"].includes(color) ? "#000" : "#fff") : C.dim, border: "none", borderRadius: 20, padding: "5px 13px", cursor: "pointer", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>
        {f.l || f}
      </button>
    ))}
  </div>
);

const TableWrap = ({ children }) => (
  <div style={{ overflowX: "auto", borderRadius: 12, border: `1px solid ${C.border}` }}>
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>{children}</table>
  </div>
);
const TH = ({ children, color }) => <th style={{ ...S.th, color: color || C.muted, borderBottom: `1px solid ${(color || C.muted) + "30"}`, background: (color || C.muted) + "0a" }}>{children}</th>;
const TD = ({ children, bold, color, mono }) => <td style={{ ...S.td, color: color || C.text, fontWeight: bold ? 700 : 400, fontFamily: mono ? "monospace" : "inherit" }}>{children}</td>;
const TR = ({ children, i, color }) => {
  const [hover, setHover] = useState(false);
  return (
    <tr onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ borderBottom: `1px solid ${C.border}`, background: hover ? (color || C.sapi) + "08" : i % 2 ? "#ffffff05" : "transparent" }}>
      {children}
    </tr>
  );
};
const Empty = () => <div style={{ textAlign: "center", padding: "36px 0", color: C.dim, fontSize: 13 }}>Tidak ada data</div>;

const AlertBar = ({ items }) => {
  if (!items.length) return null;
  return (
    <div style={{ ...S.row, flexWrap: "wrap", gap: 8, marginBottom: 4 }}>
      {items.map((a, i) => (
        <div key={i} style={{ background: a.color + "12", border: `1px solid ${a.color}35`, borderRadius: 10, padding: "8px 14px", color: a.color, fontSize: 12, ...S.row }}>
          <Ico n="warn" size={13} color={a.color} />{a.text}
        </div>
      ))}
    </div>
  );
};

const InfoBox = ({ label, value, color = C.text, sub }) => (
  <div style={{ background: "#ffffff06", borderRadius: 9, padding: "10px 14px" }}>
    <div style={{ fontSize: 9, color: C.dim, fontWeight: 700, letterSpacing: 1.2, textTransform: "uppercase", marginBottom: 4 }}>{label}</div>
    <div style={{ color, fontWeight: 700, fontSize: 13 }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: C.muted, marginTop: 2 }}>{sub}</div>}
  </div>
);

/* ===== HALAMAN: DATA SAPI / DOMBA ===== */
const PageHewan = ({ animals=[], setAnimals, type }) => {
  const isDomba = type === "domba";
  const ac = isDomba ? C.domba : C.sapi;
  const prefix = isDomba ? "D" : "S";
  const breedList = isDomba
    ? ["Domba Garut", "Domba Lokal", "Domba Merino", "Domba Ekor Gemuk", "Kambing PE", "Kambing Lokal"]
    : [
      // Sapi Impor / Persilangan
      "Simental","Limousin","Angus","Hereford","Brahman","Brangus",
      "Wagyu (Kobe)","Charolais","Droughtmaster","Murray Grey",
      // Sapi Lokal Indonesia
      "PO (Peranakan Ongole)","Sapi Bali","Sapi Madura","Sapi Aceh",
      "Sapi Pasundan","Sapi Pesisir (Sumbar)","Sapi Jabres (Jateng)",
      "Sapi Galekan (Jatim)","Sapi Ongole Murni","Sapi SO (Sumba Ongole)",
      // Sapi Persilangan Lokal
      "SimPO (Simental×PO)","LimPO (Limousin×PO)","BrahmanCross",
      "Peranakan FH","FH Afkir","Sapi Perah FH",
      // Lainnya
      "Sapi Kerbau Silangan","Lokal Campuran"
    ];

  const blankForm = { name: "", type, breed: breedList[0], gender: "Jantan", age: "", weightBuy: "", weightCurrent: "", priceBuy: "", status: "Penggemukan", buyDate: todayStr(), health: "Sehat", feedType: "Konsentrat+Hijauan", supplier: "", kandang: "", vaksin: "Belum", notes: "" };
  const [form, setForm] = useState(blankForm);
  const [editId, setEditId] = useState(null);
  const [modal, setModal] = useState(false);
  const [detail, setDetail] = useState(null);
  const [filterStatus, setFilterStatus] = useState("Semua");
  const [search, setSearch] = useState("");
  const [rasTab, setRasTab] = useState(false);
  const [selectedRas, setSelectedRas] = useState(null);

  const filtered = animals.filter(a =>
    (filterStatus === "Semua" || a.status === filterStatus) &&
    (a.name.toLowerCase().includes(search.toLowerCase()) || a.breed.toLowerCase().includes(search.toLowerCase()) || a.id.toLowerCase().includes(search.toLowerCase()))
  );

  const save = () => {
    const p = { ...form, weightBuy: +form.weightBuy, weightCurrent: +form.weightCurrent, priceBuy: +form.priceBuy, age: +form.age };
    if (editId) setAnimals(animals.map(a => a.id === editId ? { ...p, id: editId } : a));
    else setAnimals([...animals, { ...p, id: newId(prefix, animals) }]);
    setModal(false); setEditId(null); setForm(blankForm);
  };
  const openEdit = a => { setForm({ ...a }); setEditId(a.id); setModal(true); };
  const del = id => { if (window.confirm("Hapus data ini?")) setAnimals(animals.filter(a => a.id !== id)); };

  const totalBB = animals.reduce((s, a) => s + a.weightCurrent, 0);
  const totalNilai = animals.reduce((s, a) => s + nilaiEst(a), 0);
  const siap = animals.filter(a => a.status === "Siap Jual").length;
  const sakit = animals.filter(a => a.health === "Sakit").length;

  const estP = form.weightCurrent && form.priceBuy ? nilaiEst({ ...form, weightCurrent: +form.weightCurrent, priceBuy: +form.priceBuy }) - +form.priceBuy : null;

  return (
    <div style={S.col}>
      {/* STAT */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        <KartuStat label={isDomba ? "Total Domba" : "Total Sapi"} value={animals.length + " ekor"} sub={siap + " siap jual"} color={ac} icon={isDomba ? "domba" : "sapi"} />
        <KartuStat label="Total BB" value={totalBB + " kg"} color={C.info} icon="chart" />
        <KartuStat label="Nilai Aset" value={rp(totalNilai)} sub="Estimasi pasar" color={C.sell} icon="jual" />
        {sakit > 0 && <KartuStat label="Perlu Diobati" value={sakit + " ekor"} color={C.expense} icon="sehat" />}
      </div>

      {/* TAB BAR */}
      <div style={{ display:"flex", gap:8, borderBottom:"1px solid #1c1e2b", paddingBottom:0 }}>
        {[{id:false,l:"📋 Data "+( isDomba?"Domba":"Sapi")},{id:true,l:"📖 Info Ras Sapi"}].filter(t=>!isDomba||t.id===false).map(t=>(
          <button key={String(t.id)} onClick={()=>setRasTab(t.id)}
            style={{background:"none",border:"none",borderBottom:"2px solid "+(rasTab===t.id?ac:"transparent"),
              color:rasTab===t.id?ac:"#555a6a",padding:"8px 16px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>
            {t.l}
          </button>
        ))}
        {!isDomba && !rasTab && (
          <button onClick={()=>setRasTab(true)} style={{marginLeft:"auto",background:ac+"18",border:"1px solid "+ac+"30",borderRadius:8,padding:"6px 12px",cursor:"pointer",color:ac,fontSize:11,fontWeight:700}}>
            🔍 Bandingkan Ras
          </button>
        )}
      </div>

      {/* ════ TAB INFO RAS ════ */}
      {!isDomba && rasTab && (
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          {/* Grid kartu ras */}
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(280px,1fr))",gap:12}}>
            {Object.entries(RAS_SAPI).map(([nama,r])=>{
              const isSelected = selectedRas===nama;
              return (
                <div key={nama}
                  onClick={()=>setSelectedRas(isSelected?null:nama)}
                  style={{background:isSelected?"#f5c84210":"#0f1118",border:"1px solid "+(isSelected?"#f5c84255":"#1c1e2b"),
                    borderRadius:13,padding:14,cursor:"pointer",transition:"all 0.2s"}}>
                  {/* Header kartu */}
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8}}>
                    <div>
                      <div style={{color:"#f5c842",fontWeight:800,fontSize:13,marginBottom:2}}>{nama}</div>
                      <div style={{color:"#9097a8",fontSize:10}}>{r.asal}</div>
                    </div>
                    <span style={{background:"#f5c84215",color:"#f5c842",border:"1px solid #f5c84225",
                      borderRadius:20,padding:"2px 9px",fontSize:9,fontWeight:700,textAlign:"right",maxWidth:120,flexShrink:0}}>
                      {r.tipe}
                    </span>
                  </div>
                  {/* BB & ADG */}
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6,marginBottom:8}}>
                    {[
                      ["⚖️ BB Jantan", r.bbDewasa?.jantan||"-"],
                      ["⚖️ BB Betina", r.bbDewasa?.betina||"-"],
                      ["📈 ADG", r.adg||r.produksiSusu||"-"],
                      ["💰 Harga", r.harga||"-"],
                    ].map(([k,v])=>(
                      <div key={k} style={{background:"#ffffff06",borderRadius:7,padding:"5px 8px"}}>
                        <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>{k}</div>
                        <div style={{fontSize:10,color:"#e2e4f0",fontWeight:700,marginTop:1,lineHeight:1.3}}>{v}</div>
                      </div>
                    ))}
                  </div>
                  <div style={{fontSize:10,color:"#60a5fa",fontWeight:700,textAlign:"center"}}>
                    {r.popularitas} {isSelected?"▲ Tutup":"▼ Detail"}
                  </div>

                  {/* Detail accordion */}
                  {isSelected && (
                    <div style={{marginTop:12,borderTop:"1px solid #252535",paddingTop:12}}>
                      {/* Warna */}
                      <div style={{fontSize:10,color:"#9097a8",marginBottom:10}}>
                        <span style={{color:"#555a6a",fontWeight:700}}>🎨 Warna/Ciri: </span>{r.warna}
                      </div>
                      {/* Keunggulan */}
                      <div style={{marginBottom:8}}>
                        <div style={{color:"#22c55e",fontWeight:700,fontSize:11,marginBottom:5}}>✅ Keunggulan</div>
                        {r.keunggulan.map((k,i)=>(
                          <div key={i} style={{background:"#22c55e0a",border:"1px solid #22c55e18",borderRadius:6,
                            padding:"5px 9px",marginBottom:4,fontSize:10,color:"#e2e4f0",display:"flex",gap:6}}>
                            <span style={{color:"#22c55e",flexShrink:0}}>+</span>{k}
                          </div>
                        ))}
                      </div>
                      {/* Kekurangan */}
                      <div style={{marginBottom:8}}>
                        <div style={{color:"#f59e0b",fontWeight:700,fontSize:11,marginBottom:5}}>⚠️ Kekurangan</div>
                        {r.kekurangan.map((k,i)=>(
                          <div key={i} style={{background:"#f59e0b0a",border:"1px solid #f59e0b18",borderRadius:6,
                            padding:"5px 9px",marginBottom:4,fontSize:10,color:"#e2e4f0",display:"flex",gap:6}}>
                            <span style={{color:"#f59e0b",flexShrink:0}}>−</span>{k}
                          </div>
                        ))}
                      </div>
                      {/* Catatan */}
                      <div style={{background:"#3b82f60a",border:"1px solid #3b82f620",borderRadius:7,padding:"7px 10px",fontSize:10,color:"#9097a8"}}>
                        <span style={{color:"#3b82f6",fontWeight:700}}>📌 </span>{r.catatan}
                      </div>
                      {/* Tombol tambah */}
                      <button onClick={e=>{e.stopPropagation();setForm({...blankForm,breed:nama});setEditId(null);setModal(true);setRasTab(false);}}
                        style={{marginTop:10,width:"100%",background:"#f5c84218",border:"1px solid #f5c84230",
                          borderRadius:8,padding:"7px",cursor:"pointer",color:"#f5c842",fontWeight:700,fontSize:11}}>
                        ➕ Tambah Sapi Ras {nama}
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
          {/* Tabel perbandingan ringkas */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:12}}>
              📊 Tabel Perbandingan Semua Ras Sapi
            </div>
            <div style={{overflowX:"auto"}}>
              <table style={{width:"100%",borderCollapse:"collapse",fontSize:11}}>
                <thead>
                  <tr style={{borderBottom:"2px solid #f5c84230",background:"#f5c84208"}}>
                    {["Ras","Asal","Tipe","BB Jantan","ADG","Harga Est.","Popularitas"].map(h=>(
                      <th key={h} style={{padding:"7px 10px",color:"#f5c842",textAlign:"left",fontSize:9,
                        fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap"}}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(RAS_SAPI).map(([nama,r],i)=>(
                    <tr key={nama} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff02":"transparent",
                      cursor:"pointer"}} onClick={()=>setSelectedRas(selectedRas===nama?null:nama)}>
                      <td style={{padding:"7px 10px",color:"#f5c842",fontWeight:700}}>{nama}</td>
                      <td style={{padding:"7px 10px",color:"#9097a8",fontSize:10}}>{r.asal?.split("(")[0].trim()}</td>
                      <td style={{padding:"7px 10px",color:"#e2e4f0",fontSize:10}}>{r.tipe}</td>
                      <td style={{padding:"7px 10px",color:"#22c55e",fontWeight:700}}>{r.bbDewasa?.jantan||"-"}</td>
                      <td style={{padding:"7px 10px",color:"#60a5fa"}}>{r.adg||r.produksiSusu||"-"}</td>
                      <td style={{padding:"7px 10px",color:"#f59e0b",fontSize:10}}>{r.harga||"-"}</td>
                      <td style={{padding:"7px 10px"}}>{r.popularitas}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ════ TAB DATA (default) ════ */}
      {(!rasTab) && (
      <div style={{display:"flex",flexDirection:"column",gap:14}}>
      {/* TOOLBAR */}
      <div style={{ ...S.row, justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
        <div style={{ ...S.row, flexWrap: "wrap", gap: 6 }}>
          <FilterBar active={filterStatus} items={["Semua", "Penggemukan", "Siap Jual", "Breeding", "Sakit"]} onChange={setFilterStatus} color={ac} />
          <Cari value={search} onChange={setSearch} placeholder={`Cari ${isDomba ? "domba" : "sapi"}...`} />
        </div>
        <BtnSec onClick={() => { setEditId(null); setForm(blankForm); setModal(true); }} color={ac}>
          <Ico n="plus" size={13} color={ac} /> Tambah {isDomba ? "Domba" : "Sapi"}
        </BtnSec>
      </div>

      {/* TABEL */}
      <TableWrap>
        <thead>
          <tr>
            {["ID", "Nama", "Ras", "JK", "Usia", "BB Beli", "BB Skrg", "ADG/hr", "Harga Beli", "Est. Nilai", "Profit", "Kdg", "Vaksin", "Status", "Kes.", "Aksi"].map(h => <TH key={h} color={ac}>{h}</TH>)}
          </tr>
        </thead>
        <tbody>
          {filtered.length === 0 ? <tr><td colSpan={16}><Empty /></td></tr> :
            filtered.map((a, i) => {
              const ev = nilaiEst(a); const pr = ev - a.priceBuy;
              return (
                <TR key={a.id} i={i} color={ac}>
                  <TD color={C.dim} mono>{a.id}</TD>
                  <td style={S.td}>
                    <button onClick={() => setDetail(a)} style={{ background: "none", border: "none", cursor: "pointer", color: C.text, fontWeight: 700, fontSize: 12, padding: 0, textDecoration: "underline", textDecorationColor: C.dim, textUnderlineOffset: 2 }}>{a.name}</button>
                  </td>
                  <TD color={C.muted}>{a.breed}</TD>
                  <td style={S.td}><Badge text={a.gender} /></td>
                  <TD color={C.dim}>{a.age}bln</TD>
                  <TD color={C.dim}>{a.weightBuy}kg</TD>
                  <TD bold>{a.weightCurrent}kg</TD>
                  <TD color={C.sell}>+{adg(a.weightCurrent, a.weightBuy, a.buyDate)}</TD>
                  <TD color={C.dim}>{rp(a.priceBuy)}</TD>
                  <TD color={C.info} bold>{rp(ev)}</TD>
                  <TD color={pr > 0 ? C.sell : C.expense} bold>{pr > 0 ? "+" : ""}{rp(pr)}</TD>
                  <TD color={C.muted}>{a.kandang || "-"}</TD>
                  <td style={S.td}><Badge text={a.vaksin || "Belum"} /></td>
                  <td style={S.td}><Badge text={a.status} /></td>
                  <td style={S.td}><Badge text={a.health} /></td>
                  <td style={S.td}>
                    <div style={S.row}>
                      <button onClick={() => setDetail(a)} style={{ background: C.info + "14", border: `1px solid ${C.info}25`, borderRadius: 6, padding: "4px 7px", cursor: "pointer", color: C.info }}><Ico n="eye" size={11} color={C.info} /></button>
                      <button onClick={() => openEdit(a)} style={{ background: C.info + "14", border: `1px solid ${C.info}25`, borderRadius: 6, padding: "4px 7px", cursor: "pointer", color: C.info }}><Ico n="edit" size={11} color={C.info} /></button>
                      <button onClick={() => del(a.id)} style={{ background: C.expense + "14", border: `1px solid ${C.expense}25`, borderRadius: 6, padding: "4px 7px", cursor: "pointer", color: C.expense }}><Ico n="del" size={11} color={C.expense} /></button>
                    </div>
                  </td>
                </TR>
              );
            })}
        </tbody>
      </TableWrap>

      {/* FORM MODAL */}
      {modal && (
        <Modal title={`${editId ? "Edit" : "Tambah"} ${isDomba ? "Domba" : "Sapi"}`} onClose={() => { setModal(false); setEditId(null); }}>
          <div style={S.grid2}>
            <Inp label="Nama Hewan" value={form.name} onChange={v => setForm({ ...form, name: v })} required />
            <Inp label="Ras" value={form.breed} onChange={v => setForm({ ...form, breed: v })} options={breedList} />
            <Inp label="Jenis Kelamin" value={form.gender} onChange={v => setForm({ ...form, gender: v })} options={["Jantan", "Betina"]} />
            <Inp label="Usia (bulan)" value={form.age} onChange={v => setForm({ ...form, age: v })} type="number" />
            <Inp label="BB Saat Beli (kg)" value={form.weightBuy} onChange={v => setForm({ ...form, weightBuy: v })} type="number" />
            <Inp label="BB Sekarang (kg)" value={form.weightCurrent} onChange={v => setForm({ ...form, weightCurrent: v })} type="number" />
            <Inp label="Harga Beli (Rp)" value={form.priceBuy} onChange={v => setForm({ ...form, priceBuy: v })} type="number" />
            <Inp label="Tanggal Beli" value={form.buyDate} onChange={v => setForm({ ...form, buyDate: v })} type="date" />
            <Inp label="Status" value={form.status} onChange={v => setForm({ ...form, status: v })} options={["Penggemukan", "Siap Jual", "Breeding", "Sakit", "Karantina", "Pejantan"]} />
            <Inp label="Kesehatan" value={form.health} onChange={v => setForm({ ...form, health: v })} options={["Sehat", "Sakit", "Pemulihan"]} />
            <Inp label="No. Kandang" value={form.kandang} onChange={v => setForm({ ...form, kandang: v })} placeholder="mis. A1" />
            <Inp label="Vaksinasi" value={form.vaksin} onChange={v => setForm({ ...form, vaksin: v })} options={["Lengkap", "Belum", "Sebagian"]} />
            <Inp label="Supplier / Asal" value={form.supplier} onChange={v => setForm({ ...form, supplier: v })} />
            <Inp label="Jenis Pakan" value={form.feedType} onChange={v => setForm({ ...form, feedType: v })} options={["Konsentrat+Hijauan", "Hijauan", "Konsentrat", "Mixed"]} />
            <Textarea label="Catatan" value={form.notes} onChange={v => setForm({ ...form, notes: v })} span />
          </div>
          {estP !== null && (
            <div style={{ marginTop: 14, background: C.sell + "0a", border: `1px solid ${C.sell}22`, borderRadius: 10, padding: 12, ...S.row, flexWrap: "wrap", gap: 16 }}>
              <span style={{ fontSize: 12, color: C.muted }}>Est. Nilai: <strong style={{ color: C.info }}>{rp(+form.weightCurrent * (HARGA_KG[form.breed] || 50000))}</strong></span>
              <span style={{ fontSize: 12, color: C.muted }}>Est. Profit: <strong style={{ color: estP > 0 ? C.sell : C.expense }}>{rp(estP)}</strong></span>
              <span style={{ fontSize: 12, color: C.muted }}>Harga Beli/kg: <strong style={{ color: ac }}>{form.weightBuy > 0 ? rp(Math.round(+form.priceBuy / +form.weightBuy)) : "-"}/kg</strong></span>
            </div>
          )}
          <BtnPrimary onClick={save} color={ac} full>Simpan Data</BtnPrimary>
        </Modal>
      )}
      </div>)} {/* end data tab */}

      {/* DETAIL POPUP */}
      {detail && (
        <Modal title={`Detail — ${detail.name}`} onClose={() => setDetail(null)} wide>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(160px,1fr))", gap: 10 }}>
            {[["ID", detail.id], ["Ras", detail.breed], ["Jenis Kelamin", detail.gender], ["Usia", detail.age + " bulan"], ["BB Beli", detail.weightBuy + " kg"], ["BB Sekarang", detail.weightCurrent + " kg"], ["Naik BB", `${detail.weightCurrent - detail.weightBuy} kg`], ["ADG", `+${adg(detail.weightCurrent, detail.weightBuy, detail.buyDate)} kg/hr`], ["Harga Beli", rp(detail.priceBuy)], ["Harga Beli/kg", rp(detail.weightBuy > 0 ? Math.round(detail.priceBuy / detail.weightBuy) : 0)], ["Est. Nilai Jual", rp(nilaiEst(detail))], ["Est. Profit", rp(nilaiEst(detail) - detail.priceBuy)], ["Tanggal Beli", detail.buyDate], ["Supplier", detail.supplier || "-"], ["No. Kandang", detail.kandang || "-"], ["Vaksinasi", detail.vaksin || "-"], ["Jenis Pakan", detail.feedType], ["Status", detail.status], ["Kesehatan", detail.health]].map(([k, v]) => (
              <InfoBox key={k} label={k} value={v} />
            ))}
          </div>
          {detail.notes && <div style={{ marginTop: 10, background: "#ffffff05", borderRadius: 9, padding: 12, color: C.muted, fontSize: 12 }}>📝 {detail.notes}</div>}
        </Modal>
      )}
    </div>
  );
};

/* ===== HALAMAN: PEMBELIAN ===== */
const PageBeli = ({ purchases=[], setPurchases, cattle=[], sheep=[], layerFlocks=[], broilerFlocks=[] }) => {
  const allA = [...cattle, ...sheep];
  const allAyam = [...(broilerFlocks||[]), ...(layerFlocks||[])];
  const blank = { animalId: "", animalName: "", animalType: "sapi", supplier: "", supplierPhone: "", date: todayStr(), weight: "", pricePerKg: "", totalPrice: "", payMethod: "Tunai", notes: "" };
  const [form, setForm] = useState(blank);
  const [modal, setModal] = useState(false);

  const total = purchases.reduce((s, p) => s + p.totalPrice, 0);
  const save = () => {
    const a = allA.find(x => x.id === form.animalId);
    const tot = form.totalPrice ? +form.totalPrice : +form.weight * +form.pricePerKg;
    setPurchases([{ id: newId("BL", purchases), ...form, weight: +form.weight, pricePerKg: +form.pricePerKg, totalPrice: tot, animalName: a ? a.name : form.animalName }, ...purchases]);
    setModal(false); setForm(blank);
  };
  return (
    <div style={S.col}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        <KartuStat label="Total Transaksi" value={purchases.length} color={C.buy} icon="beli" />
        <KartuStat label="Total Modal" value={rp(total)} color={C.expense} icon="chart" />
        <KartuStat label="Beli Sapi" value={purchases.filter(p => p.animalType === "sapi").length + " ekor"} color={C.sapi} icon="sapi" />
        <KartuStat label="Beli Domba" value={purchases.filter(p => p.animalType === "domba").length + " ekor"} color={C.domba} icon="domba" />
        <KartuStat label="Beli Broiler" value={purchases.filter(p => p.animalType === "broiler").length + " trx"} color="#e879f9" icon="broiler" />
        <KartuStat label="Beli Layer" value={purchases.filter(p => p.animalType === "petelur").length + " trx"} color="#f59e0b" icon="petelur" />
      </div>
      <div style={{ ...S.row, justifyContent: "flex-end" }}>
        <BtnSec onClick={() => setModal(true)} color={C.buy}><Ico n="plus" size={13} color={C.buy} /> Catat Pembelian</BtnSec>
      </div>
      <TableWrap>
        <thead><tr>{["ID", "Nama Hewan", "Jenis", "Supplier", "No.HP", "Tanggal", "BB", "Harga/kg", "Total", "Bayar", "Catatan"].map(h => <TH key={h} color={C.buy}>{h}</TH>)}</tr></thead>
        <tbody>
          {purchases.length === 0 ? <tr><td colSpan={11}><Empty /></td></tr> :
            purchases.map((p, i) => (
              <TR key={p.id} i={i} color={C.buy}>
                <TD color={C.dim} mono>{p.id}</TD>
                <TD bold>{p.animalName}</TD>
                <td style={S.td}><Badge text={p.animalType} /></td>
                <TD color={C.muted}>{p.supplier}</TD>
                <TD color={C.dim} mono>{p.supplierPhone || "-"}</TD>
                <TD color={C.dim}>{p.date}</TD>
                <TD>{p.weight}kg</TD>
                <TD>{rp(p.pricePerKg)}</TD>
                <TD color={C.buy} bold>{rp(p.totalPrice)}</TD>
                <td style={S.td}><Badge text={p.payMethod} /></td>
                <TD color={C.dim}>{p.notes || "-"}</TD>
              </TR>
            ))}
        </tbody>
      </TableWrap>
      {modal && (
        <Modal title="Catat Pembelian Hewan" onClose={() => setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Jenis Ternak" value={form.animalType} onChange={v => setForm({ ...form, animalType: v, animalId: "" })} options={[{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer/Petelur"}]} />
            <div>
              <label style={S.label}>Pilih Kandang/Hewan (opsional)</label>
              <select value={form.animalId} onChange={e => {
                const src = form.animalType==="sapi" ? cattle : form.animalType==="domba" ? sheep : form.animalType==="broiler" ? broilerFlocks : layerFlocks;
                const a = (src||[]).find(x => x.id === e.target.value);
                setForm({ ...form, animalId: e.target.value, animalName: a ? a.name : "" });
              }} style={S.select}>
                <option value="">-- Pilih atau ketik nama --</option>
                {(form.animalType==="sapi" ? cattle : form.animalType==="domba" ? sheep : form.animalType==="broiler" ? (broilerFlocks||[]) : (layerFlocks||[])).map(a => <option key={a.id} value={a.id}>{a.name} — {a.breed||a.type}</option>)}
              </select>
            </div>
            {!form.animalId && <Inp label="Nama / Keterangan" value={form.animalName} onChange={v => setForm({ ...form, animalName: v })} span />}
            <Inp label="Nama Supplier" value={form.supplier} onChange={v => setForm({ ...form, supplier: v })} required />
            <Inp label="No. HP Supplier" value={form.supplierPhone} onChange={v => setForm({ ...form, supplierPhone: v })} />
            <Inp label="Tanggal Beli" value={form.date} onChange={v => setForm({ ...form, date: v })} type="date" />
            <Inp label="Berat Timbang (kg)" value={form.weight} onChange={v => setForm({ ...form, weight: v })} type="number" />
            <Inp label="Harga per kg (Rp)" value={form.pricePerKg} onChange={v => setForm({ ...form, pricePerKg: v })} type="number" />
            <Inp label="Total Harga (Rp)" value={form.totalPrice} onChange={v => setForm({ ...form, totalPrice: v })} placeholder={form.weight && form.pricePerKg ? rp(+form.weight * +form.pricePerKg) : "Auto-hitung"} type="number" />
            <Inp label="Metode Bayar" value={form.payMethod} onChange={v => setForm({ ...form, payMethod: v })} options={["Tunai", "Transfer", "DP+Pelunasan", "Kredit"]} />
            <Textarea label="Catatan" value={form.notes} onChange={v => setForm({ ...form, notes: v })} span />
          </div>
          {form.weight && form.pricePerKg && <div style={{ marginTop: 12, background: C.buy + "0a", border: `1px solid ${C.buy}22`, borderRadius: 9, padding: 11, fontSize: 13, color: C.buy, fontWeight: 700 }}>Total: {rp(+form.weight * +form.pricePerKg)}</div>}
          <BtnPrimary onClick={save} color={C.buy} full>Simpan Pembelian</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ===== HALAMAN: PENJUALAN ===== */
const PageJual = ({ sales=[], setSales, cattle=[], sheep=[], layerFlocks=[], broilerFlocks=[] }) => {
  const allA = [...cattle, ...sheep];
  const allAyam = [...(broilerFlocks||[]), ...(layerFlocks||[])];
  const blank = { animalId: "", animalType: "sapi", buyer: "", buyerPhone: "", date: todayStr(), weight: "", pricePerKg: "", saleType: "Pasar", notes: "" };
  const [form, setForm] = useState(blank);
  const [modal, setModal] = useState(false);
  const [filterType, setFilterType] = useState("semua");
  const [search, setSearch] = useState("");

  const filtered = sales.filter(s => (filterType === "semua" || s.animalType === filterType) && (s.animalName.toLowerCase().includes(search.toLowerCase()) || s.buyer.toLowerCase().includes(search.toLowerCase())));
  const totalRev = sales.reduce((s, t) => s + t.totalPrice, 0);
  const totalProfit = sales.reduce((s, t) => s + t.profit, 0);
  const avgROI = sales.length > 0 ? ((totalProfit / sales.reduce((s, t) => s + t.buyPrice, 0)) * 100).toFixed(1) : "0";
  const siapSapi   = cattle.filter(c => c.status === "Siap Jual");
  const siapDomba  = sheep.filter(d => d.status === "Siap Jual");
  const siapBroiler = (broilerFlocks||[]).filter(f => f.status === "Siap Panen");

  const selectedAnimal = allA.find(a => a.id === form.animalId);
  const previewTotal = form.weight && form.pricePerKg ? +form.weight * +form.pricePerKg : 0;
  const previewProfit = selectedAnimal ? previewTotal - selectedAnimal.priceBuy : 0;

  const save = () => {
    const tot = +form.weight * +form.pricePerKg;
    const bp = selectedAnimal ? selectedAnimal.priceBuy : 0;
    setSales([{ id: newId("JL", sales), ...form, weight: +form.weight, pricePerKg: +form.pricePerKg, animalName: selectedAnimal ? selectedAnimal.name : "", totalPrice: tot, buyPrice: bp, profit: tot - bp }, ...sales]);
    setModal(false); setForm(blank);
  };
  return (
    <div style={S.col}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        <KartuStat label="Total Pendapatan" value={rp(totalRev)} color={C.info} icon="jual" />
        <KartuStat label="Total Profit" value={rp(totalProfit)} color={C.sell} icon="chart" />
        <KartuStat label="Avg ROI" value={avgROI + "%"} color={C.sapi} icon="laporan" />
        <KartuStat label="Jual Sapi" value={sales.filter(s => s.animalType === "sapi").length + " ekor"} color={C.sapi} icon="sapi" />
        <KartuStat label="Jual Domba" value={sales.filter(s => s.animalType === "domba").length + " ekor"} color={C.domba} icon="domba" />
        <KartuStat label="Jual Broiler" value={sales.filter(s => s.animalType === "broiler").length + " batch"} color="#e879f9" icon="broiler" />
        <KartuStat label="Jual Telur/Layer" value={sales.filter(s => s.animalType === "petelur").length + " trx"} color="#f59e0b" icon="petelur" />
      </div>

      {(siapSapi.length > 0 || siapDomba.length > 0 || siapBroiler.length > 0) && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(280px,1fr))", gap: 12 }}>
          {siapSapi.length > 0 && (
            <div style={{ background: C.sapi + "0a", border: `1px solid ${C.sapi}22`, borderRadius: 12, padding: 14 }}>
              <div style={{ color: C.sapi, fontWeight: 700, fontSize: 13, marginBottom: 8 }}>🐄 Sapi Siap Jual ({siapSapi.length})</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{siapSapi.map(c => <span key={c.id} style={{ background: C.sapi + "15", color: C.sapi, borderRadius: 7, padding: "4px 9px", fontSize: 11 }}>{c.name} — {c.weightCurrent}kg — {rp(nilaiEst(c))}</span>)}</div>
            </div>
          )}
          {siapDomba.length > 0 && (
            <div style={{ background: C.domba + "0a", border: `1px solid ${C.domba}22`, borderRadius: 12, padding: 14 }}>
              <div style={{ color: C.domba, fontWeight: 700, fontSize: 13, marginBottom: 8 }}>🐑 Domba Siap Jual ({siapDomba.length})</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{siapDomba.map(d => <span key={d.id} style={{ background: C.domba + "15", color: C.domba, borderRadius: 7, padding: "4px 9px", fontSize: 11 }}>{d.name} — {d.weightCurrent}kg — {rp(nilaiEst(d))}</span>)}</div>
            </div>
          )}
          {siapBroiler.length > 0 && (
            <div style={{ background: "#e879f90a", border: "1px solid #e879f922", borderRadius: 12, padding: 14 }}>
              <div style={{ color: "#e879f9", fontWeight: 700, fontSize: 13, marginBottom: 8 }}>🐔 Broiler Siap Panen ({siapBroiler.length} kandang)</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{siapBroiler.map(f => <span key={f.id} style={{ background: "#e879f915", color: "#e879f9", borderRadius: 7, padding: "4px 9px", fontSize: 11 }}>{f.name} — {f.jumlah.toLocaleString("id-ID")} ekor — {f.beratRata}kg/ekor</span>)}</div>
            </div>
          )}
        </div>
      )}

      <div style={{ ...S.row, justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
        <div style={{ ...S.row, flexWrap: "wrap", gap: 6 }}>
          <FilterBar active={filterType} items={[{ v: "semua", l: "Semua" }, { v: "sapi", l: "🐄 Sapi" }, { v: "domba", l: "🐑 Domba" }, { v: "broiler", l: "🐔 Broiler" }, { v: "petelur", l: "🥚 Layer" }]} onChange={setFilterType} color={C.sell} />
          <Cari value={search} onChange={setSearch} placeholder="Cari penjualan..." />
        </div>
        <BtnSec onClick={() => setModal(true)} color={C.sell}><Ico n="plus" size={13} color={C.sell} /> Catat Penjualan</BtnSec>
      </div>

      <TableWrap>
        <thead><tr>{["ID", "Nama Hewan", "Jenis", "Pembeli", "No.HP", "Tanggal", "BB", "Harga/kg", "Total Jual", "Harga Beli", "Profit", "ROI", "Tipe"].map(h => <TH key={h} color={C.sell}>{h}</TH>)}</tr></thead>
        <tbody>
          {filtered.length === 0 ? <tr><td colSpan={13}><Empty /></td></tr> :
            filtered.map((s, i) => {
              const roi = s.buyPrice > 0 ? ((s.profit / s.buyPrice) * 100).toFixed(1) : "0";
              return (
                <TR key={s.id} i={i} color={C.sell}>
                  <TD color={C.dim} mono>{s.id}</TD>
                  <TD bold>{s.animalName}</TD>
                  <td style={S.td}><Badge text={s.animalType} /></td>
                  <TD color={C.muted}>{s.buyer}</TD>
                  <TD color={C.dim} mono>{s.buyerPhone || "-"}</TD>
                  <TD color={C.dim}>{s.date}</TD>
                  <TD>{s.weight}kg</TD>
                  <TD>{rp(s.pricePerKg)}</TD>
                  <TD color={C.info} bold>{rp(s.totalPrice)}</TD>
                  <TD color={C.dim}>{rp(s.buyPrice)}</TD>
                  <TD color={C.sell} bold>+{rp(s.profit)}</TD>
                  <TD color={+roi >= 20 ? C.sell : C.buy} bold>{roi}%</TD>
                  <td style={S.td}><Badge text={s.saleType} /></td>
                </TR>
              );
            })}
        </tbody>
      </TableWrap>

      {modal && (
        <Modal title="Catat Penjualan Hewan" onClose={() => setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Jenis Ternak" value={form.animalType} onChange={v => setForm({ ...form, animalType: v, animalId: "" })} options={[{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer/Petelur"}]} />
            <div>
              <label style={S.label}>Pilih Kandang/Hewan</label>
              <select value={form.animalId} onChange={e => setForm({ ...form, animalId: e.target.value })} style={S.select}>
                <option value="">-- Pilih --</option>
                {(form.animalType==="sapi" ? cattle : form.animalType==="domba" ? sheep : form.animalType==="broiler" ? (broilerFlocks||[]) : (layerFlocks||[])).map(a => <option key={a.id} value={a.id}>{a.name} {a.breed ? "("+a.breed+")" : ""} — {a.weightCurrent ? a.weightCurrent+"kg" : a.jumlah ? a.jumlah.toLocaleString("id-ID")+" ekor" : ""}</option>)}
              </select>
            </div>
            <Inp label="Nama Pembeli" value={form.buyer} onChange={v => setForm({ ...form, buyer: v })} required />
            <Inp label="No. HP Pembeli" value={form.buyerPhone} onChange={v => setForm({ ...form, buyerPhone: v })} />
            <Inp label="Tanggal Jual" value={form.date} onChange={v => setForm({ ...form, date: v })} type="date" />
            <Inp label="Berat Timbang (kg)" value={form.weight} onChange={v => setForm({ ...form, weight: v })} type="number" />
            <Inp label="Harga per kg (Rp)" value={form.pricePerKg} onChange={v => setForm({ ...form, pricePerKg: v })} type="number" />
            <Inp label="Tipe Penjualan" value={form.saleType} onChange={v => setForm({ ...form, saleType: v })} options={["Pasar", "Jagal", "Perusahaan", "Pengepul", "Supermarket", "Pabrik", "Export", "BAZNAS", "Kurban", "Aqiqah", "Online"]} />
            <Textarea label="Catatan" value={form.notes} onChange={v => setForm({ ...form, notes: v })} span />
          </div>
          {previewTotal > 0 && (
            <div style={{ marginTop: 12, background: C.sell + "0a", border: `1px solid ${C.sell}22`, borderRadius: 9, padding: 12, ...S.row, flexWrap: "wrap", gap: 14 }}>
              <span style={{ fontSize: 12, color: C.muted }}>Total: <strong style={{ color: C.info }}>{rp(previewTotal)}</strong></span>
              {selectedAnimal && <>
                <span style={{ fontSize: 12, color: C.muted }}>Profit: <strong style={{ color: previewProfit > 0 ? C.sell : C.expense }}>{rp(previewProfit)}</strong></span>
                <span style={{ fontSize: 12, color: C.muted }}>ROI: <strong style={{ color: C.sapi }}>{selectedAnimal.priceBuy > 0 ? ((previewProfit / selectedAnimal.priceBuy) * 100).toFixed(1) : 0}%</strong></span>
              </>}
            </div>
          )}
          <BtnPrimary onClick={save} color={C.sell} full>Simpan Penjualan</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};


/* ================================================================
   STANDAR INDUSTRI — Formula CP & Japfa
================================================================ */
const STANDAR_INDUSTRI = {
  broiler: [
    {
      produk:"CP-510 (Pre-Starter Broiler)", produsen:"PT Charoen Pokphand Indonesia",
      kode:"CP-510 / Hi-Pro-Vite 510", fase:"Pre-Starter D1–D7", warna:"#e879f9",
      bentuk:"Crumble halus", target:"BB 170–200 g @D7 · FCR ≤1.10",
      nutrisi:[
        {label:"Metabolizable Energy (ME)",nilai:"Min. 3.100 kcal/kg",standar:"CP Spec 2024"},
        {label:"Protein Kasar (CP)",nilai:"Min. 23%",standar:"Label resmi CP-510"},
        {label:"Lysine Total",nilai:"Min. 1.50%",standar:"CP Technical Spec"},
        {label:"Methionine Total",nilai:"Min. 0.58%",standar:"CP Technical Spec"},
        {label:"Kalsium (Ca)",nilai:"0.90–1.10%",standar:"SNI + CP"},
        {label:"Fosfor (P)",nilai:"Min. 0.60%",standar:"CP"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI 3930"},
        {label:"Serat Kasar",nilai:"Maks. 4%",standar:"CP"},
        {label:"Abu",nilai:"Maks. 7%",standar:"CP"},
        {label:"Aflatoksin",nilai:"Maks. 50 μg/kg",standar:"SNI"},
      ],
      bahan:"Jagung, Bungkil Kedelai, Tepung Daging & Tulang (MBM), CGM (Corn Gluten Meal), DDGS, Pollard, CPO, Canola, DL-Methionine, L-Lysine, Vitamin, Enzim (Phytase), Kalsium, Fosfor, Trace Mineral",
      program:[
        "D1–D7: CP-510 (Pre-Starter) ad libitum — JANGAN batasi konsumsi",
        "Target konsumsi: 8–12 g/ekor D1 → 25–30 g/ekor D7",
        "Bentuk crumble halus — mudah dikonsumsi DOC",
        "Brooder suhu: 33–34°C minggu pertama",
        "Pencahayaan 23–24 jam/hari minggu pertama",
      ],
      harga:"Rp 9.500–11.000/kg (Harga Juni 2025)",
      catatan:"Mengandung coccidiostat (Nicarbazine/Salinomycin) — jangan campur pakan lain",
    },
    {
      produk:"CP-511 (Starter Broiler)", produsen:"PT Charoen Pokphand Indonesia",
      kode:"CP-511 / Hi-Pro-Vite 511B", fase:"Starter D1–D21 (atau D8–D21)", warna:"#c084fc",
      bentuk:"Crumble", target:"BB 800–950 g @D21 · FCR ≤1.30",
      nutrisi:[
        {label:"Metabolizable Energy (ME)",nilai:"Min. 3.050 kcal/kg",standar:"Label resmi CP-511"},
        {label:"Protein Kasar (CP)",nilai:"Min. 21–23%",standar:"Label + jurnal ilmiah Unila 2024"},
        {label:"Lysine Total",nilai:"Min. 1.35%",standar:"CP Spec"},
        {label:"Methionine+Cystine",nilai:"Min. 0.82%",standar:"CP Spec"},
        {label:"Kalsium (Ca)",nilai:"0.80–1.10%",standar:"Label CP-511"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"e-Katalog LKPP"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI 3930"},
        {label:"Lemak Kasar",nilai:"Min. 5%",standar:"Label CP-511"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"Label CP-511"},
        {label:"Abu",nilai:"Maks. 7%",standar:"Label CP-511"},
      ],
      bahan:"Jagung, Bungkil Kedelai, CGM, DDGS, Pollard/Dedak Gandum, MBM (Tepung Daging Tulang), CPO, Canola, Pecahan Gandum, Tepung Daun, DL-Methionine, L-Lysine, Vitamin (A/D3/E/K/B kompleks), Enzim Phytase, Kalsium, Fosfor, Trace Mineral",
      program:[
        "D1–D21: gunakan CP-511 (tanpa atau dengan CP-510 di D1–7)",
        "Target konsumsi kumulatif D21: ±1.050–1.100 g/ekor",
        "Ganti ke CP-512 saat ayam umur 22 hari",
        "Waktu makan: ad libitum (selalu tersedia)",
        "Cek uniformity flock setiap Sabtu — CV bobot <10% = target",
      ],
      harga:"Rp 8.500–9.500/kg (karung 50 kg ±Rp 425.000–475.000)",
      catatan:"CP-511B = versi tanpa AGP (Antibiotic Growth Promoter) sesuai regulasi 2023",
    },
    {
      produk:"CP-512 (Finisher Broiler)", produsen:"PT Charoen Pokphand Indonesia",
      kode:"CP-512 / Hi-Pro-Vite 512", fase:"Finisher D22–Panen", warna:"#a78bfa",
      bentuk:"Pellet 3mm", target:"BB 1.8–2.2 kg @D35 · FCR ≤1.65",
      nutrisi:[
        {label:"Metabolizable Energy (ME)",nilai:"Min. 3.100 kcal/kg",standar:"CP-512 Spec"},
        {label:"Protein Kasar (CP)",nilai:"Min. 19–20%",standar:"Label + jurnal 2024"},
        {label:"Lysine Total",nilai:"Min. 1.10%",standar:"CP Finisher Spec"},
        {label:"Methionine+Cystine",nilai:"Min. 0.75%",standar:"CP Spec"},
        {label:"Kalsium (Ca)",nilai:"0.80–1.00%",standar:"Label CP-512"},
        {label:"Fosfor (P)",nilai:"Min. 0.45%",standar:"CP"},
        {label:"Lemak Kasar",nilai:"Min. 5%",standar:"CP-512"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"CP-512"},
        {label:"Aflatoksin",nilai:"Maks. 50 μg/kg",standar:"SNI"},
      ],
      bahan:"Jagung (lebih banyak dari starter), Bungkil Kedelai (dikurangi), CGM, DDGS, MBM, CPO/Poultry Fat, Pollard, Canola, DL-Methionine, L-Lysine, Vitamin, Mineral, Antioksidan BHT/BHA",
      program:[
        "D22–panen: CP-512 (pellet) — FCR pellet lebih baik 5–8% vs crumble",
        "WITHDRAWAL: stop 5–7 hari sebelum panen (no antibiotic)",
        "Konsumsi harian D35: ±130–160 g/ekor",
        "Kepadatan kandang maks 12 ekor/m² untuk FCR optimal",
        "Program cahaya: 20 jam terang / 4 jam gelap untuk stimulasi makan",
      ],
      harga:"Rp 8.000–9.000/kg (karung 50 kg ±Rp 400.000–450.000)",
      catatan:"Tanpa coccidiostat — sudah withdrawal. Jika ada outbreak koksi, tangani terpisah",
    },
    {
      produk:"Comfeed BR-1 (Broiler Starter Japfa)", produsen:"PT Japfa Comfeed Indonesia Tbk",
      kode:"BR-1 / Broiler I Comfeed", fase:"Starter D1–D21", warna:"#f59e0b",
      bentuk:"Crumble", target:"BB 800–950 g @D21 · FCR ≤1.30",
      nutrisi:[
        {label:"Metabolizable Energy (ME)",nilai:"Min. 3.000 kcal/kg",standar:"Label resmi BR-1 Japfa"},
        {label:"Protein Kasar (CP)",nilai:"Min. 21%",standar:"e-Katalog LKPP + Tokopedia official"},
        {label:"Lemak Kasar",nilai:"Min. 5%",standar:"Label BR-1"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"Label BR-1"},
        {label:"Abu",nilai:"Maks. 7%",standar:"Label BR-1"},
        {label:"Kalsium (Ca)",nilai:"0.80–1.10%",standar:"Label BR-1"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"Label BR-1"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI 3930"},
        {label:"Aflatoksin",nilai:"Maks. 50 μg/kg",standar:"SNI"},
      ],
      bahan:"Jagung, Bungkil Kedelai (SBM), Pollard/Katul, CGM, DDGS, MBM, CPO, Canola, Coccidiostat, DL-Methionine, L-Lysine, L-Threonine, Vitamin kompleks, Mineral, Enzim Phytase, Xylanase",
      program:[
        "D1–D21: BR-1 (crumble) ad libitum",
        "Sama dengan program CP-511 — sering dipakai bergantian",
        "Pastikan penyimpanan di atas palet kayu, gudang kering, ventilasi baik",
        "Hindari penyimpanan >4 minggu setelah produksi",
        "Cocok untuk kemitraan Japfa (JAFARM) — otomatis tersuplai",
      ],
      harga:"Rp 8.200–9.200/kg (2025)",
      catatan:"Mengandung coccidiostat + antibiotik tertentu — patuhi withdrawal 5 hari",
    },
    {
      produk:"Comfeed BR-2 (Broiler Finisher Japfa)", produsen:"PT Japfa Comfeed Indonesia Tbk",
      kode:"BR-2 / Broiler II Comfeed", fase:"Finisher D22–Panen", warna:"#fbbf24",
      bentuk:"Pellet 3mm", target:"BB 1.8–2.5 kg @D35–42 · FCR ≤1.70",
      nutrisi:[
        {label:"Metabolizable Energy (ME)",nilai:"Min. 3.000 kcal/kg",standar:"Label BR-2 Japfa"},
        {label:"Protein Kasar (CP)",nilai:"Min. 20–22%",standar:"Jurnal Sains Peternakan UNS 2016"},
        {label:"Lemak Kasar",nilai:"Min. 5–6%",standar:"Label + Harga.web.id 2025"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"Label BR-2"},
        {label:"Kalsium (Ca)",nilai:"0.80–1.10%",standar:"Label"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"Label"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI"},
        {label:"Abu",nilai:"Maks. 7%",standar:"BR-2"},
        {label:"Aflatoksin",nilai:"Maks. 50 μg/kg",standar:"SNI"},
      ],
      bahan:"Jagung (ditingkatkan), Bungkil Kedelai (dikurangi), Poultry Fat, CGM, MBM, Pollard, Canola, DL-Methionine, L-Lysine, Vitamin, Mineral, Antioksidan, Formula Anti-Stres (varian BR-2 Super Pellet 2025)",
      program:[
        "D22–D35/42: BR-2 (pellet) ad libitum",
        "BR-2 Super Pellet (varian 2025) — formula anti-stres panas ekstrem",
        "Withdrawal 5 hari sebelum panen",
        "Efisiensi pellet vs crumble: hemat FCR 0.05–0.10",
        "Bobot panen target D35: 1.8–2.0 kg | D42: 2.2–2.5 kg",
      ],
      harga:"Rp 7.800–8.800/kg (2025)",
      catatan:"Versi baru 2025 bebas GMO tersedia — cocok untuk pasar premium organik",
    },
    {
      produk:"Wonokoyo BR-1 / Idaman Broiler Starter", produsen:"PT Wonokoyo Feedmill — Surabaya",
      kode:"Wonokoyo BR-1 Starter", fase:"Starter D1–D21", warna:"#c2410c",
      bentuk:"Crumble", target:"BB 800–950g @D21 · FCR ≤1.33",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 21–23%",standar:"Label Wonokoyo BR-1"},
        {label:"ME",nilai:"Min. 3.000 kcal/kg",standar:"Wonokoyo Spec"},
        {label:"Lemak Kasar",nilai:"Min. 4%",standar:"Label"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"Label"},
        {label:"Kalsium",nilai:"0.80–1.10%",standar:"Label Wonokoyo"},
        {label:"Fosfor",nilai:"Min. 0.50%",standar:"Label"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI"},
        {label:"Aflatoksin",nilai:"Maks. 50 ppb",standar:"SNI"},
      ],
      bahan:"Jagung, Bungkil Kedelai, Gluten Jagung, Dedak Padi, Minyak Kelapa Sawit, Tepung Daging & Tulang, Vitamin, Asam Amino Esensial, Mineral Premix, Coccidiostat",
      program:[
        "D1–D21: Wonokoyo BR-1 crumble ad libitum",
        "Performa setara CP-511 di lapangan — lebih terjangkau",
        "Sangat populer di Jawa Timur, Jawa Tengah",
        "Ganti ke BR-2 Wonokoyo saat umur 22 hari",
      ],
      harga:"Rp 7.800–8.800/kg (2025) — sedikit lebih murah dari CP/Japfa",
      catatan:"Wonokoyo = pemain besar ke-3 setelah CP & Japfa — populer di peternak mandiri Jawa",
    },
    {
      produk:"New Hope BR-1 Starter (Broiler)", produsen:"PT New Hope Indonesia",
      kode:"New Hope BR-1 Starter", fase:"Starter D1–D21", warna:"#1d4ed8",
      bentuk:"Crumble", target:"BB 850–950g @D21",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 21%",standar:"Label New Hope BR-1 (Jurnal JSTIP 2024)"},
        {label:"ME",nilai:"Min. 3.000 kcal/kg",standar:"New Hope Spec"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Lemak Kasar",nilai:"Min. 5%",standar:"New Hope"},
        {label:"Serat Kasar",nilai:"Maks. 5%",standar:"New Hope"},
        {label:"Kalsium",nilai:"0.80–1.10%",standar:"New Hope"},
        {label:"Fosfor",nilai:"Min. 0.50%",standar:"New Hope"},
      ],
      bahan:"Jagung, Bungkil Kedelai, Pollard, CGM, MBM, CPO, DL-Methionine, L-Lysine, Vitamin, Mineral, Coccidiostat, Enzim",
      program:[
        "Dipakai dalam penelitian JSTIP 2024 — performa baik",
        "Harga bersaing — alternatif CP/Japfa untuk peternak mandiri",
        "Tersedia di agen New Hope di seluruh Jawa",
      ],
      harga:"Rp 7.500–8.500/kg",
      catatan:"New Hope adalah grup pakan global asal China — masuk Indonesia 2000-an, kini jadi pemain signifikan",
    },
  ],
  layer: [
    {
      produk:"EH-701 (Layer Starter/Grower Japfa)", produsen:"PT Japfa Comfeed Indonesia Tbk",
      kode:"EH-701 / Egg Layer Starter", fase:"Starter Pullet 1–6 minggu", warna:"#f59e0b",
      bentuk:"Crumble / Pellet Kecil", target:"Kematangan seksual optimal · Bobot pullet seragam",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 20%",standar:"Japfa Layer Spec"},
        {label:"ME",nilai:"Min. 2.950 kcal/kg",standar:"Japfa"},
        {label:"Kalsium (Ca)",nilai:"0.80–1.20%",standar:"Fase pullet — Ca belum tinggi"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"Japfa"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Lysine Total",nilai:"Min. 1.00%",standar:"Japfa Spec"},
      ],
      bahan:"Jagung, SBM Full Fat, MBM, CGM, DDGS, Olein, Lysine, Methionine, Vitamin, Microtech 500, Yiduozyme, Kalsium, Fosfat",
      program:[
        "Minggu 1–6: EH-701 starter crumble ad libitum",
        "Target uniformity BW >80% pada minggu 8",
        "Suhu brooder: 33°C minggu 1 → turun 3°C/minggu",
        "Pencahayaan: 20–23 jam minggu 1, turun bertahap",
      ],
      harga:"Rp 8.000–9.000/kg",
      catatan:"Fase kritis — kesalahan nutrisi di sini berdampak produksi seumur hidup",
    },
    {
      produk:"EH-711 (Layer Peak Production Japfa)", produsen:"PT Japfa Comfeed Indonesia Tbk",
      kode:"EH-711 / Egg Layer Dewasa", fase:"Layer Dewasa ≥19 minggu (Peak Production)", warna:"#f97316",
      bentuk:"Mash / Pellet", target:"HDP ≥90% · Berat telur 60–65g · FCR ≤2.0",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 17%",standar:"Label resmi EH-711 Japfa"},
        {label:"ME",nilai:"Sesuai kebutuhan produksi",standar:"Japfa Layer Spec"},
        {label:"Lemak Kasar",nilai:"Min. 3%",standar:"Label EH-711"},
        {label:"Serat Kasar",nilai:"Maks. 7%",standar:"Label"},
        {label:"Abu",nilai:"Maks. 14%",standar:"Label EH-711"},
        {label:"Kalsium (Ca) — KRITIS",nilai:"3.25–4.25%",standar:"Label resmi EH-711 Japfa"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"Label"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Enzim Fitase",nilai:">400 FTU/kg",standar:"Label EH-711"},
        {label:"Aflatoksin",nilai:"Maks. 50 μg/kg",standar:"SNI"},
      ],
      bahan:"Jagung, SBM Full Fat, MBM, CGM, DDGS, Olein/CPO, Lysine HCl, Methionine, L-Threonine, Vitamin, Microtech 500 Minigranular, Yiduozyme P8601, Kalsium (oyster shell), Fosfat, Fitase",
      program:[
        "Umur ≥19 minggu: EH-711 Mash 100–115 g/ekor/hari",
        "KALSIUM KRITIS: tambah oyster shell kasar sore hari 5–10 g/ekor",
        "Air minum: min. 180–200 mL/ekor/hari (kekurangan = drop 10% dalam 24 jam)",
        "Program cahaya: WAJIB 16 jam minimal — kurang = stop produksi",
        "Suhu optimal: 18–24°C — ≥28°C cangkang menipis & produksi turun",
      ],
      harga:"Rp 7.000–8.000/kg (karung 50 kg ±Rp 350.000–400.000)",
      catatan:"Produk terlaris Japfa untuk layer komersial — tersedia di semua agen Japfa/Malindo",
    },
    {
      produk:"526 (Layer Mash CP)", produsen:"PT Charoen Pokphand Indonesia",
      kode:"CP-526 / Hi-Pro-Vite 526", fase:"Layer Peak Production", warna:"#f5c842",
      bentuk:"Mash", target:"HDP ≥92% · FCR ≤1.95",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 17%",standar:"CP Layer Spec"},
        {label:"ME",nilai:"Min. 2.750 kcal/kg",standar:"CP 526"},
        {label:"Kalsium (Ca)",nilai:"3.50–4.00%",standar:"CP Layer Spec"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"CP 526"},
        {label:"Lysine",nilai:"Min. 0.80%",standar:"CP Technical"},
        {label:"Methionine+Cystine",nilai:"Min. 0.58%",standar:"CP"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Serat Kasar",nilai:"Maks. 7%",standar:"CP-526"},
        {label:"Linoleic Acid",nilai:"Min. 1.20%",standar:"CP — kualitas telur"},
      ],
      bahan:"Jagung, Bungkil Kedelai, MBM, CGM, CPO/Olein, Limestone (kapur kasar), DCP, DL-Methionine, L-Lysine, Vitamin, Mineral, Phytase, Xanthophyll (pigmentor kuning)",
      program:[
        "Umur ≥18 minggu: CP-526 Mash 100–110 g/ekor/hari",
        "Timbang ayam setiap 2 minggu — jaga BCS optimal",
        "Vaksin AI H5N1 setiap 4–6 bulan — WAJIB",
        "Kandang tertutup (close house) optimalkan produksi CP-526",
      ],
      harga:"Rp 7.200–8.200/kg (2025)",
      catatan:"Tersedia versi 526L (Low Protein) untuk masa afkir dan 526P (Pre-lay 14–17 minggu)",
    },
    {
      produk:"Wonokoyo P-31 (Layer Mash Komplit)", produsen:"PT Wonokoyo Feedmill — Surabaya",
      kode:"Wonokoyo P-31 / Idaman Petelur", fase:"Layer Produksi ≥18 minggu", warna:"#b45309",
      bentuk:"Mash", target:"HDP >85% · Cangkang keras",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 16–17%",standar:"Label P-31 Wonokoyo"},
        {label:"Kalsium (Ca)",nilai:"3.50–4.00%",standar:"Label Wonokoyo"},
        {label:"Fosfor (P)",nilai:"Min. 0.50%",standar:"Label"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Lemak Kasar",nilai:"Min. 3%",standar:"Wonokoyo"},
        {label:"Serat Kasar",nilai:"Maks. 7%",standar:"Wonokoyo"},
        {label:"Aflatoksin",nilai:"Maks. 50 ppb",standar:"SNI"},
      ],
      bahan:"Jagung, Bungkil Kedelai, Gluten Jagung (CGM), Dedak Padi, Minyak Kelapa Sawit (CPO), Vitamin, Asam Amino Esensial, Mineral Premix, Kalsium (Limestone), Fosfat",
      program:[
        "Pakan komplit — langsung berikan tanpa campuran",
        "100–115 g/ekor/hari",
        "Harga lebih terjangkau dari CP/Japfa — cocok peternak mandiri",
        "Tersedia juga varian P-32 (layer dewasa usia lanjut) dan P-33 (afkir)",
        "Agen Wonokoyo tersebar di Jatim, Jateng, Jabar, Kalimantan",
      ],
      harga:"Rp 7.000–8.000/kg (karung 50 kg ±Rp 350.000–400.000)",
      catatan:"Merek kedua terbesar setelah CP/Japfa — sangat populer di Jawa Timur dan Jawa Tengah",
    },
    {
      produk:"New Hope L-83 (Layer Komplit)", produsen:"PT New Hope — Indonesia",
      kode:"New Hope L-83 / L-38-1", fase:"Layer ≥18 minggu sampai afkir", warna:"#0ea5e9",
      bentuk:"Mash", target:"HDP >87% · Berat telur 60–65g",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 17%",standar:"Label resmi New Hope L-83"},
        {label:"Kalsium (Ca)",nilai:"Min. 3.50%",standar:"Label + CekList.id 2025"},
        {label:"Fosfor (P)",nilai:"Min. 0.60%",standar:"Label New Hope"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
        {label:"Lemak Kasar",nilai:"Min. 3%",standar:"New Hope"},
        {label:"Urea",nilai:"Tidak terdeteksi",standar:"Label resmi — aman layer"},
      ],
      bahan:"Jagung, Dedak Padi, Bungkil Kedelai, Tepung Ikan, Tepung Daging & Tulang (MBM), Limestone, Vitamin Kompleks, Asam Amino, Mineral",
      program:[
        "Pakan komplit — langsung berikan ke ayam ≥18 minggu",
        "Tanpa urea — lebih aman dari risiko kematian mendadak",
        "Kaya kalsium dari MBM + tepung ikan — cangkang telur lebih tebal",
        "Cocok untuk Layer Lohmann Brown dan ISA Brown",
        "Formulasi khusus untuk awal bertelur (mulai umur 18 minggu)",
      ],
      harga:"Rp 7.500–8.500/kg (10 kg ±Rp 75.000–85.000 eceran)",
      catatan:"PT New Hope masuk Indonesia 2000-an — merek cukup populer di Jateng, DIY, sebagian Jabar",
    },
    {
      produk:"Farmsco Egg Max / Egg Pro (Layer Premium)", produsen:"PT Farmsco Feed Indonesia",
      kode:"Farmsco Egg Max / Egg Pro", fase:"Layer Peak Production & Late Lay", warna:"#7c3aed",
      bentuk:"Mash / Pellet", target:"HDP >92% · Kualitas telur premium",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 17–18%",standar:"Farmsco.co.id Layer Spec"},
        {label:"Kalsium (Ca)",nilai:"3.80–4.20%",standar:"Farmsco Egg Max Spec"},
        {label:"ME",nilai:"2.750–2.800 kcal/kg",standar:"Farmsco"},
        {label:"Lysine",nilai:"Min. 0.85%",standar:"Farmsco Layer"},
        {label:"Methionine+Cystine",nilai:"Min. 0.60%",standar:"Farmsco"},
        {label:"Fosfor",nilai:"Min. 0.45%",standar:"Farmsco"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
      ],
      bahan:"Jagung, SBM Full Fat, MBM, CGM, Limestone Kasar, CPO, DL-Methionine, L-Lysine, Phytase, Vitamin D3 tinggi, Mineral lengkap, Xanthophyll pigmentor",
      program:[
        "Lini lengkap: Hi-Pre Starter → Hi-Starter → Hi-Grower → Hi-Pullet → Hi-Shell → Egg Max → Egg Pro → Egg Plus → Egg Shell+ → KO Super 1 & 2",
        "Egg Max untuk peak production HDP >90%",
        "Egg Shell+ khusus untuk memperbaiki kualitas cangkang (Ca tinggi)",
        "KO Super 1 & 2 untuk fase afkir — efisiensi biaya",
        "Farmsco = merek Korea-Indonesia, kualitas premium, dipakai di farm besar",
      ],
      harga:"Rp 7.500–9.000/kg (premium)",
      catatan:"Tersedia di agen Farmsco — kontak: farmsco.co.id. Dipakai di farm layer besar Jawa Barat dan Jawa Tengah",
    },
    {
      produk:"Malindo K-36 Konsentrat Layer", produsen:"PT Malindo Feedmill Tbk",
      kode:"Malindo K-36 / K-34 / 7605", fase:"Konsentrat Layer ≥18 minggu sampai afkir", warna:"#ea580c",
      bentuk:"Konsentrat 35% + Jagung 50% + Dedak 15%", target:"HDP >88% · FCR ≤2.1",
      nutrisi:[
        {label:"Protein Kasar (K-36)",nilai:"36%",standar:"Label Malindo K-36 (konsentrat)"},
        {label:"Fosfor (K-36)",nilai:"1.0–1.5%",standar:"Label Malindo"},
        {label:"Aflatoksin",nilai:"Maks. 40 μg/kg",standar:"Label Malindo — lebih ketat dari SNI"},
        {label:"Catatan",nilai:"Protein ransum jadi ±17% setelah dicampur jagung+dedak",standar:"Hitungan praktis K-36"},
        {label:"Kalsium ransum",nilai:"±3.50%",standar:"Setelah mix standar Malindo"},
        {label:"Kadar Air",nilai:"Maks. 13%",standar:"SNI"},
      ],
      bahan:"Formula konsentrat: SBM, MBM, CGM, DDGS, Limestone, DCP, DL-Methionine, L-Lysine, Vitamin, Mineral, Phytase — dicampur dengan jagung+dedak oleh peternak",
      program:[
        "Formula campuran: Konsentrat K-36 35% + Jagung 50% + Dedak 15%",
        "Beli konsentrat K-36 dari agen Malindo, campurkan sendiri",
        "Biaya lebih hemat 15–25% vs pakan komplit",
        "K-34 protein lebih rendah dari K-36 — untuk fase late lay/afkir",
        "Pakan komplit 7605 tersedia jika tidak mau campur sendiri",
      ],
      harga:"Konsentrat K-36: Rp 9.000–11.000/kg → ransum jadi: Rp 6.500–7.500/kg",
      catatan:"Sistem konsentrat Malindo populer di Jatim dan Jabar — peternak bisa kontrol biaya lebih fleksibel",
    },
  ],
  sapi: [
    {
      produk:"Konsentrat Sapi Penggemukan Feedlot Grade A", produsen:"Standar Feedlot Nasional (PT Santori/GGL/Indo Prima Beef)",
      kode:"F9 / Grade A Beef Concentrate", fase:"Finisher Penggemukan (Grower → Finisher)", warna:"#f5c842",
      bentuk:"Pellet / Mash", target:"ADG 1.0–1.5 kg/hari · FCR 6–7",
      nutrisi:[
        {label:"Protein Kasar (CP)",nilai:"Min. 14–16%",standar:"SNI 3148-2:2017"},
        {label:"TDN (Total Digestible Nutrient)",nilai:"Min. 64–69%",standar:"SNI + Indo Prima Beef F9 Spec"},
        {label:"Serat Kasar",nilai:"Maks. 12–17%",standar:"SNI 3148-2"},
        {label:"Lemak Kasar",nilai:"Maks. 6%",standar:"SNI"},
        {label:"Abu",nilai:"Maks. 10%",standar:"SNI"},
        {label:"Kalsium (Ca)",nilai:"0.60–0.90%",standar:"NRC Beef 2016"},
        {label:"Fosfor (P)",nilai:"0.30–0.50%",standar:"NRC Beef 2016"},
        {label:"Kadar Air",nilai:"Maks. 14%",standar:"SNI 3148-2:2017"},
      ],
      bahan:"Jagung Giling (35–40%), Bungkil Kedelai/Canola (12–15%), Dedak Padi (10–15%), Pollard (8–12%), Molases (4–5%), Bungkil Kelapa (5–8%), Onggok (5–8%), Urea Feed Grade (0.5–1%), Kapur CaCO3 (1.5%), DCP (1%), Garam NaCl (0.5%), Premix Sapi (1%), NaHCO3/Buffer (1%), Antioksidan BHT",
      program:[
        "Hijauan 50–60% + Konsentrat 40–50% dari total DMI",
        "Dosis konsentrat: 4–6 kg/ekor/hari (tergantung BB 300–500 kg)",
        "Adaptasi pakan 14 hari: mulai 2 kg naik 0.5 kg per 3 hari",
        "Pemberian: 2× sehari (pagi 06.00 + sore 15.00)",
        "Air minum ad libitum — min. 30–50 L/ekor/hari",
        "Monitor BCS (Body Condition Score) setiap 2 minggu — target BCS 3.0–3.5",
      ],
      harga:"Rp 3.500–4.500/kg (formula mandiri) | Rp 5.000–6.500/kg (konsentrat pabrikan)",
      catatan:"Formula ini setara konsentrat yang dipakai PT Santori, GGL, Indo Prima Beef untuk feedlot komersial",
    },
    {
      produk:"Konsentrat Sapi Grower (F8) — Fase Pertumbuhan", produsen:"Standar Indo Prima Beef / Feedlot Nasional",
      kode:"F8 / Grower Concentrate", fase:"Grower (adaptasi – 3 bulan pertama)", warna:"#fbbf24",
      bentuk:"Mash / Pellet", target:"ADG 0.7–1.0 kg/hari · Adaptasi rumen",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 16–20%",standar:"Indo Prima Beef F8 Spec"},
        {label:"TDN",nilai:"Min. 63%",standar:"Indo Prima Beef F8"},
        {label:"Serat Kasar",nilai:"Maks. 17%",standar:"SNI grower"},
        {label:"Kalsium",nilai:"0.50–0.80%",standar:"NRC"},
        {label:"Fosfor",nilai:"0.30–0.45%",standar:"NRC"},
        {label:"Kadar Air",nilai:"Maks. 14%",standar:"SNI"},
      ],
      bahan:"Jagung Giling (30%), Bungkil Kedelai (15%), Dedak Padi (20%), Pollard (12%), Molases (5%), Bungkil Kelapa (8%), Urea (0.5%), DCP (1%), Kapur (1%), Garam (0.5%), Premix Sapi (1%)",
      program:[
        "Digunakan saat adaptasi awal (bakalan baru masuk)",
        "Protein lebih tinggi untuk pertumbuhan jaringan",
        "Setelah 3 bulan, beralih ke F9/Finisher untuk penggemukan",
        "Kombinasi dengan jerami fermentasi untuk serat rumen",
      ],
      harga:"Rp 3.000–4.000/kg formula mandiri",
      catatan:"Setelah grower 3 bulan, switch ke F9 Finisher untuk ADG maksimal",
    },
    {
      produk:"Nutrifeed BC-133 (Konsentrat Sapi Potong Rakyat)", produsen:"KJUB Puspetasari — Klaten / Cirebon / Magetan",
      kode:"Nutrifeed BC-133", fase:"Penggemukan & Perah Serbaguna", warna:"#d97706",
      bentuk:"Pellet/Mash 50kg/sak", target:"ADG 0.8–1.1 kg/hari · Produksi susu support",
      nutrisi:[
        {label:"Protein Kasar (CP)",nilai:"12–13%",standar:"Label resmi Nutrifeed BC-133"},
        {label:"TDN",nilai:"Min. 60%",standar:"Nutrifeed Spec — BC-131 s/d BC-134"},
        {label:"Lemak Kasar",nilai:"Maks. 7%",standar:"Lazada + Nutrifeed.co.id"},
        {label:"Kadar Air",nilai:"Maks. 14%",standar:"SNI 3148"},
        {label:"Serat Kasar",nilai:"Maks. 18%",standar:"Nutrifeed"},
        {label:"Kalsium (Ca)",nilai:"0.50–0.90%",standar:"Nutrifeed Spec"},
        {label:"Fosfor (P)",nilai:"Min. 0.30%",standar:"Nutrifeed"},
      ],
      bahan:"Wheat Pollard, Bungkil Kopra, Jagung Giling, Gaplek (Singkong Kering), Bungkil Sawit, Bekatul Halus, Kulit Kopi, Kulit Kacang Tanah, Dedak Kasar, Limbah Roti, Tetes Tebu (Molases), Probiotik, Garam, Mineral Premix — 18 bahan baku total berbasis limbah pertanian lokal",
      program:[
        "Dosis: 2% BB/hari = 5–8 kg/ekor/hari untuk sapi 250–400 kg",
        "Berikan 2–3× sehari sebelum hijauan diberikan",
        "Grade: BC-131 (CP 10–11%) | BC-132 (11–12%) | BC-133 (12–13%) | BC-134 (13–14%)",
        "BC-133/134 direkomendasikan untuk penggemukan intensif",
        "Cocok dicampur pollard untuk tingkatkan energi dan palatabilitas",
      ],
      harga:"Rp 2.800–3.500/kg (2025) — paling populer & terjangkau di peternak rakyat Jawa",
      catatan:"Produksi 150 ton/hari, jaringan luas di Jabar-Jateng-Jatim. Berdiri 1978. Cocok untuk peternak rakyat skala 5–50 ekor",
    },
    {
      produk:"Konsentrat Mandiri Self-Mix (Formula Peternak Rakyat)", produsen:"Kios Sapronak Lokal / Peternak Mandiri",
      kode:"Self-Mix / Voer Mandiri", fase:"Penggemukan & Laktasi — fleksibel", warna:"#92400e",
      bentuk:"Mash (campuran kering)", target:"ADG 0.7–1.0 kg/hari · Biaya pakan efisien",
      nutrisi:[
        {label:"Protein Kasar target",nilai:"14–16%",standar:"SNI 3148-2:2017 Penggemukan"},
        {label:"TDN target",nilai:"Min. 64–69%",standar:"SNI + NRC Beef 2016"},
        {label:"Serat Kasar",nilai:"Maks. 17%",standar:"SNI 3148-2"},
        {label:"Lemak Kasar",nilai:"Maks. 6%",standar:"SNI"},
        {label:"Kadar Air",nilai:"Maks. 12%",standar:"SNI"},
        {label:"Abu",nilai:"Maks. 10%",standar:"SNI"},
      ],
      bahan:"Jagung Giling 35% + Dedak Padi 18% + Pollard 10% + Bungkil Kedelai 12% + Onggok 8% + Bungkil Kelapa 8% + Molases 4% + CaCO3 1.5% + Garam 0.5% + Premix Mineral 1% + Urea Feed 0.5% + EM4 Peternakan (dosis air minum)",
      program:[
        "Formula paling umum dipakai peternak rakyat Tasikmalaya–Ciamis–Garut",
        "Beli bahan satuan di kios pertanian, campur sendiri dengan sekop",
        "Hemat 20–30% dibanding konsentrat pabrikan",
        "Tambahkan EM4 Peternakan 1mL/L air minum — efisiensi rumen meningkat 10–15%",
        "Simpan di gudang kering, konsumsi maksimal 2 minggu setelah campuran",
      ],
      harga:"Rp 2.500–3.200/kg (self-mix) vs Rp 3.500–5.000/kg konsentrat pabrikan",
      catatan:"⚠️ Cek kandungan nutrisi tiap batch jika bahan berubah. Gunakan kalkulator pakan atau konsultasi PPL",
    },
  ],
  domba: [
    {
      produk:"Konsentrat Domba Penggemukan Intensif", produsen:"Standar SNI + Penelitian BPTP Jabar",
      kode:"Domba Concentrate Grade A", fase:"Penggemukan 3–5 bulan", warna:"#a3e635",
      bentuk:"Mash / Pellet kecil", target:"ADG 150–200 g/hari · FCR 4–5",
      nutrisi:[
        {label:"Protein Kasar (CP)",nilai:"Min. 14–16%",standar:"SNI + NRC Small Ruminant 2007"},
        {label:"TDN",nilai:"Min. 65–70%",standar:"NRC SR 2007"},
        {label:"Serat Kasar",nilai:"Maks. 20%",standar:"SNI domba"},
        {label:"Lemak Kasar",nilai:"Maks. 6%",standar:"SNI"},
        {label:"Kalsium (Ca)",nilai:"0.40–0.70%",standar:"Ca:P = 1.5:1–2:1"},
        {label:"Tembaga (Cu) — KRITIS!",nilai:"Maks. 10–15 ppm",standar:"⚠️ Domba SANGAT sensitif Cu — overdosis fatal!"},
        {label:"Fosfor",nilai:"0.30–0.50%",standar:"NRC"},
        {label:"Kadar Air",nilai:"Maks. 14%",standar:"SNI"},
      ],
      bahan:"Jagung Giling (30–35%), Bungkil Kedelai (10–12%), Dedak Padi (15–20%), Pollard (10%), Onggok (8–10%), Bungkil Kelapa (8%), Molases (4%), Urea (0.5–0.7%), Kapur (1.5%), Garam (0.5%), Premix Domba Cu-rendah (1%), Sulfur Elemental (0.3%), Betaine (0.1%)",
      program:[
        "⚠️ WAJIB: Gunakan PREMIX DOMBA — JANGAN premix sapi (Cu terlalu tinggi)!",
        "Dosis: 1.5–2.5% BH/hari = 300–600 g/ekor/hari",
        "Hijauan 60% + Konsentrat 40% untuk penggemukan",
        "Air minum bersih ad libitum — min. 2–3 liter/ekor/hari",
        "Cek FAMACHA score tiap minggu untuk monitoring anemia cacing",
        "Monitor bobot setiap 2 minggu — target ADG 150–200 g/hari",
      ],
      harga:"Rp 2.800–3.800/kg formula mandiri",
      catatan:"Tidak ada merek komersial khusus domba sekelas CP/Japfa — peternak wajib buat sendiri atau beli dari koperasi",
    },
    {
      produk:"Nutrifeed Konsentrat Domba (Kambing)", produsen:"KJUB Puspetasari Klaten",
      kode:"Nutrifeed Domba/Kambing 30kg", fase:"Penggemukan & Induk Domba", warna:"#65a30d",
      bentuk:"Mash 30 kg/sak", target:"ADG 100–150 g/hari · Produksi susu kambing PE",
      nutrisi:[
        {label:"Protein Kasar",nilai:"Min. 12–14%",standar:"Label Nutrifeed Domba"},
        {label:"TDN",nilai:"Min. 55–62%",standar:"Nutrifeed Spec"},
        {label:"Serat Kasar",nilai:"Maks. 20%",standar:"SNI Domba"},
        {label:"Kalsium",nilai:"0.40–0.80%",standar:"NRC SR 2007"},
        {label:"Tembaga (Cu) — KRITIS",nilai:"Dikontrol rendah <12 ppm",standar:"⚠️ Formula domba aman Cu"},
        {label:"Kadar Air",nilai:"Maks. 14%",standar:"SNI"},
      ],
      bahan:"Dedak Halus, Onggok, Bungkil Kelapa, Pollard, Molases, Bungkil Kedelai, Garam, Kapur, Mineral Premix Domba (Cu-rendah), Probiotik",
      program:[
        "⚠️ Kemasan domba berbeda dari sapi — 30 kg/sak, JANGAN tukar!",
        "Dosis: 300–600 g/ekor/hari (1–2% BB domba 30–60 kg)",
        "Berikan sebelum hijauan — palatabilitas lebih baik",
        "Cocok untuk domba Garut, domba lokal, kambing PE",
        "Hubungi Nutrifeed (nutrifeed.co.id) untuk agen terdekat",
      ],
      harga:"Rp 3.000–3.800/kg (sak 30 kg)",
      catatan:"Satu-satunya merek pabrikan nasional yang punya lini khusus domba/kambing — Cu-rendah aman",
    },
    {
      produk:"Ampas Tahu + Dedak Self-Mix (Domba Rakyat)", produsen:"Peternak mandiri Jabar",
      kode:"Ampas Tahu Formula", fase:"Penggemukan Intensif Domba", warna:"#84cc16",
      bentuk:"Basah/comboran", target:"ADG 80–120 g/hari · Biaya sangat murah",
      nutrisi:[
        {label:"Protein Kasar (campuran)",nilai:"15–18%",standar:"Riset IPB — ampas tahu PK 25–30% + dedak 12%"},
        {label:"TDN campuran",nilai:"Est. 58–63%",standar:"Estimasi dari komposisi bahan"},
        {label:"Serat Kasar",nilai:"Est. 15–20%",standar:"Tergantung rasio hijauan"},
        {label:"Kalsium",nilai:"Est. 0.30–0.50%",standar:"Perlu tambah kapur"},
        {label:"Catatan Cu",nilai:"Tidak ada sumber Cu tinggi — aman domba",standar:"✅ Aman"},
      ],
      bahan:"Ampas Tahu Segar 60–70% + Dedak Halus 20–25% + Molases 5% + Kapur 1% + Garam 0.5% + Premix Vitamin/Mineral Domba (opsional)",
      program:[
        "Formula PALING POPULER peternak rakyat Tasikmalaya–Garut–Ciamis",
        "Ampas tahu: Rp 300–800/kg segar dari pabrik tahu lokal — sangat murah",
        "Berikan segar — tidak boleh disimpan >24 jam (fermentasi asam)",
        "Kombinasikan dengan rumput gajah/jerami fermentasi 60–70% dari total",
        "Tambah lamtoro kering 10–15% untuk boost protein (PK 23.7%)",
      ],
      harga:"Rp 500–800/kg total campuran — sangat ekonomis",
      catatan:"Riset IPB: Ampas tahu + konsentrat domba meningkatkan ADG 50–95 g/ekor/hari. Lokal, murah, mudah didapat",
    },
  ],
};


/* ================================================================
   PAKAN TRADISIONAL — Bahan & Kandungan Nutrisi
================================================================ */
const PAKAN_TRADISIONAL = {
  sapi: [
    {
      nama:"Jerami Padi (Mentah)", kode:"Hijauan Limbah Panen", warna:"#d97706",
      jenis:"Hijauan Sumber Serat", ketersediaan:"Sangat melimpah musim panen (Juni–Sep & Nov–Jan)",
      nutrisi:[
        {label:"Protein Kasar (PK)",nilai:"3–5%",ket:"Sangat rendah — tidak cukup untuk hidup pokok"},
        {label:"TDN",nilai:"40–44%",ket:"Rendah — energi tidak mencukupi"},
        {label:"Serat Kasar (SK)",nilai:"30–38%",ket:"Sangat tinggi — sulit dicerna tanpa fermentasi"},
        {label:"Bahan Kering (BK)",nilai:"84–87%",ket:"Kering — mudah disimpan"},
        {label:"NDF (serat dinding sel)",nilai:"73–78%",ket:"Tinggi lignin — batasi kecernaan"},
        {label:"Kalsium (Ca)",nilai:"0.20–0.32%",ket:"Cukup rendah"},
        {label:"Fosfor (P)",nilai:"0.08–0.12%",ket:"Sangat rendah — perlu suplementasi"},
      ],
      cara:"Berikan 10–15 kg/ekor/hari sebagai roughage. JANGAN jadikan pakan tunggal",
      tips:"Fermentasi dengan EM4 + molases = protein naik jadi 7–9%, kecernaan naik 20–30%. Wajib kombinasi konsentrat",
      biaya:"Gratis – Rp 200/kg (limbah)",
      rating:"⭐⭐ — Darurat & roughage only",
    },
    {
      nama:"Jerami Padi Fermentasi (Amoniasi / EM4)", kode:"Jerami Fermentasi", warna:"#f59e0b",
      jenis:"Hijauan Fermentasi Premium", ketersediaan:"Bisa dibuat sepanjang tahun dari jerami",
      nutrisi:[
        {label:"Protein Kasar",nilai:"7–10%",ket:"Naik signifikan dari 3–5% → 7–10% setelah fermentasi"},
        {label:"TDN",nilai:"50–58%",ket:"Naik dari 40% → 50–58% setelah fermentasi"},
        {label:"Serat Kasar",nilai:"24–28%",ket:"Turun — lignin terdegradasi mikroba"},
        {label:"Kecernaan BK",nilai:"55–65%",ket:"Naik 20–30% vs jerami mentah"},
        {label:"pH",nilai:"3.8–4.5",ket:"Asam laktat — awet 3–6 bulan"},
      ],
      cara:"Buat silase: jerami + EM4 0.5% + molases 3% + air → tutup kedap udara 21 hari",
      tips:"Riset Antonius (2009): jerami fermentasi bisa substitusi 35% rumput gajah tanpa turunkan performa sapi Simental",
      biaya:"Rp 400–800/kg (biaya EM4 + molases)",
      rating:"⭐⭐⭐⭐ — Sangat direkomendasikan",
    },
    {
      nama:"Rumput Gajah (Pennisetum purpureum)", kode:"Hijauan Segar Utama", warna:"#22c55e",
      jenis:"Hijauan Segar — Paling Populer", ketersediaan:"Panen tiap 40–60 hari, produktif 150 ton/ha/tahun",
      nutrisi:[
        {label:"Protein Kasar",nilai:"6–12%",ket:"Bervariasi: muda lebih tinggi dari tua"},
        {label:"TDN",nilai:"54–60%",ket:"Cukup untuk hidup pokok"},
        {label:"Serat Kasar",nilai:"28–35%",ket:"Moderat — baik untuk rumen"},
        {label:"Bahan Kering",nilai:"18–22%",ket:"Segar — air tinggi"},
        {label:"Kalsium (Ca)",nilai:"0.35–0.50%",ket:"Cukup"},
        {label:"Fosfor (P)",nilai:"0.22–0.35%",ket:"Cukup"},
      ],
      cara:"Berikan segar 30–40 kg/ekor/hari atau dijadikan silase. Panen saat tinggi 80–100cm",
      tips:"Tanam variasi: Rumput Gajah Odot (lebih tinggi protein 14%) lebih direkomendasikan untuk penggemukan intensif",
      biaya:"Rp 300–500/kg segar — atau GRATIS dari kebun sendiri",
      rating:"⭐⭐⭐⭐ — Hijauan terbaik lokal",
    },
    {
      nama:"Silase Jagung (Corn Silage)", kode:"Silase Jagung Utuh", warna:"#eab308",
      jenis:"Hijauan Premium Fermentasi", ketersediaan:"Musiman — panen jagung April–Mei & Sep–Okt",
      nutrisi:[
        {label:"Protein Kasar",nilai:"8–12%",ket:"Lebih tinggi dari jerami biasa"},
        {label:"TDN",nilai:"62–68%",ket:"Tinggi — energi untuk penggemukan"},
        {label:"Serat Kasar",nilai:"22–28%",ket:"Moderat"},
        {label:"Bahan Kering",nilai:"28–35%",ket:"Optimal untuk silase"},
        {label:"NDF",nilai:"45–55%",ket:"Lebih rendah dari jerami padi"},
        {label:"Pati (Starch)",nilai:"25–30%",ket:"Tinggi — energi cepat dari biji jagung"},
      ],
      cara:"Panen jagung umur 45–65 hari (tebon jagung), cacah, masukkan silo/drum kedap udara + molases 3%",
      tips:"Standar feedlot internasional — dipakai Santori, GGL. Peternak rakyat bisa buat skala kecil pakai drum 200L",
      biaya:"Rp 600–1.000/kg (biaya cacah + molases)",
      rating:"⭐⭐⭐⭐⭐ — Setara pakan feedlot",
    },
    {
      nama:"Gedebog / Batang Pisang", kode:"Limbah Kebun Pisang", warna:"#84cc16",
      jenis:"Pakan Darurat & Suplementasi", ketersediaan:"Melimpah di pedesaan Jawa — gratis",
      nutrisi:[
        {label:"Protein Kasar",nilai:"3.0–3.5%",ket:"Sangat rendah — bukan sumber protein"},
        {label:"Serat Kasar",nilai:"14–29%",ket:"Tinggi serat — kenyang tapi miskin nutrisi"},
        {label:"Bahan Kering",nilai:"87.7%",ket:"Riset Sapibagus & Goopo.id"},
        {label:"BETN",nilai:"28–29%",ket:"Sumber energi dari karbohidrat"},
        {label:"Abu",nilai:"25%",ket:"Tinggi — mengandung mineral K, Na"},
        {label:"Kadar Air batang segar",nilai:"90–95%",ket:"Sangat tinggi — cepat busuk"},
      ],
      cara:"Iris tipis, berikan segar max 5 kg/ekor atau fermentasi dalam drum kedap udara",
      tips:"⚠️ JANGAN jadikan pakan tunggal! Palatabilitas rendah. Fermentasi dulu untuk tingkatkan nilai nutrisi dan penerimaan sapi",
      biaya:"Gratis",
      rating:"⭐⭐ — Darurat saja",
    },
    {
      nama:"Daun Singkong + Kulit Singkong", kode:"Limbah Kebun Singkong", warna:"#10b981",
      jenis:"Sumber Protein Lokal", ketersediaan:"Melimpah di Jawa, Sumatera, Kalimantan",
      nutrisi:[
        {label:"Protein Kasar daun singkong",nilai:"8–10%",ket:"Cukup baik — setara rumput gajah"},
        {label:"Serat Kasar daun",nilai:"28–33%",ket:"Tinggi"},
        {label:"Bahan Kering daun",nilai:"20–22%",ket:"Segar"},
        {label:"Protein kulit singkong",nilai:"3–5%",ket:"Rendah — lebih ke sumber energi"},
        {label:"Asam Sianida (HCN)",nilai:"Ada — perlu dilayukan",ket:"⚠️ Layukan 24 jam sebelum diberikan!"},
        {label:"Kalsium",nilai:"0.50–0.70%",ket:"Cukup baik"},
      ],
      cara:"Daun singkong: layukan 24 jam, berikan 5–10 kg/ekor. Kulit singkong: keringkan jadi gaplek lalu giling",
      tips:"Onggok (ampas singkong kering) = sumber energi murah Rp 1.500–2.500/kg, TDN 68–72% — sering dipakai sebagai substitusi jagung",
      biaya:"Daun: gratis / Rp 500/kg. Onggok: Rp 1.500–2.500/kg kering",
      rating:"⭐⭐⭐ — Baik untuk suplementasi",
    },
    {
      nama:"Daun Lamtoro (Leucaena leucocephala)", kode:"Leguminosa Lokal", warna:"#06b6d4",
      jenis:"Sumber Protein Tinggi Lokal", ketersediaan:"Tumbuh liar di Jawa, NTB, NTT — ditanam pagar",
      nutrisi:[
        {label:"Protein Kasar",nilai:"20–27%",ket:"Sangat tinggi — setara bungkil kedelai!"},
        {label:"TDN",nilai:"65–72%",ket:"Tinggi — energi baik"},
        {label:"Serat Kasar",nilai:"14–18%",ket:"Moderat"},
        {label:"Kalsium (Ca)",nilai:"1.2–1.8%",ket:"Tinggi — sangat baik untuk tulang"},
        {label:"Fosfor (P)",nilai:"0.18–0.25%",ket:"Cukup"},
        {label:"Mimosin (antinutrisi)",nilai:"Ada",ket:"⚠️ Batasi max 30–40% ransum — overdosis = rambut rontok"},
      ],
      cara:"Berikan daun segar atau kering max 30–40% dari total ransum. Lebih dari itu menyebabkan mimosinosis",
      tips:"Peternak NTB/NTT pakai lamtoro sebagai 'pengganti bungkil kedelai lokal' — protein 20–27% jauh lebih tinggi dari rumput biasa",
      biaya:"Gratis jika tanam pagar kebun",
      rating:"⭐⭐⭐⭐ — Protein tinggi lokal",
    },
    {
      nama:"Gamal (Gliricidia sepium)", kode:"Leguminosa Pagar Hidup", warna:"#8b5cf6",
      jenis:"Hijauan Legum Protein Tinggi", ketersediaan:"Bisa ditanam sebagai pagar kandang",
      nutrisi:[
        {label:"Protein Kasar",nilai:"18–24%",ket:"Tinggi — sumber protein nabati lokal terbaik"},
        {label:"TDN",nilai:"60–67%",ket:"Energi cukup"},
        {label:"Serat Kasar",nilai:"14–18%",ket:"Moderat"},
        {label:"Kalsium",nilai:"1.4–1.8%",ket:"Sangat tinggi"},
        {label:"Tanin (antinutrisi)",nilai:"Ada",ket:"⚠️ Layukan atau panaskan sebentar sebelum diberikan"},
      ],
      cara:"Layukan 12–24 jam atau campurkan 20–30% dari total ransum hijauaan",
      tips:"Gamal + rumput gajah = kombinasi terbaik pengganti konsentrat mahal untuk sapi potong rakyat. Tanaman tahan kering",
      biaya:"Gratis (tanam pagar)",
      rating:"⭐⭐⭐⭐ — Sangat direkomendasikan",
    },
  ],
  domba: [
    {
      nama:"Rumput Lapangan / Rumput Liar", kode:"Hijauan Liar Gratis", warna:"#a3e635",
      jenis:"Hijauan Dasar Utama Domba", ketersediaan:"Melimpah di semua daerah — ngarit setiap hari",
      nutrisi:[
        {label:"Protein Kasar",nilai:"7–10%",ket:"Cukup untuk hidup pokok domba"},
        {label:"TDN",nilai:"50–58%",ket:"Moderat — cukup untuk pemeliharaan"},
        {label:"Serat Kasar",nilai:"25–35%",ket:"Tinggi — sesuai kapasitas rumen domba"},
        {label:"Bahan Kering",nilai:"18–25%",ket:"Segar"},
        {label:"Kalsium",nilai:"0.25–0.50%",ket:"Bervariasi per jenis rumput"},
      ],
      cara:"Ngarit pagi hari 1–2 kg/ekor/hari (BK). Berikan segar, jangan layu berlebihan",
      tips:"Domba lebih suka rumput yang beragam vs satu jenis. Rotasi padang rumput mengurangi beban cacing",
      biaya:"Gratis (tenaga ngarit saja)",
      rating:"⭐⭐⭐ — Cukup untuk pemeliharaan, tidak cukup untuk penggemukan",
    },
    {
      nama:"Daun Kaliandra (Calliandra calothyrsus)", kode:"Leguminosa Domba", warna:"#f43f5e",
      jenis:"Protein Tinggi Lokal Domba", ketersediaan:"Tumbuh di lahan kering dan pegunungan",
      nutrisi:[
        {label:"Protein Kasar",nilai:"18–23%",ket:"Tinggi — cocok untuk penggemukan domba"},
        {label:"TDN",nilai:"60–66%",ket:"Energi baik"},
        {label:"Tanin Kondensasi",nilai:"Ada",ket:"⚠️ Batasi 20–30% ransum — terlalu banyak hambat penyerapan protein"},
        {label:"Serat Kasar",nilai:"18–22%",ket:"Moderat"},
        {label:"Fosfor",nilai:"0.15–0.22%",ket:"Rendah — perlu suplementasi"},
      ],
      cara:"Berikan daun segar atau kering 20–30% dari total hijauan",
      tips:"Riset domba NTB: kaliandra + rumput setaria meningkatkan ADG 30–50% vs rumput biasa. Tahan kemarau",
      biaya:"Gratis (tanam lahan kering)",
      rating:"⭐⭐⭐⭐ — Terbaik untuk penggemukan domba lokal",
    },
    {
      nama:"Ampas Tahu Segar", kode:"Limbah Industri Tahu", warna:"#fbbf24",
      jenis:"Konsentrat Protein Basah Termurah", ketersediaan:"Sangat melimpah di Jawa — setiap kota ada pabrik tahu",
      nutrisi:[
        {label:"Protein Kasar",nilai:"25–30%",ket:"Sangat tinggi untuk harga sangat murah!"},
        {label:"TDN",nilai:"65–72%",ket:"Energi tinggi dari lemak kedelai"},
        {label:"Lemak Kasar",nilai:"10–15%",ket:"Tinggi dari minyak kedelai"},
        {label:"Serat Kasar",nilai:"15–20%",ket:"Moderat"},
        {label:"Kadar Air",nilai:"70–80%",ket:"Sangat tinggi — tidak tahan lama"},
        {label:"Protein setelah kering",nilai:"Est. 15–18%",ket:"Jika dikeringkan untuk disimpan"},
      ],
      cara:"Berikan segar max 1–2 kg/ekor/hari domba. Jangan simpan >24 jam (fermentasi asam)",
      tips:"Riset IPB: Ampas tahu 500g/hari + rumput gajah → ADG domba 50–95 g/ekor/hari. Formula paling ekonomis peternak Tasik-Garut",
      biaya:"Rp 300–800/kg segar — SANGAT MURAH",
      rating:"⭐⭐⭐⭐⭐ — Terbaik dari segi protein per rupiah",
    },
    {
      nama:"Kulit Kacang Tanah + Jerami Kacang", kode:"Limbah Panen Kacang", warna:"#78350f",
      jenis:"Hijauan Limbah Pertanian", ketersediaan:"Musiman — panen kacang Mei–Jul & Nov–Jan",
      nutrisi:[
        {label:"Protein Kasar jerami kacang",nilai:"12–17%",ket:"Cukup baik untuk leguminosa"},
        {label:"TDN",nilai:"55–65%",ket:"Cukup"},
        {label:"Serat Kasar",nilai:"25–35%",ket:"Moderat"},
        {label:"Kalsium",nilai:"0.8–1.5%",ket:"Tinggi — baik untuk domba"},
      ],
      cara:"Berikan kering 1–2 kg/ekor atau campuran dengan rumput lapangan",
      tips:"Musim kacang = stok jerami kacang untuk cadangan kemarau. Protein lebih tinggi dari jerami padi",
      biaya:"Rp 500–1.000/kg kering",
      rating:"⭐⭐⭐ — Baik saat musim panen kacang",
    },
  ],
  broiler: [
    {
      nama:"Bekatul / Dedak Padi Halus", kode:"Dedak Lokal", warna:"#e879f9",
      jenis:"Energi + Serat Lokal Paling Umum", ketersediaan:"Sangat melimpah — ada di setiap kios pertanian",
      nutrisi:[
        {label:"Protein Kasar",nilai:"11–14%",ket:"Cukup sebagai pelengkap"},
        {label:"ME (Energi Metabolis)",nilai:"1.900–2.300 kcal/kg",ket:"Lebih rendah dari jagung"},
        {label:"Serat Kasar",nilai:"8–12%",ket:"Tinggi — batasi max 10–15% ransum broiler"},
        {label:"Lemak Kasar",nilai:"6–10%",ket:"Tinggi — mengandung vitamin E"},
        {label:"Asam amino",nilai:"Lisin 0.5%, Met 0.2%",ket:"Tidak seimbang — perlu suplementasi"},
        {label:"Vitamin B kompleks",nilai:"Tinggi",ket:"B1, B2, B3, B6 — paling kaya"},
      ],
      cara:"Campurkan 10–15% dalam ransum broiler starter, max 20% di finisher",
      tips:"Batasi penggunaan karena serat tinggi menurunkan FCR. Kualitas bervariasi — pilih dedak halus dari penggilingan modern",
      biaya:"Rp 3.000–4.000/kg",
      rating:"⭐⭐⭐ — Bahan pelengkap ekonomis",
    },
    {
      nama:"Jagung Giling + Bekatul (Formula Rakyat)", kode:"Ransum Dasar Tradisional", warna:"#f59e0b",
      jenis:"Ransum Dasar Peternak Mandiri", ketersediaan:"Selalu tersedia di kios pertanian",
      nutrisi:[
        {label:"Protein Kasar campuran",nilai:"11–14%",ket:"Jagung 8.5% + Bekatul 12% → rata 10–13%"},
        {label:"ME campuran",nilai:"2.800–3.000 kcal/kg",ket:"Jagung tinggi energi 3.300 kcal — didominasi jagung"},
        {label:"Serat Kasar",nilai:"5–8%",ket:"Tergantung rasio jagung:bekatul"},
        {label:"Kekurangan",nilai:"Protein rendah, AA tidak seimbang",ket:"Perlu tambah tepung ikan atau ampas tahu"},
      ],
      cara:"Formula dasar: Jagung 60–70% + Bekatul 20–30% + Tepung Ikan 5–10%",
      tips:"Formula rakyat ini bisa ditingkatkan: tambahkan konsentrat 30% CP/Japfa sebagai pelengkap protein dan mineral",
      biaya:"Rp 4.500–5.500/kg campuran",
      rating:"⭐⭐⭐ — Perlu ditambah sumber protein",
    },
    {
      nama:"Maggot BSF (Black Soldier Fly Larvae)", kode:"Maggot Segar / Kering", warna:"#a78bfa",
      jenis:"Protein Hewani Premium Lokal", ketersediaan:"Bisa dibudidayakan sendiri dari sampah organik",
      nutrisi:[
        {label:"Protein Kasar (kering)",nilai:"40–45%",ket:"Sangat tinggi — setara tepung ikan!"},
        {label:"Lemak Kasar (kering)",nilai:"28–35%",ket:"Tinggi — sumber energi padat"},
        {label:"Asam Amino",nilai:"Lengkap esensial",ket:"Lisin, Met, Treonin, Arginin lengkap"},
        {label:"Kalsium",nilai:"5–8%",ket:"Sangat tinggi dari kulit chitin"},
        {label:"Fosfor",nilai:"0.6–1.2%",ket:"Cukup"},
        {label:"Protein Kasar (segar)",nilai:"14–17%",ket:"Segar — kadar air tinggi"},
      ],
      cara:"Berikan segar 5–10% ransum atau kering 5–8% campuran. Budidaya dari sampah dapur/limbah organik",
      tips:"Laporan Liputan6 2026: Maggot BSF = solusi pakan protein murah untuk broiler mandiri. ROI budidaya maggot 6–8 bulan",
      biaya:"Budidaya mandiri: Rp 2.000–5.000/kg segar. Beli jadi: Rp 8.000–15.000/kg kering",
      rating:"⭐⭐⭐⭐⭐ — Revolusi protein pakan unggas lokal",
    },
    {
      nama:"Cacing Tanah (Lumbricus rubellus)", kode:"Protein Hewani Tradisional", warna:"#92400e",
      jenis:"Sumber Protein Hewani Tradisional", ketersediaan:"Bisa dibudidaya / cari di lahan pertanian",
      nutrisi:[
        {label:"Protein Kasar",nilai:"60–72%",ket:"Sangat tinggi — TERTINGGI protein hewani lokal"},
        {label:"Lemak Kasar",nilai:"7–10%",ket:"Moderat"},
        {label:"Asam Amino",nilai:"Lengkap + Arakidonat",ket:"AA esensial sangat lengkap"},
        {label:"Mineral",nilai:"Fe, Zn, Ca tinggi",ket:"Mineral mikro sangat kaya"},
      ],
      cara:"Berikan segar 2–5 ekor/ayam/hari atau kering dicampur ransum max 5%",
      tips:"Cara tradisional peternak kampung — tapi susah didapat dalam jumlah besar. Maggot BSF lebih praktis untuk skala komersial",
      biaya:"Budidaya vermikompos: Rp 5.000–10.000/kg",
      rating:"⭐⭐⭐⭐ — Bergizi tinggi, tapi sulit skala besar",
    },
    {
      nama:"Nasi Aking + Sisa Dapur", kode:"Limbah Dapur", warna:"#6b7280",
      jenis:"Pakan Darurat / Subsisten", ketersediaan:"Tersedia di rumah tangga pedesaan",
      nutrisi:[
        {label:"Protein Kasar nasi",nilai:"6–8%",ket:"Rendah — sumber karbohidrat utama"},
        {label:"ME nasi aking",nilai:"3.000–3.200 kcal/kg",ket:"Tinggi energi dari pati nasi kering"},
        {label:"Serat Kasar",nilai:"1–3%",ket:"Sangat rendah"},
        {label:"Vitamin",nilai:"Sangat rendah",ket:"Perlu suplementasi vitamin"},
      ],
      cara:"Campurkan 20–40% dalam ransum sebagai pengganti jagung darurat. Keringkan dulu sebelum disimpan",
      tips:"Kandang Gadri formula: 60% karbohidrat (nasi aking+jagung) + 20% protein + 20% hijauan — cocok untuk peternak subsisten",
      biaya:"Gratis dari sisa dapur",
      rating:"⭐⭐ — Darurat saja, nutrisi tidak seimbang",
    },
  ],
  petelur: [
    {
      nama:"Kulit Kerang / Cangkang Telur (Oyster Shell)", kode:"Sumber Kalsium Alami", warna:"#f59e0b",
      jenis:"Suplementasi Kalsium Wajib", ketersediaan:"Tersedia di kios pakan, warung nelayan, pabrik tahu",
      nutrisi:[
        {label:"Kalsium (Ca)",nilai:"36–38%",ket:"SANGAT TINGGI — sumber Ca terbaik untuk cangkang telur"},
        {label:"Protein",nilai:"Sangat rendah",ket:"Bukan sumber protein"},
        {label:"Ketersediaan Ca biologis",nilai:"90–95%",ket:"Sangat mudah diserap — lebih baik dari kapur halus"},
        {label:"Ukuran partikel",nilai:"2–4 mm",ket:"Kasar = lambat larut = Ca tersedia malam hari saat shell formation"},
      ],
      cara:"Berikan free-choice (bebas pilih) terpisah ATAU campurkan 4–5% ransum (kasar). Berikan sore hari",
      tips:"⚠️ WAJIB untuk layer! Kekurangan Ca = cangkang lembek dan osteoporosis ayam. Lebih efektif dari kapur biasa karena slow-release",
      biaya:"Rp 500–1.500/kg",
      rating:"⭐⭐⭐⭐⭐ — Wajib ada di kandang layer",
    },
    {
      nama:"Tepung Ikan Lokal (Ikan Rucah)", kode:"Tepung Ikan Buatan Sendiri", warna:"#0ea5e9",
      jenis:"Sumber Protein Hewani Premium", ketersediaan:"Bisa dibuat dari ikan segar/rucah — nelayan lokal",
      nutrisi:[
        {label:"Protein Kasar",nilai:"55–65%",ket:"Tinggi — tergantung jenis ikan dan proses"},
        {label:"Lysine",nilai:"4–5%",ket:"Asam amino #1 yang dibutuhkan layer"},
        {label:"Methionine",nilai:"1.5–2.0%",ket:"AA untuk kualitas telur"},
        {label:"Kalsium",nilai:"4–8%",ket:"Tinggi dari tulang ikan"},
        {label:"Fosfor",nilai:"2–3%",ket:"Tersedia tinggi"},
        {label:"Energi (ME)",nilai:"2.800–3.000 kcal/kg",ket:"Tinggi"},
      ],
      cara:"Campurkan 5–8% dalam ransum layer. Bisa buat sendiri: rebus ikan + keringkan + giling",
      tips:"Peternak Tasikmalaya sering pakai ikan asin murah giling sebagai sumber protein pengganti konsentrat mahal",
      biaya:"Tepung ikan komersial: Rp 15.000–20.000/kg. Buat sendiri: Rp 8.000–12.000/kg",
      rating:"⭐⭐⭐⭐ — Protein terbaik untuk kualitas telur",
    },
    {
      nama:"Dedak Padi + Jagung + Kulit Kerang (Formula Peternak Rakyat)", kode:"Ransum Layer Mandiri", warna:"#f97316",
      jenis:"Ransum Komplit Tradisional Layer", ketersediaan:"Semua bahan mudah didapat di kios pertanian",
      nutrisi:[
        {label:"Protein campuran",nilai:"14–16%",ket:"Jagung 8.5% + Dedak 12% + Tepung Ikan 55% → rata 14–16%"},
        {label:"ME campuran",nilai:"2.600–2.800 kcal/kg",ket:"Cukup untuk produksi telur"},
        {label:"Kalsium (dengan kulit kerang)",nilai:"3.0–3.5%",ket:"Kulit kerang 5% → Ca cukup untuk cangkang"},
        {label:"Fosfor",nilai:"0.45–0.55%",ket:"Cukup dari dedak + tepung ikan"},
        {label:"Serat Kasar",nilai:"6–9%",ket:"Moderat"},
      ],
      cara:"Formula: Jagung 50% + Dedak 20% + Tepung Ikan 7% + Konsentrat CP/Japfa 15% + Kulit Kerang 5% + Garam 0.5% + Premix 0.5%",
      tips:"Formula paling sering dipakai peternak mandiri layer Jawa Barat — hemat 20–30% vs pakan komplit. Produksi HDP bisa 80–87%",
      biaya:"Rp 5.500–6.500/kg campuran (vs Rp 7.000–8.000/kg pakan komplit)",
      rating:"⭐⭐⭐⭐ — Cost-effective untuk peternak mandiri",
    },
    {
      nama:"Daun Pepaya (Carica papaya)", kode:"Jamu Layer Tradisional", warna:"#22c55e",
      jenis:"Suplemen Herbal Nafsu Makan", ketersediaan:"Sangat melimpah di seluruh Indonesia",
      nutrisi:[
        {label:"Protein Kasar",nilai:"18–22%",ket:"Tinggi — tapi ada enzim papain"},
        {label:"Vitamin A (β-karoten)",nilai:"Sangat tinggi",ket:"Pigmentor alami — kuning telur lebih pekat"},
        {label:"Vitamin C",nilai:"Tinggi",ket:"Antioksidan — daya tahan penyakit"},
        {label:"Enzim Papain",nilai:"Ada",ket:"Membantu pencernaan protein dan cegah cacingan"},
        {label:"Tanin",nilai:"Ada sedikit",ket:"Batasi max 5–10% ransum"},
      ],
      cara:"Cincang halus 50–100g/ekor/hari atau rebus sebentar dan campur ransum",
      tips:"Peternak tradisional Jawa: daun pepaya = 'jamu wajib' untuk layer agar produksi stabil dan ayam sehat. Kuning telur lebih pekat jika rutin diberi",
      biaya:"Gratis dari pohon pepaya",
      rating:"⭐⭐⭐⭐ — Suplemen herbal terbaik untuk layer",
    },
    {
      nama:"Kunyit + Jahe + Temulawak (Jamu Unggas)", kode:"Herbal Imunomodulator", warna:"#f5c842",
      jenis:"Suplemen Herbal Anti-Stres", ketersediaan:"Sangat melimpah di Jawa — harga murah",
      nutrisi:[
        {label:"Kurkumin (Kunyit)",nilai:"2–5% dalam rimpang",ket:"Anti-inflamasi + imunomodulator + antimikroba"},
        {label:"Gingerol (Jahe)",nilai:"Ada",ket:"Anti-inflamasi + nafsu makan + anti-Mycoplasma"},
        {label:"Xanthorrhizol (Temulawak)",nilai:"Ada",ket:"Hepatoprotektif + imunomodulator"},
        {label:"Minyak Atsiri",nilai:"1–3%",ket:"Antibakteri alami"},
        {label:"Mineral & Vitamin",nilai:"Beragam",ket:"Mineral mikro + vit B kompleks"},
      ],
      cara:"Rebus 200g kunyit + 100g jahe + 100g temulawak / 10L air, saring, campurkan ke air minum 2–3× seminggu",
      tips:"Riset IPB: jamu kunyit-temulawak 0.5% ransum meningkatkan HDP 3–5% dan mengurangi FCR 0.05–0.10 pada layer komersial",
      biaya:"Rp 500–1.500/L jamu jadi",
      rating:"⭐⭐⭐⭐ — Pengganti antibiotik alami paling terbukti",
    },
  ],
};

/* ===== DATA RACIKAN PAKAN ===== */
const RACIKAN_PAKAN = {
  sapi: [
    {
      nama: "Konsentrat Sapi Penggemukan (Grade A)", fase: "Penggemukan 6–12 bln",
      target: "ADG 1.0–1.2 kg/hari · FCR 6–7", color: "#f5c842",
      ket: "Formula setara Charoen CP / Japfa untuk sapi feedlot komersial",
      nutrisi: [
        {label:"Protein Kasar (CP)",nilai:"14–16%",ideal:"15%",benchmark:"SNI 3148-1:2019"},
        {label:"TDN (Total Digestible Nutrients)",nilai:"68–72%",ideal:"70%",benchmark:"NRC 2016"},
        {label:"Serat Kasar (CF)",nilai:"<18%",ideal:"15%",benchmark:"Maks 20%"},
        {label:"Lemak Kasar (EE)",nilai:"3–5%",ideal:"4%",benchmark:"Maks 6%"},
        {label:"Abu (Ash)",nilai:"<10%",ideal:"8%",benchmark:"Maks 12%"},
        {label:"Kalsium (Ca)",nilai:"0.6–0.9%",ideal:"0.7%",benchmark:"NRC"},
        {label:"Fosfor (P)",nilai:"0.3–0.5%",ideal:"0.4%",benchmark:"NRC"},
        {label:"Kadar Air",nilai:"<14%",ideal:"12%",benchmark:"SNI"},
      ],
      bahan: [
        {bahan:"Jagung Kuning Giling",pct:40,harga:5500,fungsi:"Sumber energi utama, pati tinggi"},
        {bahan:"Bungkil Kedelai (SBM 48%)",pct:15,harga:9000,fungsi:"Protein bypass rumen terbaik"},
        {bahan:"Dedak Padi Halus",pct:12,harga:3200,fungsi:"Sumber energi + serat fermentasi"},
        {bahan:"Molases (Tetes Tebu)",pct:5,harga:2500,fungsi:"Palatabilitas + energi cepat"},
        {bahan:"Pollard (Wheat Bran)",pct:10,harga:4800,fungsi:"Sumber serat + protein backup"},
        {bahan:"Bungkil Kelapa",pct:8,harga:4000,fungsi:"Energi + protein nabati lokal"},
        {bahan:"Urea Feed Grade (46%N)",pct:1,harga:6500,fungsi:"NPN — sumber N rumen (max 1%)"},
        {bahan:"Tepung Ikan 65%",pct:3,harga:18000,fungsi:"Protein bypass berkualitas tinggi"},
        {bahan:"Kapur / CaCO₃",pct:1.5,harga:800,fungsi:"Kalsium — kesehatan tulang & otot"},
        {bahan:"Dikalsium Fosfat (DCP)",pct:1,harga:12000,fungsi:"Ca + P tersedia — mineral kritis"},
        {bahan:"Garam Dapur (NaCl)",pct:0.5,harga:2000,fungsi:"Elektrolit — nafsu makan"},
        {bahan:"Premix Sapi (Vit+Min)",pct:1,harga:45000,fungsi:"Vit A/D/E, Cu, Zn, Se, Co, I"},
        {bahan:"Bicarbonat (NaHCO₃)",pct:1,harga:8000,fungsi:"Buffer rumen — cegah asidosis"},
        {bahan:"Antioksidan BHT",pct:0.05,harga:80000,fungsi:"Stabilitas lemak — shelf life"},
        {bahan:"CMC / Binder",pct:0.5,harga:25000,fungsi:"Binding agent — bentuk pelet"},
      ],
      feeding: [
        "Pakan hijauan (50–60%): jerami fermentasi / silase jagung / rumput gajah",
        "Konsentrat (40–50%): 4–6 kg/ekor/hari tergantung BB",
        "Jadwal: 2× sehari (pagi 06.00 + sore 15.00), air minum ad libitum",
        "Adaptasi 14 hari: mulai 2 kg → naik bertahap tiap 3 hari",
        "Monitor BCS (Body Condition Score) setiap 2 minggu",
        "Tambahan probiotik 5 g/ekor/hari meningkatkan FCR 10–15%",
      ],
    },
    {
      nama: "Konsentrat Sapi Laktasi (Induk Bunting/Menyusui)", fase: "Bunting 7–9 bln + Laktasi",
      target: "Produksi susu optimal · BCS 3.0–3.5", color: "#60a5fa",
      ket: "Formula nutrisi untuk sapi perah / induk sapi potong masa laktasi",
      nutrisi: [
        {label:"Protein Kasar (CP)",nilai:"16–18%",ideal:"17%",benchmark:"NRC Dairy 2021"},
        {label:"NEL (Net Energy Lactation)",nilai:"1.55–1.65 Mcal/kg",ideal:"1.60 Mcal",benchmark:"NRC"},
        {label:"Serat Kasar (NDF)",nilai:"28–35%",ideal:"32%",benchmark:"Rumen health"},
        {label:"Lemak Kasar",nilai:"4–6%",ideal:"5%",benchmark:"Maks 6% total diet"},
        {label:"Kalsium (Ca)",nilai:"0.8–1.0%",ideal:"0.9%",benchmark:"NRC (laktasi tinggi)"},
        {label:"Fosfor (P)",nilai:"0.4–0.5%",ideal:"0.45%",benchmark:"NRC"},
        {label:"Magnesium (Mg)",nilai:"0.2–0.3%",ideal:"0.25%",benchmark:"Cegah hypomagnesemia"},
        {label:"Kadar Air",nilai:"<14%",ideal:"12%",benchmark:"SNI"},
      ],
      bahan: [
        {bahan:"Jagung Giling",pct:35,harga:5500,fungsi:"Energi utama — pati bypass"},
        {bahan:"Bungkil Kedelai 48%",pct:18,harga:9000,fungsi:"Protein RUP terbaik untuk susu"},
        {bahan:"Canola Meal",pct:8,harga:8500,fungsi:"Asam amino esensial balanced"},
        {bahan:"Dedak Padi",pct:10,harga:3200,fungsi:"Serat + energi + B-vitamin"},
        {bahan:"Onggok / Cassava Pulp",pct:8,harga:1800,fungsi:"Sumber energi fermentasi rumen"},
        {bahan:"Lemak By-Pass (Ca-Soap)",pct:3,harga:22000,fungsi:"Energi tinggi tanpa gangu rumen"},
        {bahan:"Tepung Ikan 65%",pct:4,harga:18000,fungsi:"Lysine + Met bypass — protein susu"},
        {bahan:"Molases",pct:4,harga:2500,fungsi:"Palatabilitas + binding"},
        {bahan:"Kapur CaCO₃",pct:1.5,harga:800,fungsi:"Ca untuk sintesis susu"},
        {bahan:"DCP",pct:1.2,harga:12000,fungsi:"Ca + P — mineral kritis laktasi"},
        {bahan:"Garam",pct:0.5,harga:2000,fungsi:"Elektrolit"},
        {bahan:"Premix Sapi Laktasi",pct:1,harga:55000,fungsi:"Vit E/B₁₂, Biotin, Cu, Se, Zn"},
        {bahan:"Buffer (NaHCO₃ + MgO)",pct:1.5,harga:10000,fungsi:"pH rumen stabil — milk fat"},
        {bahan:"Niacin",pct:0.05,harga:120000,fungsi:"Mencegah ketosis — early lactation"},
      ],
      feeding: [
        "Total DMI (Dry Matter Intake): 3–3.5% BH/hari",
        "Pemberian 3× sehari agar rumen stabil",
        "Total mixed ration (TMR) direkomendasikan untuk efisiensi",
        "Hijauan: silase jagung / rumput setaria 50–55% dari total diet",
        "Tingkatkan konsentrat 2 minggu sebelum partus (steaming up)",
        "Setelah partus: naik bertahap 0.5 kg/hari hingga peak lactation",
      ],
    },
  ],
  domba: [
    {
      nama: "Pakan Domba Penggemukan Intensif", fase: "Bakalan 3–6 bulan",
      target: "ADG 150–200 g/hari · FCR 4–5", color: "#a3e635",
      ket: "Formula setara Wonosari / pakan domba komersial grade A",
      nutrisi: [
        {label:"Protein Kasar (CP)",nilai:"14–16%",ideal:"15%",benchmark:"SNI + NRC Small Ruminant"},
        {label:"TDN",nilai:"65–70%",ideal:"68%",benchmark:"NRC 2007"},
        {label:"Serat Kasar (CF)",nilai:"<20%",ideal:"18%",benchmark:"Maks 22%"},
        {label:"Lemak Kasar",nilai:"3–5%",ideal:"4%",benchmark:"Maks 6%"},
        {label:"Kalsium (Ca)",nilai:"0.4–0.7%",ideal:"0.5%",benchmark:"Ca:P = 1.5:1 – 2:1"},
        {label:"Fosfor (P)",nilai:"0.3–0.5%",ideal:"0.35%",benchmark:"NRC"},
        {label:"Tembaga (Cu) — PERHATIAN",nilai:"7–11 ppm",ideal:"8 ppm",benchmark:"Domba sensitif Cu — maks 15 ppm!"},
        {label:"Kadar Air",nilai:"<14%",ideal:"12%",benchmark:"SNI"},
      ],
      bahan: [
        {bahan:"Jagung Giling",pct:35,harga:5500,fungsi:"Energi utama"},
        {bahan:"Bungkil Kedelai",pct:12,harga:9000,fungsi:"Protein utama"},
        {bahan:"Dedak Padi",pct:15,harga:3200,fungsi:"Serat + B-vit + energi"},
        {bahan:"Pollard",pct:10,harga:4800,fungsi:"Serat larut — rumen sehat"},
        {bahan:"Onggok",pct:10,harga:1800,fungsi:"Energi fermentasi murah"},
        {bahan:"Bungkil Kelapa",pct:8,harga:4000,fungsi:"Energi + protein lokal"},
        {bahan:"Molases",pct:4,harga:2500,fungsi:"Palatabilitas + binding"},
        {bahan:"Kapur CaCO₃",pct:1.5,harga:800,fungsi:"Kalsium"},
        {bahan:"Garam",pct:0.5,harga:2000,fungsi:"Elektrolit — nafsu makan"},
        {bahan:"Premix Domba (Cu rendah)",pct:1,harga:40000,fungsi:"WAJIB Cu rendah! Vit A/D/E, Zn, Se"},
        {bahan:"Sulfur (Elemental S)",pct:0.3,harga:5000,fungsi:"Metabolisme N — ratio N:S = 10:1"},
        {bahan:"Urea Feed Grade",pct:0.7,harga:6500,fungsi:"NPN — max 0.5–1% dari total"},
        {bahan:"Betaine Anhydrous",pct:0.1,harga:90000,fungsi:"Osmoprotektan — cegah heat stress"},
      ],
      feeding: [
        "⚠️ PERHATIAN: Domba SANGAT sensitif tembaga (Cu)! Jangan pakai premix sapi!",
        "Hijauan: 60% rumput + 40% konsentrat untuk penggemukan",
        "Dosis konsentrat: 1.5–2.5% BH/hari (300–600 g/ekor/hari)",
        "Air minum bersih ad libitum — minimal 2–3 liter/ekor/hari",
        "Berikan hay / jerami kualitas baik sebagai roughage base",
        "Tambahan Zinc 50 ppm bantu pertumbuhan wool + imunitas",
        "Puasa hijauan 4 jam sebelum konsentrat meningkatkan konsumsi",
      ],
    },
  ],
  broiler: [
    {
      nama: "Ransum Broiler Starter (DOC – Umur 14 Hari)", fase: "Starter D1–D14",
      target: "BB target 380–420 g/ekor @14 hari · FCR ≤1.3", color: "#e879f9",
      ket: "Formula setara CP-511 / Japfa BEST / Pokphand — fase kritis pertumbuhan sel otot",
      nutrisi: [
        {label:"Metabolizable Energy (ME)",nilai:"3050–3100 kcal/kg",ideal:"3080 kcal",benchmark:"Ross 308 Guide 2022"},
        {label:"Protein Kasar (CP)",nilai:"22–23%",ideal:"22.5%",benchmark:"Cobb 500 Nutrition Spec"},
        {label:"Lysine (total)",nilai:"1.35–1.45%",ideal:"1.42%",benchmark:"Asam amino #1 broiler"},
        {label:"Methionine (total)",nilai:"0.52–0.58%",ideal:"0.55%",benchmark:"Penentu kualitas daging"},
        {label:"Calcium (Ca)",nilai:"0.95–1.05%",ideal:"1.00%",benchmark:"Tulang + metabolisme"},
        {label:"Available Phosphorus (aP)",nilai:"0.45–0.50%",ideal:"0.48%",benchmark:"NRC Poultry 2012"},
        {label:"Sodium (Na)",nilai:"0.18–0.22%",ideal:"0.20%",benchmark:"Keseimbangan elektrolit"},
        {label:"Kadar Air",nilai:"<13%",ideal:"12%",benchmark:"SNI 01-3930"},
      ],
      bahan: [
        {bahan:"Jagung Kuning 3 Giling",pct:53,harga:5500,fungsi:"Energi primer + pigmentor xanthophyll"},
        {bahan:"Bungkil Kedelai Hi-Pro 48%",pct:28,harga:9000,fungsi:"Protein + Lysine terbaik — backbone formula"},
        {bahan:"Tepung Ikan 65%",pct:5,harga:18000,fungsi:"Protein animal — palatabilitas + AA balance"},
        {bahan:"Poultry Fat / Lemak Unggas",pct:3,harga:8000,fungsi:"Densitas energi — cold pressed"},
        {bahan:"Dedak Gandum (Pollard)",pct:4,harga:4800,fungsi:"Serat larut + vitamin B kompleks"},
        {bahan:"Dikalsium Fosfat (DCP)",pct:2,harga:12000,fungsi:"Ca + aP — tulang + metabolisme"},
        {bahan:"Kapur CaCO₃",pct:1.2,harga:800,fungsi:"Kalsium pelengkap"},
        {bahan:"Garam (NaCl)",pct:0.3,harga:2000,fungsi:"Na + Cl — keseimbangan osmotik"},
        {bahan:"DL-Methionine 99%",pct:0.25,harga:55000,fungsi:"Methionine sintetis — AA limiting #2"},
        {bahan:"L-Lysine HCl 98%",pct:0.15,harga:18000,fungsi:"Lysine — AA limiting #1 unggas"},
        {bahan:"L-Threonine 98%",pct:0.05,harga:25000,fungsi:"Threonine — efisiensi protein"},
        {bahan:"Premix Broiler Starter",pct:0.5,harga:80000,fungsi:"Vit A/D₃/E/K/B kompleks + Cu/Zn/Se/I"},
        {bahan:"Phytase 5000 FTU",pct:0.01,harga:300000,fungsi:"Membebaskan P dari phytat — hemat DCP"},
        {bahan:"NSP Enzyme (Xylanase+β-glucanase)",pct:0.01,harga:250000,fungsi:"Degradasi NSP — perbaiki FCR 3–5%"},
        {bahan:"Coccidiostat (Salinomycin/Amprolium)",pct:0.05,harga:150000,fungsi:"Pencegahan koksidiosis"},
        {bahan:"Antimycotoxin (Toxin Binder)",pct:0.2,harga:60000,fungsi:"Adsorb aflatoksin dari jagung"},
        {bahan:"Choline Chloride 60%",pct:0.05,harga:35000,fungsi:"Metabolisme lemak + pertumbuhan"},
        {bahan:"Sodium Bicarbonate",pct:0.2,harga:8000,fungsi:"Buffer — keseimbangan elektrolit"},
      ],
      feeding: [
        "Bentuk: Crumble (remah) D1–D7, lalu mini-pellet D8–D14",
        "Konsumsi target: 8–12 g/ekor/hari (D1) → 30–40 g/ekor/hari (D14)",
        "Pemberian: ad libitum (selalu tersedia) — JANGAN dibatasi di starter!",
        "Suhu brooder: 33°C minggu 1 → 30°C minggu 2 (turun 3°C/minggu)",
        "Air minum: rasio air:pakan = 1.7–2:1 — kualitas air pH 6–7",
        "Pencahayaan 23 jam D1–D7 → 20 jam D8–D14",
        "Vaksin ND (tetes mata) D4, Gumboro (air minum) D10",
        "Monitor uniformity flock: CV bobot < 10% adalah target",
      ],
    },
    {
      nama: "Ransum Broiler Finisher (Umur 22–35 Hari)", fase: "Finisher D22–D35",
      target: "BB target 1.8–2.2 kg/ekor · FCR ≤1.65", color: "#c084fc",
      ket: "Formula low protein — efisiensi energi maksimum, deposit lemak terkontrol",
      nutrisi: [
        {label:"Metabolizable Energy (ME)",nilai:"3150–3200 kcal/kg",ideal:"3175 kcal",benchmark:"Ross 308 Finisher Spec"},
        {label:"Protein Kasar (CP)",nilai:"19–20%",ideal:"19.5%",benchmark:"Turun dari starter (protein sparing)"},
        {label:"Lysine (total)",nilai:"1.10–1.20%",ideal:"1.15%",benchmark:"Efisiensi breast meat"},
        {label:"Methionine+Cystine",nilai:"0.78–0.85%",ideal:"0.82%",benchmark:"Kualitas karkas"},
        {label:"Calcium (Ca)",nilai:"0.85–0.95%",ideal:"0.90%",benchmark:"Tulang finisher"},
        {label:"Available Phosphorus",nilai:"0.38–0.45%",ideal:"0.42%",benchmark:"NRC Poultry"},
        {label:"Ether Extract (Lemak)",nilai:"5–7%",ideal:"6%",benchmark:"Densitas energi"},
        {label:"Kadar Air",nilai:"<13%",ideal:"12%",benchmark:"SNI"},
      ],
      bahan: [
        {bahan:"Jagung Kuning",pct:58,harga:5500,fungsi:"Energi utama — ditingkatkan dari starter"},
        {bahan:"Bungkil Kedelai 48%",pct:22,harga:9000,fungsi:"Protein — diturunkan (protein sparing)"},
        {bahan:"Poultry Fat",pct:5,harga:8000,fungsi:"Densitas energi tinggi — efisiensi FCR"},
        {bahan:"Tepung Ikan 65%",pct:3,harga:18000,fungsi:"Protein animal + palatabilitas"},
        {bahan:"Pollard",pct:4,harga:4800,fungsi:"Serat + B-vitamin"},
        {bahan:"DCP",pct:1.8,harga:12000,fungsi:"Ca + aP"},
        {bahan:"Kapur",pct:1.0,harga:800,fungsi:"Kalsium"},
        {bahan:"DL-Methionine",pct:0.18,harga:55000,fungsi:"Methionine — kualitas karkas"},
        {bahan:"L-Lysine HCl",pct:0.12,harga:18000,fungsi:"Lysine — breast muscle"},
        {bahan:"Garam",pct:0.3,harga:2000,fungsi:"Elektrolit"},
        {bahan:"Premix Broiler Finisher",pct:0.5,harga:75000,fungsi:"Vit + mineral lengkap (tanpa coccidiostat!)"},
        {bahan:"Phytase",pct:0.01,harga:300000,fungsi:"Hemat P anorganik"},
        {bahan:"Enzim NSP",pct:0.01,harga:250000,fungsi:"FCR improvement"},
        {bahan:"Antioksidan",pct:0.02,harga:150000,fungsi:"Stabilitas lemak — shelf life karkas"},
        {bahan:"Toxin Binder",pct:0.2,harga:60000,fungsi:"Keamanan pakan"},
        {bahan:"Betaine",pct:0.1,harga:90000,fungsi:"Hemat methionine + cegah heat stress"},
      ],
      feeding: [
        "Bentuk: Pellet 3mm (WAJIB pellet untuk FCR optimal)",
        "Konsumsi target: 80–100 g/hari (D22) → 130–160 g/hari (D35)",
        "Withdrawal feed: STOP coccidiostat & antibiotik 5–7 hari sebelum panen",
        "Program pencahayaan: 20 jam terang / 4 jam gelap — stimulasi konsumsi",
        "Air minum: maintenance 1.8–2× konsumsi pakan (berat)",
        "Kepadatan kandang maks: 10–12 ekor/m² untuk FCR optimal",
        "Monitor bobot sampling 10% populasi setiap 5 hari",
        "FCR ≤1.65 = excellent; 1.65–1.75 = good; >1.80 = perlu evaluasi",
      ],
    },
  ],
  petelur: [
    {
      nama: "Ransum Layer Peak Production (HDP >90%)", fase: "Lay Phase 1 — 18–40 minggu",
      target: "HDP ≥92% · Berat telur 60–65 g · FCR ≤2.0", color: "#f59e0b",
      ket: "Formula setara Lohmann/ISA Brown Guide — masa produksi puncak",
      nutrisi: [
        {label:"Metabolizable Energy (ME)",nilai:"2750–2800 kcal/kg",ideal:"2780 kcal",benchmark:"Lohmann Brown Management Guide"},
        {label:"Protein Kasar (CP)",nilai:"16–17%",ideal:"16.5%",benchmark:"Cukup — bukan tinggi protein!"},
        {label:"Lysine",nilai:"0.80–0.90%",ideal:"0.85%",benchmark:"Kualitas putih telur"},
        {label:"Methionine",nilai:"0.38–0.42%",ideal:"0.40%",benchmark:"Yolk + albumin"},
        {label:"Kalsium (Ca) — KRITIS",nilai:"3.8–4.2%",ideal:"4.0%",benchmark:"Cangkang telur = 2g Ca/telur"},
        {label:"Available Phosphorus",nilai:"0.35–0.40%",ideal:"0.38%",benchmark:"Keseimbangan Ca:P = 10:1"},
        {label:"Natrium (Na)",nilai:"0.16–0.20%",ideal:"0.18%",benchmark:"Keseimbangan elektrolit"},
        {label:"Linoleic Acid",nilai:"≥1.5%",ideal:"1.8%",benchmark:"Berat telur — omega-6"},
      ],
      bahan: [
        {bahan:"Jagung Kuning",pct:52,harga:5500,fungsi:"Energi + xanthophyll (kuning yolk)"},
        {bahan:"Bungkil Kedelai 48%",pct:18,harga:9000,fungsi:"Protein — albumin telur"},
        {bahan:"Limestone / Kapur Besar",pct:9,harga:800,fungsi:"Ca UTAMA cangkang telur (HARUS kapur kasar!)"},
        {bahan:"Dedak Gandum Pollard",pct:5,harga:4800,fungsi:"Serat + vit B"},
        {bahan:"Minyak Kelapa Sawit / CPO",pct:3,harga:12000,fungsi:"Linoleic acid + densitas energi"},
        {bahan:"DCP",pct:1.5,harga:12000,fungsi:"aP + Ca tersedia"},
        {bahan:"Bungkil Kedelai / Canola",pct:4,harga:8500,fungsi:"Asam amino balance"},
        {bahan:"DL-Methionine",pct:0.20,harga:55000,fungsi:"Methionine — kualitas kuning telur"},
        {bahan:"L-Lysine",pct:0.10,harga:18000,fungsi:"Albumin + efisiensi protein"},
        {bahan:"Garam NaCl",pct:0.30,harga:2000,fungsi:"Elektrolit"},
        {bahan:"Sodium Bicarbonate",pct:0.15,harga:8000,fungsi:"Buffer + Na tambahan"},
        {bahan:"Premix Layer",pct:0.5,harga:70000,fungsi:"Vit D₃ (kritis Ca!), A, E, K, B₁₂, Biotin, Mn, Zn, Se, I"},
        {bahan:"Phytase",pct:0.01,harga:300000,fungsi:"Bebaskan P + Ca dari phytat"},
        {bahan:"Xylanase",pct:0.01,harga:250000,fungsi:"Viskositas usus halus — absorpsi Ca"},
        {bahan:"Canthaxanthin / Capsicum",pct:0.01,harga:400000,fungsi:"Pigmentor premium — yolk skor 12–14"},
        {bahan:"Toxin Binder",pct:0.2,harga:60000,fungsi:"Aflatoksin — cegah drop produksi"},
        {bahan:"MOS / Beta-glucan (Prebiotik)",pct:0.05,harga:120000,fungsi:"Gut health — uniformity produksi"},
      ],
      feeding: [
        "⚠️ KALSIUM adalah nutrisi #1 layer — kekurangan = shell tipis & egg drop!",
        "Dosis: 100–115 g pakan/ekor/hari (jangan lebih — FCR naik!)",
        "Berikan ½ kapur kasar di sore hari — mobilisasi Ca saat pembentukan cangkang malam",
        "Air minum: 180–200 ml/ekor/hari — kekurangan air = drop produksi 10% dalam 24 jam!",
        "Suhu kandang: 18–24°C optimal — >28°C konsumsi turun, kulit telur menipis",
        "Program cahaya: 16 jam/hari minimum — kurang cahaya = stop produksi!",
        "Vaksin AI (H5N1) rutin setiap 6 bulan — WAJIB",
        "FCR ≤2.0 = excellent; 2.0–2.2 = good; >2.3 = evaluasi menyeluruh",
      ],
    },
    {
      nama: "Ransum Layer Pre-Lay & Pullet (14–17 minggu)", fase: "Pre-Lay 14–17 minggu",
      target: "Kematangan seksual seragam · BCS optimal saat awal bertelur", color: "#fbbf24",
      ket: "Fase kritis — program nutrisi menentukan performa produksi 1 tahun ke depan",
      nutrisi: [
        {label:"ME",nilai:"2700–2750 kcal/kg",ideal:"2720 kcal",benchmark:"Lohmann Pre-Lay Spec"},
        {label:"Protein Kasar",nilai:"17–18%",ideal:"17.5%",benchmark:"Tinggi protein untuk organ reproduksi"},
        {label:"Kalsium (Ca)",nilai:"2.0–2.5%",ideal:"2.25%",benchmark:"Persiapan medullary bone"},
        {label:"Available Phosphorus",nilai:"0.40–0.45%",ideal:"0.42%",benchmark:"NRC"},
        {label:"Linoleic Acid",nilai:"≥1.3%",ideal:"1.5%",benchmark:"Ukuran telur pertama"},
        {label:"Vit D₃",nilai:"≥3000 IU/kg",ideal:"3500 IU",benchmark:"Mobilisasi Ca optimal"},
        {label:"Folic Acid",nilai:"≥1.5 mg/kg",ideal:"2.0 mg",benchmark:"Fertilitas + perkembangan folikel"},
        {label:"Kadar Air",nilai:"<13%",ideal:"12%",benchmark:"SNI"},
      ],
      bahan: [
        {bahan:"Jagung Kuning",pct:50,harga:5500,fungsi:"Energi sedang"},
        {bahan:"Bungkil Kedelai 48%",pct:22,harga:9000,fungsi:"Protein tinggi untuk perkembangan ovarium"},
        {bahan:"Limestone Kasar",pct:4,harga:800,fungsi:"Pre-lay Ca — persiapan medullary bone"},
        {bahan:"Pollard",pct:8,harga:4800,fungsi:"Serat — peristaltik usus + B-vit"},
        {bahan:"DCP",pct:2,harga:12000,fungsi:"aP + Ca"},
        {bahan:"Minyak Sawit",pct:2,harga:12000,fungsi:"Energi + linoleic acid"},
        {bahan:"DL-Methionine",pct:0.22,harga:55000,fungsi:"Methionine — reproduksi"},
        {bahan:"L-Lysine",pct:0.12,harga:18000,fungsi:"Protein synthesis"},
        {bahan:"Garam",pct:0.3,harga:2000,fungsi:"Elektrolit"},
        {bahan:"NaHCO₃",pct:0.15,harga:8000,fungsi:"Buffer"},
        {bahan:"Premix Layer Pre-lay",pct:0.5,harga:75000,fungsi:"Vit D₃ tinggi + Folic acid + Biotin + Mn"},
        {bahan:"Phytase",pct:0.01,harga:300000,fungsi:"P availability"},
        {bahan:"Toxin Binder",pct:0.2,harga:60000,fungsi:"Proteksi aflatoksin"},
      ],
      feeding: [
        "Transisi ke ransum pre-lay pada TEPAT minggu ke-14 (jangan terlambat!)",
        "Dosis: 90–100 g/ekor/hari — jaga uniformity bobot ≥80%",
        "Program cahaya: mulai tambah 1 jam/minggu dari 10 jam → 16 jam saat bertelur",
        "Penambahan cahaya SEBELUM bobot standar = produksi jelek seumur hidup!",
        "Bobot target Lohmann Brown: 1450–1550 g saat pertama bertelur",
        "Monitor perkembangan organ reproduksi: palpasi kloaka setiap minggu",
      ],
    },
  ],
};

/* ===== HALAMAN: PAKAN ===== */
/* ================================================================
   DATABASE BAHAN PAKAN — Nilai Nutrisi Standar (Balitnak / NRC)
================================================================ */
const BAHAN_DB = [
  // SUMBER ENERGI
  {id:"jag",nama:"Jagung Kuning Giling",kat:"Energi",pk:8.5,me:3370,tdn:88,ca:0.02,p:0.28,sk:2.3,lk:3.9,air:14,harga:5500},
  {id:"ded",nama:"Dedak Padi Halus",kat:"Energi",pk:12.0,me:1630,tdn:57,ca:0.12,p:1.50,sk:12.0,lk:8.0,air:12,harga:3200},
  {id:"pol",nama:"Pollard/Wheat Bran",kat:"Energi",pk:15.5,me:1600,tdn:65,ca:0.13,p:1.10,sk:9.5,lk:4.5,air:12,harga:4800},
  {id:"ong",nama:"Onggok/Cassava Pulp",kat:"Energi",pk:2.5,me:3000,tdn:78,ca:0.27,p:0.09,sk:16.5,lk:0.5,air:12,harga:1800},
  {id:"mol",nama:"Molases/Tetes Tebu",kat:"Energi",pk:3.0,me:2480,tdn:72,ca:0.74,p:0.09,sk:0,lk:0.1,air:25,harga:2500},
  {id:"cpo",nama:"CPO/Minyak Kelapa Sawit",kat:"Energi",pk:0,me:8600,tdn:98,ca:0,p:0,sk:0,lk:99,air:0,harga:12000},
  {id:"lmt",nama:"Lemak Unggas (Poultry Fat)",kat:"Energi",pk:0,me:8200,tdn:98,ca:0,p:0,sk:0,lk:99,air:0,harga:8000},
  {id:"sin",nama:"Singkong/Gaplek Kering",kat:"Energi",pk:2.5,me:3200,tdn:80,ca:0.15,p:0.10,sk:4.0,lk:0.5,air:12,harga:2200},
  // SUMBER PROTEIN NABATI
  {id:"sbm",nama:"Bungkil Kedelai 48% (SBM)",kat:"Protein Nabati",pk:48.0,me:2240,tdn:86,ca:0.27,p:0.67,sk:6.0,lk:1.5,air:12,harga:9000},
  {id:"cgm",nama:"CGM (Corn Gluten Meal)",kat:"Protein Nabati",pk:60.0,me:3460,tdn:90,ca:0.10,p:0.48,sk:3.0,lk:5.0,air:12,harga:11000},
  {id:"bkl",nama:"Bungkil Kelapa",kat:"Protein Nabati",pk:21.0,me:1750,tdn:68,ca:0.21,p:0.67,sk:15.0,lk:9.5,air:12,harga:4000},
  {id:"bks",nama:"Bungkil Sawit/Palm KM",kat:"Protein Nabati",pk:16.0,me:1770,tdn:65,ca:0.30,p:0.70,sk:18.0,lk:7.0,air:12,harga:3500},
  {id:"ure",nama:"Urea Feed Grade 46%N",kat:"Protein NPN",pk:287,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:6500},
  // SUMBER PROTEIN HEWANI
  {id:"tik",nama:"Tepung Ikan 65%",kat:"Protein Hewani",pk:65.0,me:2830,tdn:77,ca:5.11,p:3.10,sk:1.0,lk:9.0,air:10,harga:18000},
  {id:"mbm",nama:"MBM Tepung Daging & Tulang",kat:"Protein Hewani",pk:50.0,me:2210,tdn:70,ca:10.0,p:5.10,sk:2.5,lk:8.0,air:10,harga:12000},
  {id:"mgg",nama:"Maggot BSF Kering",kat:"Protein Hewani",pk:42.0,me:2950,tdn:80,ca:5.0,p:0.9,sk:7.0,lk:22.0,air:10,harga:10000},
  {id:"ddgs",nama:"DDGS (Corn Distillers)",kat:"Protein Campuran",pk:28.0,me:2380,tdn:80,ca:0.06,p:0.81,sk:8.5,lk:9.5,air:12,harga:7500},
  // MINERAL & ADDITIVE
  {id:"dcp",nama:"DCP (Dikalsium Fosfat)",kat:"Mineral",pk:0,me:0,tdn:0,ca:22.0,p:18.0,sk:0,lk:0,air:5,harga:12000},
  {id:"kap",nama:"Limestone/Kapur CaCO3",kat:"Mineral",pk:0,me:0,tdn:0,ca:38.0,p:0,sk:0,lk:0,air:0,harga:800},
  {id:"oys",nama:"Oyster Shell/Kulit Kerang",kat:"Mineral",pk:0,me:0,tdn:0,ca:36.0,p:0.1,sk:0,lk:0,air:2,harga:1500},
  {id:"gar",nama:"Garam NaCl",kat:"Mineral",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:2000},
  {id:"pxb",nama:"Premix Broiler",kat:"Additive",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:80000},
  {id:"pxl",nama:"Premix Layer",kat:"Additive",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:70000},
  {id:"pxs",nama:"Premix Sapi (Ruminansia)",kat:"Additive",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:45000},
  {id:"met",nama:"DL-Methionine 99%",kat:"Additive",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:55000},
  {id:"lys",nama:"L-Lysine HCl 98%",kat:"Additive",pk:0,me:0,tdn:0,ca:0,p:0,sk:0,lk:0,air:0,harga:18000},
  // HIJAUAN & ROUGHAGE
  {id:"rgj",nama:"Rumput Gajah Segar",kat:"Hijauan",pk:9.0,me:1850,tdn:58,ca:0.40,p:0.28,sk:32.0,lk:2.5,air:78,harga:400},
  {id:"jrm",nama:"Jerami Padi Fermentasi",kat:"Hijauan",pk:8.5,me:1600,tdn:52,ca:0.25,p:0.10,sk:26.0,lk:1.5,air:15,harga:600},
  {id:"sil",nama:"Silase Jagung",kat:"Hijauan",pk:10.0,me:2400,tdn:66,ca:0.30,p:0.22,sk:25.0,lk:3.5,air:30,harga:900},
  {id:"lmt",nama:"Daun Lamtoro Kering",kat:"Hijauan",pk:24.0,me:2500,tdn:70,ca:1.50,p:0.22,sk:17.0,lk:4.5,air:12,harga:500},
  {id:"ath",nama:"Ampas Tahu Kering",kat:"Protein Nabati",pk:28.0,me:2700,tdn:72,ca:0.42,p:0.65,sk:18.0,lk:11.0,air:12,harga:2500},
];

/* KEBUTUHAN NUTRISI TARGET per Jenis & Fase */
const KEBUTUHAN = {
  broiler: [
    {fase:"Pre-Starter (D1–7)",me:3100,pk:23,ca:1.0,p:0.5,sk:4,referensi:"CP-510 / Cobb 500 Guide"},
    {fase:"Starter (D8–21)",me:3050,pk:21,ca:0.9,p:0.5,sk:5,referensi:"CP-511 / Ross 308"},
    {fase:"Finisher (D22–Panen)",me:3150,pk:19,ca:0.85,p:0.45,sk:5,referensi:"CP-512 / Ross Finisher"},
  ],
  petelur: [
    {fase:"Pullet Starter (1–6 mgg)",me:2950,pk:20,ca:1.0,p:0.5,sk:6,referensi:"EH-701 Japfa / Lohmann"},
    {fase:"Pre-Layer (14–17 mgg)",me:2750,pk:17.5,ca:2.25,p:0.42,sk:7,referensi:"CP-526P / ISA Brown"},
    {fase:"Layer Peak (18–40 mgg)",me:2780,pk:16.5,ca:4.0,p:0.38,sk:7,referensi:"EH-711 Japfa / Lohmann"},
    {fase:"Layer Late (>40 mgg)",me:2700,pk:15,ca:4.2,p:0.35,sk:7,referensi:"Lohmann Late Lay"},
  ],
  sapi: [
    {fase:"Grower Penggemukan (F8)",me:2400,pk:14,ca:0.6,p:0.3,sk:17,referensi:"Indo Prima Beef F8"},
    {fase:"Finisher Penggemukan (F9)",me:2600,pk:12,ca:0.55,p:0.28,sk:15,referensi:"Indo Prima Beef F9"},
    {fase:"Sapi Perah Laktasi",me:2700,pk:17,ca:0.9,p:0.45,sk:17,referensi:"NRC Dairy 2021"},
  ],
  domba: [
    {fase:"Penggemukan Bakalan",me:2400,pk:14,ca:0.5,p:0.3,sk:20,referensi:"NRC Small Ruminant"},
    {fase:"Domba Bunting/Induk",me:2200,pk:12,ca:0.7,p:0.35,sk:22,referensi:"NRC + Balitnak"},
  ],
};

/* CONTOH FORMULA PERUSAHAAN */
const CONTOH_FORMULA = {
  broiler: {
    judul:"Formula CP-511 Setara (Broiler Starter D8–21)",
    sumber:"Berdasarkan jurnal ilmiah & label resmi CP-511 PT Charoen Pokphand",
    bahan:[
      {nama:"Jagung Kuning",pct:55,catatan:"Energi utama"},
      {nama:"Bungkil Kedelai 48%",pct:26,catatan:"Protein utama"},
      {nama:"Tepung Ikan 65%",pct:4,catatan:"Protein hewani + palatabilitas"},
      {nama:"CPO/Poultry Fat",pct:3,catatan:"Densitas energi"},
      {nama:"Pollard",pct:5,catatan:"Serat + Vit B"},
      {nama:"DCP",pct:2,catatan:"Ca + P"},
      {nama:"Limestone",pct:1.2,catatan:"Ca"},
      {nama:"DL-Methionine",pct:0.25,catatan:"AA limiting"},
      {nama:"L-Lysine",pct:0.15,catatan:"AA limiting"},
      {nama:"Premix Broiler",pct:0.5,catatan:"Vit+Min"},
      {nama:"Garam NaCl",pct:0.3,catatan:"Elektrolit"},
      {nama:"Coccidiostat",pct:0.1,catatan:"Anti-koksidia"},
    ],
    hasil:{me:3055,pk:21.8,ca:0.98,p:0.52,sk:4.5,harga:8800},
  },
  petelur: {
    judul:"Formula EH-711 Setara (Layer Peak Production)",
    sumber:"Berdasarkan label EH-711 Japfa + jurnal nutrisi unggas",
    bahan:[
      {nama:"Jagung Kuning",pct:52,catatan:"Energi + pigmentor"},
      {nama:"Bungkil Kedelai 48%",pct:18,catatan:"Protein albumin telur"},
      {nama:"DDGS",pct:5,catatan:"Protein + energi murah"},
      {nama:"Pollard",pct:5,catatan:"Serat"},
      {nama:"CPO",pct:3,catatan:"Linoleic acid + energi"},
      {nama:"Oyster Shell",pct:9,catatan:"Ca utama cangkang telur"},
      {nama:"DCP",pct:1.5,catatan:"aP + Ca"},
      {nama:"DL-Methionine",pct:0.2,catatan:"Kualitas kuning telur"},
      {nama:"L-Lysine",pct:0.1,catatan:"Albumin"},
      {nama:"Premix Layer",pct:0.5,catatan:"Vit D3 + Mn + Se"},
      {nama:"Garam",pct:0.3,catatan:"Na + Cl"},
      {nama:"NaHCO3",pct:0.15,catatan:"Buffer"},
    ],
    hasil:{me:2785,pk:17.2,ca:4.05,p:0.40,sk:5.8,harga:7400},
  },
  sapi: {
    judul:"Formula Konsentrat F9 Setara (Feedlot Finisher)",
    sumber:"Berdasarkan Indo Prima Beef F9 + SNI 3148-2:2017",
    bahan:[
      {nama:"Jagung Kuning",pct:38,catatan:"Energi utama — TDN tinggi"},
      {nama:"Bungkil Kedelai",pct:12,catatan:"Protein + rumen bypass"},
      {nama:"Dedak Padi",pct:16,catatan:"Serat + energi"},
      {nama:"Onggok",pct:10,catatan:"Energi fermentasi murah"},
      {nama:"Bungkil Kelapa",pct:8,catatan:"Energi + protein lokal"},
      {nama:"Pollard",pct:8,catatan:"Serat + vit B"},
      {nama:"Molases",pct:4,catatan:"Palatabilitas + energi cepat"},
      {nama:"Urea 46%",pct:0.8,catatan:"NPN sumber N rumen"},
      {nama:"Limestone",pct:1.2,catatan:"Kalsium"},
      {nama:"DCP",pct:0.7,catatan:"Ca + P"},
      {nama:"Garam",pct:0.5,catatan:"Elektrolit"},
      {nama:"Premix Sapi",pct:1.0,catatan:"Vit+Min"},
    ],
    hasil:{me:2620,pk:13.8,ca:0.58,p:0.30,sk:14.5,harga:3800},
  },
  domba: {
    judul:"Formula Konsentrat Domba Penggemukan (SNI + BPTP Jabar)",
    sumber:"Standar BPTP Jawa Barat + NRC Small Ruminant 2007",
    bahan:[
      {nama:"Jagung Kuning",pct:33,catatan:"Energi utama"},
      {nama:"Dedak Padi",pct:18,catatan:"Serat + B-vit"},
      {nama:"Bungkil Kedelai",pct:10,catatan:"Protein"},
      {nama:"Pollard",pct:10,catatan:"Serat larut — rumen"},
      {nama:"Onggok",pct:10,catatan:"Energi murah"},
      {nama:"Bungkil Kelapa",pct:8,catatan:"Protein + energi lokal"},
      {nama:"Ampas Tahu Kering",pct:6,catatan:"Protein tinggi murah"},
      {nama:"Molases",pct:3,catatan:"Palatabilitas"},
      {nama:"Limestone",pct:1.3,catatan:"Kalsium"},
      {nama:"Garam",pct:0.5,catatan:"Elektrolit"},
      {nama:"Premix Domba Cu-rendah",pct:1.0,catatan:"⚠️ WAJIB Cu rendah!"},
    ],
    hasil:{me:2420,pk:14.2,ca:0.52,p:0.31,sk:18.5,harga:3100},
  },
};

/* ================================================================
   KalkulatorRansum — Komponen Terpisah (state di top-level)
================================================================ */
const KalkulatorRansum = () => {
  const [animal,  setAnimal]  = React.useState("broiler");
  const [fase,    setFase]    = React.useState(0);
  const [bahan,   setBahan]   = React.useState([
    {id:1,dbId:"jag",pct:55},{id:2,dbId:"sbm",pct:26},{id:3,dbId:"tik",pct:4},
    {id:4,dbId:"cpo",pct:3},{id:5,dbId:"pol",pct:5},{id:6,dbId:"dcp",pct:2},
    {id:7,dbId:"kap",pct:1.2},{id:8,dbId:"met",pct:0.25},{id:9,dbId:"lys",pct:0.15},
    {id:10,dbId:"pxb",pct:0.5},{id:11,dbId:"gar",pct:0.3},
  ]);
  const [editNutrisi, setEditNutrisi] = React.useState(false);
  const [customTarget, setCustomTarget] = React.useState(null);
  const [showFormula, setShowFormula]   = React.useState(true);
  const [contohKey, setContohKey]       = React.useState("broiler");
  const nextId = React.useRef(20);

  // Load formula contoh
  const loadFormula = (key) => {
    const cf = CONTOH_FORMULA[key];
    if (!cf) return;
    const rows = cf.bahan.map((b, i) => {
      const match = BAHAN_DB.find(x =>
        x.nama.toLowerCase().replace(/[^a-z]/g,"").includes(
          b.nama.toLowerCase().replace(/[^a-z]/g,"").substring(0,6)
        )
      );
      return { id: i+1, dbId: match ? match.id : "jag", pct: b.pct };
    });
    setBahan(rows);
    nextId.current = rows.length + 2;
  };

  // Load default per animal
  const DEFAULTS = {
    broiler:[{id:1,dbId:"jag",pct:55},{id:2,dbId:"sbm",pct:26},{id:3,dbId:"tik",pct:4},{id:4,dbId:"cpo",pct:3},{id:5,dbId:"pol",pct:5},{id:6,dbId:"dcp",pct:2},{id:7,dbId:"kap",pct:1.2},{id:8,dbId:"met",pct:0.25},{id:9,dbId:"lys",pct:0.15},{id:10,dbId:"pxb",pct:0.5},{id:11,dbId:"gar",pct:0.3}],
    petelur:[{id:1,dbId:"jag",pct:52},{id:2,dbId:"sbm",pct:18},{id:3,dbId:"ddgs",pct:5},{id:4,dbId:"pol",pct:5},{id:5,dbId:"cpo",pct:3},{id:6,dbId:"oys",pct:9},{id:7,dbId:"dcp",pct:1.5},{id:8,dbId:"met",pct:0.2},{id:9,dbId:"lys",pct:0.1},{id:10,dbId:"pxl",pct:0.5},{id:11,dbId:"gar",pct:0.3}],
    sapi:  [{id:1,dbId:"jag",pct:38},{id:2,dbId:"sbm",pct:12},{id:3,dbId:"ded",pct:16},{id:4,dbId:"ong",pct:10},{id:5,dbId:"bkl",pct:8},{id:6,dbId:"pol",pct:8},{id:7,dbId:"mol",pct:4},{id:8,dbId:"ure",pct:0.8},{id:9,dbId:"kap",pct:1.2},{id:10,dbId:"dcp",pct:0.7},{id:11,dbId:"gar",pct:0.5},{id:12,dbId:"pxs",pct:1.0}],
    domba: [{id:1,dbId:"jag",pct:33},{id:2,dbId:"ded",pct:18},{id:3,dbId:"sbm",pct:10},{id:4,dbId:"pol",pct:10},{id:5,dbId:"ong",pct:10},{id:6,dbId:"bkl",pct:8},{id:7,dbId:"ath",pct:6},{id:8,dbId:"mol",pct:3},{id:9,dbId:"kap",pct:1.3},{id:10,dbId:"gar",pct:0.5},{id:11,dbId:"pxs",pct:1.0}],
  };

  const switchAnimal = (a) => {
    setAnimal(a);
    setFase(0);
    setCustomTarget(null);
    setBahan(DEFAULTS[a] || DEFAULTS.broiler);
    nextId.current = 20;
  };

  const kTargetList = KEBUTUHAN[animal] || [];
  const baseTarget  = kTargetList[fase] || kTargetList[0] || {};
  const target      = customTarget || baseTarget;

  // Hitung hasil ransum
  const totalPct = bahan.reduce((s,b) => s + (parseFloat(b.pct)||0), 0);
  const hasil = bahan.reduce((acc, b) => {
    const db = BAHAN_DB.find(x => x.id === b.dbId);
    if (!db) return acc;
    const f = (parseFloat(b.pct)||0) / 100;
    return {
      me:    acc.me    + db.me    * f,
      pk:    acc.pk    + db.pk    * f,
      tdn:   acc.tdn   + db.tdn   * f,
      ca:    acc.ca    + db.ca    * f,
      p:     acc.p     + db.p     * f,
      sk:    acc.sk    + db.sk    * f,
      lk:    acc.lk    + db.lk    * f,
      harga: acc.harga + db.harga * f,
    };
  }, {me:0,pk:0,tdn:0,ca:0,p:0,sk:0,lk:0,harga:0});

  const updatePct   = (id, val) => setBahan(bahan.map(b => b.id===id ? {...b, pct: parseFloat(val)||0} : b));
  const updateBahan = (id, dbId) => setBahan(bahan.map(b => b.id===id ? {...b, dbId} : b));
  const removeBahan = (id) => setBahan(bahan.filter(b => b.id !== id));
  const addBahan    = (dbId) => { if(!dbId) return; setBahan([...bahan, {id: nextId.current++, dbId, pct: 0}]); };
  const autoBalance = () => {
    // Temukan bahan filler (jagung atau dedak) dan adjust agar total = 100
    const fillerIdx = bahan.findIndex(b => ["jag","ded","pol"].includes(b.dbId));
    if (fillerIdx < 0) return;
    const others = bahan.reduce((s,b,i) => i===fillerIdx ? s : s+(parseFloat(b.pct)||0), 0);
    const newPct  = Math.max(0, 100 - others);
    setBahan(bahan.map((b,i) => i===fillerIdx ? {...b, pct: +newPct.toFixed(2)} : b));
  };

  const accentCol = {broiler:"#e879f9",petelur:"#f59e0b",sapi:"#f5c842",domba:"#a3e635"}[animal]||"#60a5fa";

  // Gap helper
  const statusOf = (actual, tgt, tolerance=0.05) => {
    if (!tgt) return "info";
    const r = actual/tgt;
    if (r >= 1-tolerance && r <= 1+tolerance) return "ok";
    return r < 1-tolerance ? "low" : "high";
  };
  const statusColor = {ok:"#22c55e", low:"#ef4444", high:"#f59e0b", info:"#60a5fa"};
  const statusLabel = {ok:"✓ OK", low:"↓ Kurang", high:"↑ Lebih", info:"—"};

  // Saran koreksi
  const saranList = [];
  if (Math.abs(totalPct-100) > 0.5) saranList.push({c:"#ef4444", m:`⚠️ Total ${totalPct.toFixed(2)}% — harus 100%. Klik Auto-Balance untuk menyesuaikan jagung/dedak otomatis`});
  if (target.me && hasil.me < target.me*0.96) saranList.push({c:"#ef4444", m:`ME kurang ${(target.me-hasil.me).toFixed(0)} kcal → Tambahkan jagung atau CPO/lemak (naikkan %)`});
  if (target.me && hasil.me > target.me*1.06) saranList.push({c:"#f59e0b", m:`ME berlebih ${(hasil.me-target.me).toFixed(0)} kcal → Kurangi jagung, ganti sebagian dengan dedak/pollard`});
  if (target.pk && hasil.pk < target.pk*0.96) saranList.push({c:"#ef4444", m:`Protein kurang ${(target.pk-hasil.pk).toFixed(2)}% → Naikkan % Bungkil Kedelai atau Tepung Ikan`});
  if (target.pk && hasil.pk > target.pk*1.06) saranList.push({c:"#f59e0b", m:`Protein berlebih ${(hasil.pk-target.pk).toFixed(2)}% → Kurangi SBM, tambah jagung sebagai pengganti`});
  if (target.ca && hasil.ca < target.ca*0.94) saranList.push({c:"#ef4444", m:`Kalsium kurang ${(target.ca-hasil.ca).toFixed(3)}% → Tambahkan Limestone atau Oyster Shell`});
  if (target.ca && hasil.ca > target.ca*1.12) saranList.push({c:"#f59e0b", m:`Kalsium berlebih → Kurangi Limestone/Oyster Shell`});
  if (target.p  && hasil.p  < target.p *0.94) saranList.push({c:"#ef4444", m:`Fosfor kurang ${(target.p-hasil.p).toFixed(3)}% → Naikkan % DCP`});
  if (saranList.length === 0) saranList.push({c:"#22c55e", m:"✅ Formula memenuhi semua target nutrisi! Siap diujicobakan skala kecil."});

  const CF = CONTOH_FORMULA[animal] || CONTOH_FORMULA.broiler;

  return (
    <div style={{display:"flex",flexDirection:"column",gap:14}}>

      {/* ── Pilih Jenis Ternak ── */}
      <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
        {[{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer"},{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"}].map(t=>(
          <button key={t.v} onClick={()=>switchAnimal(t.v)}
            style={{background:animal===t.v?accentCol+"22":"#0f1118",border:"1px solid "+(animal===t.v?accentCol+"55":C.border),borderRadius:10,padding:"9px 18px",cursor:"pointer",color:animal===t.v?accentCol:C.muted,fontWeight:700,fontSize:13}}>
            {t.l}
          </button>
        ))}
      </div>

      {/* ── Pilih Fase ── */}
      <div style={{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"}}>
        <span style={{fontSize:11,color:"#555a6a",fontWeight:700}}>Fase:</span>
        {kTargetList.map((f,i)=>(
          <button key={i} onClick={()=>{setFase(i);setCustomTarget(null);}}
            style={{background:fase===i&&!customTarget?accentCol+"18":"#0f1118",border:"1px solid "+(fase===i&&!customTarget?accentCol+"40":C.border),borderRadius:8,padding:"6px 13px",cursor:"pointer",color:fase===i&&!customTarget?accentCol:C.muted,fontSize:11,fontWeight:700}}>
            {f.fase}
          </button>
        ))}
        <button onClick={()=>setEditNutrisi(true)}
          style={{background:"#a855f718",border:"1px solid #a855f730",borderRadius:8,padding:"6px 13px",cursor:"pointer",color:"#a855f7",fontSize:11,fontWeight:700}}>
          ✏️ Edit Target
        </button>
      </div>

      {/* ── Target aktif info ── */}
      <div style={{background:accentCol+"0a",border:"1px solid "+accentCol+"25",borderRadius:10,padding:"10px 14px",display:"flex",flexWrap:"wrap",gap:12,alignItems:"center"}}>
        <span style={{color:accentCol,fontWeight:700,fontSize:12}}>🎯 Target {customTarget?"(Custom)":target.fase}:</span>
        {[["ME",target.me,"kcal/kg"],["PK",target.pk,"%"],["Ca",target.ca,"%"],["P",target.p,"%"],["SK max",target.sk,"%"]].map(([k,v,u])=>
          v ? <span key={k} style={{background:"#ffffff08",borderRadius:7,padding:"3px 9px",fontSize:11,color:"#e2e4f0"}}>
            <b style={{color:accentCol}}>{k}</b> {v}{u}
          </span> : null
        )}
        <span style={{fontSize:10,color:"#555a6a",marginLeft:"auto"}}>📖 {target.referensi}</span>
      </div>

      {/* ── GRID UTAMA ── */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>

        {/* KIRI: Tabel Komposisi Bahan */}
        <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
            <div style={{color:accentCol,fontFamily:"'DM Serif Display',serif",fontSize:14}}>⚗️ Komposisi Bahan (per 100 kg)</div>
            <div style={{display:"flex",gap:6}}>
              <span style={{fontSize:12,color:Math.abs(totalPct-100)<0.5?"#22c55e":"#ef4444",fontWeight:800}}>
                Σ {totalPct.toFixed(2)}%
              </span>
              <button onClick={autoBalance}
                style={{background:"#22c55e15",border:"1px solid #22c55e25",borderRadius:7,padding:"4px 9px",cursor:"pointer",color:"#22c55e",fontSize:10,fontWeight:700}}>
                ⚖️ Balance
              </button>
            </div>
          </div>

          <div style={{overflowY:"auto",maxHeight:440}}>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:11}}>
              <thead>
                <tr style={{borderBottom:"1px solid #252535",background:"#ffffff04"}}>
                  {["Bahan Pakan","% per 100kg","PK%","ME","Ca%","Harga/kg","Hapus"].map(h=>(
                    <th key={h} style={{padding:"6px 7px",color:"#555a6a",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap"}}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {bahan.map((b,i)=>{
                  const db = BAHAN_DB.find(x=>x.id===b.dbId)||{pk:0,me:0,ca:0,harga:0,nama:"?"};
                  const kontribusiPk = ((parseFloat(b.pct)||0)/100 * db.pk).toFixed(2);
                  return (
                    <tr key={b.id} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff02":"transparent"}}>
                      <td style={{padding:"5px 7px",minWidth:150}}>
                        <select value={b.dbId} onChange={e=>updateBahan(b.id,e.target.value)}
                          style={{background:"#13161f",border:"1px solid #252535",borderRadius:5,color:"#e2e4f0",fontSize:10,padding:"3px 5px",width:"100%",maxWidth:180}}>
                          {["Energi","Protein Nabati","Protein NPN","Protein Hewani","Protein Campuran","Mineral","Additive","Hijauan"].map(kat=>(
                            <optgroup key={kat} label={kat}>
                              {BAHAN_DB.filter(x=>x.kat===kat).map(x=>(
                                <option key={x.id} value={x.id}>{x.nama}</option>
                              ))}
                            </optgroup>
                          ))}
                        </select>
                      </td>
                      <td style={{padding:"5px 7px",width:80}}>
                        <input type="number" value={b.pct} min={0} max={100} step={0.05}
                          onChange={e=>updatePct(b.id, e.target.value)}
                          style={{background:"#0d0f18",border:"2px solid "+accentCol+"55",borderRadius:6,color:accentCol,fontSize:12,padding:"4px 7px",width:65,fontWeight:700,textAlign:"right"}}/>
                      </td>
                      <td style={{padding:"5px 7px",color:"#22c55e",fontWeight:600,fontSize:11}}>{kontribusiPk}</td>
                      <td style={{padding:"5px 7px",color:"#9097a8",fontSize:10}}>{db.me}</td>
                      <td style={{padding:"5px 7px",color:"#9097a8",fontSize:10}}>{db.ca}</td>
                      <td style={{padding:"5px 7px",color:"#555a6a",fontSize:10,whiteSpace:"nowrap"}}>{rp(db.harga)}</td>
                      <td style={{padding:"5px 7px"}}>
                        <button onClick={()=>removeBahan(b.id)}
                          style={{background:"#ef444415",border:"none",borderRadius:5,padding:"3px 8px",cursor:"pointer",color:"#ef4444",fontSize:12}}>✕</button>
                      </td>
                    </tr>
                  );
                })}
                {/* TOTAL ROW */}
                <tr style={{borderTop:"2px solid "+accentCol+"40",background:accentCol+"08"}}>
                  <td style={{padding:"8px 7px",color:accentCol,fontWeight:800,fontSize:12}}>TOTAL / 100 kg</td>
                  <td style={{padding:"8px 7px",color:Math.abs(totalPct-100)<0.5?"#22c55e":"#ef4444",fontWeight:800,fontSize:13}}>{totalPct.toFixed(2)}%</td>
                  <td style={{padding:"8px 7px",color:"#22c55e",fontWeight:700}}>{hasil.pk.toFixed(2)}</td>
                  <td style={{padding:"8px 7px",color:"#22c55e",fontWeight:700}}>{hasil.me.toFixed(0)}</td>
                  <td style={{padding:"8px 7px",color:"#22c55e",fontWeight:700}}>{hasil.ca.toFixed(3)}</td>
                  <td style={{padding:"8px 7px",color:"#f59e0b",fontWeight:700}}>{rp(+hasil.harga.toFixed(0))}/kg</td>
                  <td/>
                </tr>
              </tbody>
            </table>
          </div>

          {/* Tambah bahan */}
          <div style={{marginTop:10,display:"flex",gap:8}}>
            <select id="selAdd" defaultValue=""
              style={{flex:1,background:"#13161f",border:"1px solid "+accentCol+"40",borderRadius:7,color:"#e2e4f0",fontSize:11,padding:"7px 8px"}}>
              <option value="">＋ Pilih bahan untuk ditambah...</option>
              {["Energi","Protein Nabati","Protein NPN","Protein Hewani","Protein Campuran","Mineral","Additive","Hijauan"].map(kat=>(
                <optgroup key={kat} label={kat}>
                  {BAHAN_DB.filter(x=>x.kat===kat).map(x=>(
                    <option key={x.id} value={x.id}>{x.nama} | PK {x.pk}% ME {x.me} Ca {x.ca}%</option>
                  ))}
                </optgroup>
              ))}
            </select>
            <button onClick={()=>{ const s=document.getElementById("selAdd"); addBahan(s.value); s.value=""; }}
              style={{background:accentCol+"18",border:"1px solid "+accentCol+"30",borderRadius:7,padding:"7px 14px",cursor:"pointer",color:accentCol,fontWeight:700,fontSize:13}}>＋</button>
          </div>
        </div>

        {/* KANAN: Analisa Hasil */}
        <div style={{display:"flex",flexDirection:"column",gap:10}}>

          {/* Scorecard nutrisi */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
            <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:12}}>📊 Hasil Analisa vs Target</div>
            {[
              {label:"ME (kcal/kg)",      actual:+hasil.me.toFixed(0),  tgt:target.me,  unit:"kcal"},
              {label:"TDN (%)",           actual:+hasil.tdn.toFixed(1), tgt:null,       unit:"%"},
              {label:"Protein Kasar (PK)",actual:+hasil.pk.toFixed(2),  tgt:target.pk,  unit:"%"},
              {label:"Kalsium (Ca)",      actual:+hasil.ca.toFixed(3),  tgt:target.ca,  unit:"%"},
              {label:"Fosfor (P)",        actual:+hasil.p.toFixed(3),   tgt:target.p,   unit:"%"},
              {label:"Serat Kasar (SK)",  actual:+hasil.sk.toFixed(2),  tgt:target.sk,  unit:"%"},
              {label:"Lemak Kasar (LK)", actual:+hasil.lk.toFixed(2),  tgt:null,       unit:"%"},
              {label:"Harga /kg",         actual:+hasil.harga.toFixed(0),tgt:null,      unit:"Rp"},
            ].map(r=>{
              const st = statusOf(r.actual, r.tgt);
              const col = statusColor[st];
              const barW = r.tgt ? Math.min(120, (r.actual/r.tgt)*100) : 50;
              return (
                <div key={r.label} style={{marginBottom:9}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:2}}>
                    <span style={{fontSize:11,color:"#e2e4f0",fontWeight:600}}>{r.label}</span>
                    <div style={{display:"flex",gap:7,alignItems:"center"}}>
                      <span style={{color:col,fontWeight:800,fontSize:12}}>
                        {r.unit==="Rp"?rp(r.actual):r.actual}{r.unit!=="Rp"?r.unit:""}
                      </span>
                      {r.tgt && <span style={{color:"#555a6a",fontSize:10}}>/ tgt {r.tgt}{r.unit}</span>}
                      {r.tgt && <span style={{background:col+"18",color:col,border:"1px solid "+col+"30",borderRadius:20,padding:"1px 8px",fontSize:9,fontWeight:800}}>{statusLabel[st]}</span>}
                    </div>
                  </div>
                  <div style={{height:5,background:"#1c1e2b",borderRadius:3}}>
                    <div style={{height:5,borderRadius:3,background:col,width:barW+"%",transition:"width 0.25s"}}/>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Biaya & Ringkasan */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
            <div style={{color:"#f97316",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💰 Biaya Produksi Ransum</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
              {[
                ["Per kg",          rp(+hasil.harga.toFixed(0))],
                ["Per 50 kg (sak)", rp(+(hasil.harga*50).toFixed(0))],
                ["Per 100 kg",      rp(+(hasil.harga*100).toFixed(0))],
                ["Per ton (1000kg)",rp(+(hasil.harga*1000).toFixed(0))],
                ["Total bahan",     totalPct.toFixed(2)+"%"],
                ["Selisih dari 100%",((totalPct-100).toFixed(2))+"%"],
              ].map(([k,v])=>(
                <div key={k} style={{background:"#ffffff05",borderRadius:8,padding:"8px 10px"}}>
                  <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                  <div style={{color:"#f59e0b",fontWeight:800,fontSize:12}}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Saran Koreksi */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:8}}>🔧 Saran Koreksi</div>
            {saranList.map((s,i)=>(
              <div key={i} style={{background:s.c+"0c",border:"1px solid "+s.c+"22",borderRadius:7,padding:"8px 10px",marginBottom:5,fontSize:11,color:"#e2e4f0",lineHeight:1.5}}>
                {s.m}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Kontribusi Per Bahan (Tabel Detail) ── */}
      <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
        <div style={{color:"#60a5fa",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:12}}>📋 Kontribusi Nutrisi Per Bahan (Rumus BP/BPT×NBP)</div>
        <div style={{overflowX:"auto"}}>
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:11}}>
            <thead>
              <tr style={{borderBottom:"2px solid "+accentCol+"30",background:accentCol+"08"}}>
                {["No","Bahan Pakan","% (kg)","PK%","Kontribusi PK","ME kcal","Kontrib ME","Ca%","Kontrib Ca","P%","Kontrib P","SK%","Harga/kg","Nilai"].map(h=>(
                  <th key={h} style={{padding:"7px 8px",color:accentCol,textAlign:"right",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap"}}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {bahan.map((b,i)=>{
                const db = BAHAN_DB.find(x=>x.id===b.dbId)||{pk:0,me:0,ca:0,p:0,sk:0,harga:0,nama:"?"};
                const f  = (parseFloat(b.pct)||0)/100;
                return (
                  <tr key={b.id} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff02":"transparent"}}>
                    <td style={{padding:"6px 8px",color:"#555a6a",textAlign:"right"}}>{i+1}</td>
                    <td style={{padding:"6px 8px",color:"#e2e4f0",fontWeight:600,whiteSpace:"nowrap"}}>{db.nama}</td>
                    <td style={{padding:"6px 8px",color:accentCol,fontWeight:700,textAlign:"right"}}>{b.pct}</td>
                    <td style={{padding:"6px 8px",color:"#9097a8",textAlign:"right"}}>{db.pk}</td>
                    <td style={{padding:"6px 8px",color:"#22c55e",fontWeight:700,textAlign:"right"}}>{(db.pk*f).toFixed(3)}</td>
                    <td style={{padding:"6px 8px",color:"#9097a8",textAlign:"right"}}>{db.me}</td>
                    <td style={{padding:"6px 8px",color:"#22c55e",fontWeight:700,textAlign:"right"}}>{(db.me*f).toFixed(0)}</td>
                    <td style={{padding:"6px 8px",color:"#9097a8",textAlign:"right"}}>{db.ca}</td>
                    <td style={{padding:"6px 8px",color:"#22c55e",fontWeight:700,textAlign:"right"}}>{(db.ca*f).toFixed(4)}</td>
                    <td style={{padding:"6px 8px",color:"#9097a8",textAlign:"right"}}>{db.p}</td>
                    <td style={{padding:"6px 8px",color:"#22c55e",fontWeight:700,textAlign:"right"}}>{(db.p*f).toFixed(4)}</td>
                    <td style={{padding:"6px 8px",color:"#9097a8",textAlign:"right"}}>{db.sk}</td>
                    <td style={{padding:"6px 8px",color:"#555a6a",textAlign:"right",whiteSpace:"nowrap"}}>{rp(db.harga)}</td>
                    <td style={{padding:"6px 8px",color:"#f59e0b",fontWeight:700,textAlign:"right",whiteSpace:"nowrap"}}>{rp(+(db.harga*f).toFixed(0))}</td>
                  </tr>
                );
              })}
              <tr style={{borderTop:"2px solid "+accentCol+"40",background:accentCol+"0a"}}>
                <td colSpan={2} style={{padding:"8px",color:accentCol,fontWeight:800}}>TOTAL RANSUM / 100kg</td>
                <td style={{padding:"8px",color:Math.abs(totalPct-100)<0.5?"#22c55e":"#ef4444",fontWeight:800,textAlign:"right"}}>{totalPct.toFixed(2)}%</td>
                <td/>
                <td style={{padding:"8px",color:"#22c55e",fontWeight:800,textAlign:"right"}}>{hasil.pk.toFixed(3)}</td>
                <td/>
                <td style={{padding:"8px",color:"#22c55e",fontWeight:800,textAlign:"right"}}>{hasil.me.toFixed(0)}</td>
                <td/>
                <td style={{padding:"8px",color:"#22c55e",fontWeight:800,textAlign:"right"}}>{hasil.ca.toFixed(4)}</td>
                <td/>
                <td style={{padding:"8px",color:"#22c55e",fontWeight:800,textAlign:"right"}}>{hasil.p.toFixed(4)}</td>
                <td style={{padding:"8px",color:"#22c55e",fontWeight:800,textAlign:"right"}}>{hasil.sk.toFixed(2)}</td>
                <td/>
                <td style={{padding:"8px",color:"#f59e0b",fontWeight:800,textAlign:"right",whiteSpace:"nowrap"}}>{rp(+(hasil.harga*100).toFixed(0))}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* ── Contoh Formula Perusahaan ── */}
      <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:8,marginBottom:10}}>
          <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:13}}>🏭 Contoh Formula Perusahaan</div>
          <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
            {Object.keys(CONTOH_FORMULA).map(k=>(
              <button key={k} onClick={()=>setContohKey(k)}
                style={{background:contohKey===k?"#f5c84218":"#0f1118",border:"1px solid "+(contohKey===k?"#f5c84240":C.border),borderRadius:7,padding:"5px 11px",cursor:"pointer",color:contohKey===k?"#f5c842":C.muted,fontSize:11,fontWeight:700}}>
                {{broiler:"🐔",petelur:"🥚",sapi:"🐄",domba:"🐑"}[k]} {k}
              </button>
            ))}
            <button onClick={()=>loadFormula(contohKey)}
              style={{background:"#22c55e18",border:"1px solid #22c55e30",borderRadius:7,padding:"5px 13px",cursor:"pointer",color:"#22c55e",fontWeight:700,fontSize:11}}>
              ⬆️ Load ke Kalkulator
            </button>
          </div>
        </div>
        <div style={{fontSize:10,color:"#555a6a",marginBottom:10}}>📖 {CONTOH_FORMULA[contohKey]?.sumber}</div>
        <div style={{overflowX:"auto"}}>
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:11}}>
            <thead>
              <tr style={{borderBottom:"1px solid #252535",background:"#f5c84208"}}>
                {["No","Bahan Pakan","% (kg per 100kg)","Fungsi / Catatan"].map(h=>(
                  <th key={h} style={{padding:"6px 9px",color:"#f5c842",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase"}}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(CONTOH_FORMULA[contohKey]?.bahan||[]).map((b,i)=>(
                <tr key={i} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff02":"transparent"}}>
                  <td style={{padding:"7px 9px",color:"#555a6a"}}>{i+1}</td>
                  <td style={{padding:"7px 9px",color:"#e2e4f0",fontWeight:700}}>{b.nama}</td>
                  <td style={{padding:"7px 9px",color:"#f5c842",fontWeight:800}}>{b.pct}%</td>
                  <td style={{padding:"7px 9px",color:"#9097a8"}}>{b.catatan}</td>
                </tr>
              ))}
              <tr style={{borderTop:"2px solid #f5c84230",background:"#f5c84208"}}>
                <td colSpan={2} style={{padding:"8px 9px",color:"#f5c842",fontWeight:800}}>TOTAL → Hasil Analisa</td>
                <td style={{padding:"8px 9px",color:"#f5c842",fontWeight:800}}>100%</td>
                <td style={{padding:"8px 9px",color:"#22c55e",fontSize:11,fontWeight:700}}>
                  ME: {CONTOH_FORMULA[contohKey]?.hasil.me} kcal · PK: {CONTOH_FORMULA[contohKey]?.hasil.pk}% · Ca: {CONTOH_FORMULA[contohKey]?.hasil.ca}% · P: {CONTOH_FORMULA[contohKey]?.hasil.p}% · ≈ {rp(CONTOH_FORMULA[contohKey]?.hasil.harga)}/kg
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* ── Edit Target Modal ── */}
      {editNutrisi && (
        <div style={{position:"fixed",inset:0,background:"#000000cc",zIndex:1000,display:"flex",alignItems:"center",justifyContent:"center",padding:20}}>
          <div style={{background:"#0a0c16",border:"1px solid #a855f730",borderRadius:16,padding:24,width:"100%",maxWidth:480}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:16,marginBottom:16}}>✏️ Edit Target Nutrisi Custom</div>
            {[
              {key:"me",  label:"ME (kcal/kg)",  step:10,   def:baseTarget.me},
              {key:"pk",  label:"Protein Kasar (%)", step:0.1, def:baseTarget.pk},
              {key:"ca",  label:"Kalsium Ca (%)", step:0.01, def:baseTarget.ca},
              {key:"p",   label:"Fosfor P (%)",   step:0.01, def:baseTarget.p},
              {key:"sk",  label:"Serat Kasar max (%)", step:0.1, def:baseTarget.sk},
            ].map(f=>(
              <div key={f.key} style={{display:"flex",alignItems:"center",gap:10,marginBottom:10}}>
                <label style={{...S.label,width:200,flexShrink:0}}>{f.label}</label>
                <input type="number" step={f.step}
                  defaultValue={(customTarget||baseTarget)[f.key]||f.def||0}
                  id={"ct_"+f.key}
                  style={{...S.select,flex:1}}/>
              </div>
            ))}
            <div style={{fontSize:11,color:"#555a6a",marginBottom:14}}>Referensi: {baseTarget.referensi}</div>
            <div style={{display:"flex",gap:8}}>
              <button onClick={()=>{
                const ct={...baseTarget};
                ["me","pk","ca","p","sk"].forEach(k=>{
                  const el=document.getElementById("ct_"+k);
                  if(el) ct[k]=parseFloat(el.value)||0;
                });
                ct.referensi="Custom Edit";
                ct.fase="Target Custom";
                setCustomTarget(ct);
                setEditNutrisi(false);
              }} style={{flex:1,background:"#a855f718",border:"1px solid #a855f730",borderRadius:9,padding:"10px",cursor:"pointer",color:"#a855f7",fontWeight:700}}>
                ✅ Simpan Target
              </button>
              <button onClick={()=>{setCustomTarget(null);setEditNutrisi(false);}}
                style={{background:"#ef444415",border:"1px solid #ef444425",borderRadius:9,padding:"10px 14px",cursor:"pointer",color:"#ef4444",fontWeight:700}}>
                ✕ Reset
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};


const PagePakan = ({ feed, setFeed }) => {
  const blank = { type: "", brand: "", unit: "Kg", stock: "", pricePerUnit: "", usagePerDay: "", forAnimal: "semua", date: todayStr(), supplier: "" };
  const [form, setForm]     = useState(blank);
  const [modal, setModal]   = useState(false);
  const [editId, setEditId] = useState(null);
  const [filter, setFilter] = useState("semua");
  const [tabPakan, setTabPakan] = useState("stok");
  const [racikanType, setRacikanType] = useState("sapi");
  const [racikanIdx,  setRacikanIdx]  = useState(0);
  const [indType,  setIndType]  = useState("broiler");
  const [indIdx,   setIndIdx]   = useState(0);
  const [tradType, setTradType] = useState("sapi");
  const [tradIdx,  setTradIdx]  = useState(null);
  const [kalcAnimal, setKalcAnimal] = useState("broiler");
  const [kalcBahan, setKalcBahan]   = useState([
    {id:1,nama:"Jagung Kuning",pk:8.5,me:3370,ca:0.02,p:0.28,sk:2.3,air:14,pct:0,harga:5500},
    {id:2,nama:"Bungkil Kedelai 48%",pk:48,me:2240,ca:0.27,p:0.67,sk:6.0,air:12,pct:0,harga:9000},
    {id:3,nama:"Dedak Padi Halus",pk:12,me:1630,ca:0.12,p:1.50,sk:12,air:12,pct:0,harga:3200},
    {id:4,nama:"Tepung Ikan 65%",pk:65,me:2830,ca:5.11,p:3.10,sk:1.0,air:10,pct:0,harga:18000},
    {id:5,nama:"MBM (Tepung Daging&Tulang)",pk:50,me:2210,ca:10.0,p:5.10,sk:2.5,air:10,pct:0,harga:12000},
    {id:6,nama:"CPO/Minyak Sawit",pk:0,me:8600,ca:0,p:0,sk:0,air:0,pct:0,harga:12000},
    {id:7,nama:"DCP (Dikalsium Fosfat)",pk:0,me:0,ca:22.0,p:18.0,sk:0,air:5,pct:0,harga:12000},
    {id:8,nama:"Limestone/Kapur",pk:0,me:0,ca:38.0,p:0,sk:0,air:0,pct:0,harga:800},
    {id:9,nama:"Premix Broiler",pk:0,me:0,ca:0,p:0,sk:0,air:0,pct:0,harga:80000},
    {id:10,nama:"Garam NaCl",pk:0,me:0,ca:0,p:0,sk:0,air:0,pct:0,harga:2000},
  ]);
  const [kalcEdit, setKalcEdit] = useState(null);
  const [kalcNew,  setKalcNew]  = useState({nama:"",pk:0,me:0,ca:0,p:0,sk:0,air:12,pct:0,harga:0});

  const filtered     = filter === "semua" ? feed : feed.filter(f => f.forAnimal === filter || f.forAnimal === "semua");
  const totalNilai   = feed.reduce((s, f) => s + f.stock * f.pricePerUnit, 0);
  const totalPerHari = feed.reduce((s, f) => s + f.usagePerDay * f.pricePerUnit, 0);
  const kritis       = feed.filter(f => f.usagePerDay > 0 && f.stock / f.usagePerDay < 7).length;

  const save = () => {
    const p = { ...form, stock: +form.stock, pricePerUnit: +form.pricePerUnit, usagePerDay: +form.usagePerDay };
    if (editId) setFeed(feed.map(f => f.id === editId ? { ...p, id: editId } : f));
    else setFeed([...feed, { id: newId("PK", feed), ...p }]);
    setModal(false); setEditId(null); setForm(blank);
  };
  const openEdit = f => { setForm({ ...f }); setEditId(f.id); setModal(true); };
  const del = id => { if (window.confirm("Hapus pakan?")) setFeed(feed.filter(f => f.id !== id)); };

  const typeOpts = [{v:"sapi",l:"🐄 Sapi",c:"#f5c842"},{v:"domba",l:"🐑 Domba",c:"#a3e635"},{v:"broiler",l:"🐔 Broiler",c:"#e879f9"},{v:"petelur",l:"🥚 Layer",c:"#f59e0b"}];
  const curRacikan   = RACIKAN_PAKAN[racikanType] || [];
  const activeFormula = curRacikan[racikanIdx] || curRacikan[0];

  // Hitung harga per kg formula berdasarkan komposisi bahan
  const hargaFormula = activeFormula
    ? +(activeFormula.bahan.reduce((s,b) => s + (b.pct/100)*b.harga, 0)).toFixed(0)
    : 0;

  return (
    <div style={S.col}>
      {/* STAT CARDS */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))", gap:12 }}>
        <KartuStat label="Jenis Pakan" value={feed.length} color={C.buy} icon="pakan" />
        <KartuStat label="Nilai Stok" value={rp(totalNilai)} color={C.info} icon="chart" />
        <KartuStat label="Biaya/Hari" value={rp(totalPerHari)} color={C.breed} icon="expense" />
        <KartuStat label="Stok Kritis" value={kritis + " item"} color={C.expense} icon="warn" />
      </div>

      {/* MAIN TABS */}
      <div style={{ display:"flex", borderBottom:"1px solid #1c1e2b", overflowX:"auto" }}>
        {[{id:"stok",l:"📦 Stok Pakan"},{id:"racikan",l:"🧪 Panduan Racikan"},{id:"industri",l:"🏭 Standar CP & Japfa"},{id:"tradisional",l:"🌿 Pakan Tradisional"},{id:"kalkulator",l:"🧮 Kalkulator Ransum"}].map(t=>(
          <button key={t.id} onClick={()=>setTabPakan(t.id)}
            style={{background:"none",border:"none",borderBottom:"2px solid "+(tabPakan===t.id?"#f97316":"transparent"),
              color:tabPakan===t.id?"#f97316":"#555a6a",padding:"8px 18px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>
            {t.l}
          </button>
        ))}
      </div>

      {/* ════ TAB STOK ════ */}
      {tabPakan === "stok" && (
        <>
          <div style={{ ...S.row, justifyContent:"space-between", flexWrap:"wrap", gap:8 }}>
            <FilterBar active={filter} items={[{v:"semua",l:"Semua"},{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer"}]} onChange={setFilter} color={C.buy} />
            <BtnSec onClick={()=>{ setEditId(null); setForm(blank); setModal(true); }} color={C.buy}><Ico n="plus" size={13} color={C.buy} /> Tambah Pakan</BtnSec>
          </div>
          <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(240px,1fr))", gap:14 }}>
            {filtered.map(f => {
              const days = f.usagePerDay > 0 ? Math.floor(f.stock / f.usagePerDay) : 999;
              const low  = f.usagePerDay > 0 && days < 7;
              const fc   = f.forAnimal==="sapi"?"#f5c842":f.forAnimal==="domba"?"#a3e635":f.forAnimal==="broiler"?"#e879f9":f.forAnimal==="petelur"?"#f59e0b":C.muted;
              return (
                <div key={f.id} style={{ background:low?C.expense+"08":C.card, border:"1px solid "+(low?C.expense+"35":C.border), borderRadius:13, padding:16 }}>
                  <div style={{ ...S.row, justifyContent:"space-between", alignItems:"flex-start", marginBottom:12 }}>
                    <div>
                      <div style={{ color:C.text, fontWeight:700, fontSize:14 }}>{f.type}</div>
                      <div style={{ color:C.dim, fontSize:11, marginTop:2 }}>{f.brand}{f.supplier&&" · "+f.supplier}</div>
                    </div>
                    <div style={{ display:"flex", flexDirection:"column", gap:4, alignItems:"flex-end" }}>
                      <span style={{ background:fc+"15", color:fc, border:"1px solid "+fc+"28", borderRadius:20, padding:"2px 8px", fontSize:10, fontWeight:700 }}>
                        {f.forAnimal==="semua"?"Semua":f.forAnimal==="sapi"?"🐄 Sapi":f.forAnimal==="domba"?"🐑 Domba":f.forAnimal==="broiler"?"🐔 Broiler":f.forAnimal==="petelur"?"🥚 Layer":f.forAnimal}
                      </span>
                      {low&&<span style={{ background:C.expense+"15", color:C.expense, border:"1px solid "+C.expense+"28", borderRadius:20, padding:"2px 8px", fontSize:10, fontWeight:700 }}>KRITIS!</span>}
                    </div>
                  </div>
                  <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:7, marginBottom:12 }}>
                    {[["STOK",f.stock+" "+f.unit,C.text],["PAKAI/HARI",f.usagePerDay+" "+f.unit,"#f5c842"],["HARGA/UNIT",rp(f.pricePerUnit),C.info],["SISA",days===999?"∞":days+" hari",low?C.expense:C.sell]].map(([k,v,col])=>(
                      <div key={k} style={{ background:"#ffffff06", borderRadius:8, padding:"8px 10px" }}>
                        <div style={{ fontSize:9, color:C.dim, fontWeight:700, marginBottom:3 }}>{k}</div>
                        <div style={{ color:col, fontWeight:700, fontSize:12 }}>{v}</div>
                      </div>
                    ))}
                  </div>
                  <div style={{ height:3, background:C.border, borderRadius:3, marginBottom:8 }}>
                    <div style={{ height:3, borderRadius:3, background:low?C.expense:C.sell, width:Math.min(100,days===999?100:(days/30)*100)+"%", transition:"width 0.4s" }}/>
                  </div>
                  <div style={{ ...S.row, justifyContent:"space-between" }}>
                    <span style={{ fontSize:11, color:C.dim }}>Nilai: {rp(f.stock*f.pricePerUnit)}</span>
                    <div style={S.row}>
                      <button onClick={()=>openEdit(f)} style={{ background:C.info+"14", border:"1px solid "+C.info+"22", borderRadius:6, padding:"4px 7px", cursor:"pointer", color:C.info }}><Ico n="edit" size={11} color={C.info}/></button>
                      <button onClick={()=>del(f.id)} style={{ background:C.expense+"14", border:"1px solid "+C.expense+"22", borderRadius:6, padding:"4px 7px", cursor:"pointer", color:C.expense }}><Ico n="del" size={11} color={C.expense}/></button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}

      {/* ════ TAB RACIKAN ════ */}
      {tabPakan === "racikan" && (
        <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
          {/* Pilih jenis ternak */}
          <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
            {typeOpts.map(t=>(
              <button key={t.v} onClick={()=>{ setRacikanType(t.v); setRacikanIdx(0); }}
                style={{ background:racikanType===t.v?t.c+"20":"#0f1118", border:"1px solid "+(racikanType===t.v?t.c+"50":C.border), borderRadius:10, padding:"9px 18px", cursor:"pointer", color:racikanType===t.v?t.c:C.muted, fontWeight:700, fontSize:13 }}>
                {t.l}
              </button>
            ))}
          </div>

          {/* Pilih fase / formula */}
          {curRacikan.length > 1 && (
            <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
              {curRacikan.map((r,i)=>(
                <button key={i} onClick={()=>setRacikanIdx(i)}
                  style={{ background:racikanIdx===i?r.color+"18":"#0f1118", border:"1px solid "+(racikanIdx===i?r.color+"40":C.border), borderRadius:8, padding:"7px 14px", cursor:"pointer", color:racikanIdx===i?r.color:C.muted, fontWeight:700, fontSize:11 }}>
                  {r.fase}
                </button>
              ))}
            </div>
          )}

          {activeFormula && (
            <>
              {/* Header formula */}
              <div style={{ background:activeFormula.color+"0e", border:"1px solid "+activeFormula.color+"30", borderRadius:14, padding:"16px 20px" }}>
                <div style={{ color:activeFormula.color, fontFamily:"'DM Serif Display',serif", fontSize:18, fontWeight:700, marginBottom:6 }}>
                  🧪 {activeFormula.nama}
                </div>
                <div style={{ color:"#9097a8", fontSize:12, marginBottom:8 }}>{activeFormula.ket}</div>
                <div style={{ display:"flex", gap:10, flexWrap:"wrap", alignItems:"center" }}>
                  <span style={{ background:activeFormula.color+"18", color:activeFormula.color, border:"1px solid "+activeFormula.color+"30", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>
                    🎯 {activeFormula.target}
                  </span>
                  <span style={{ background:"#3b82f615", color:"#3b82f6", border:"1px solid #3b82f628", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>
                    💰 Est. Harga/kg: {rp(hargaFormula)}
                  </span>
                  <span style={{ background:"#22c55e15", color:"#22c55e", border:"1px solid #22c55e28", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>
                    🧬 Fase: {activeFormula.fase}
                  </span>
                </div>
              </div>

              {/* 2 kolom: Nutrisi + Bahan */}
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>

                {/* STANDAR NUTRISI */}
                <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16 }}>
                  <div style={{ color:"#3b82f6", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:12 }}>
                    🔬 Standar Kandungan Nutrisi
                  </div>
                  <div style={{ fontSize:10, color:"#555a6a", marginBottom:10 }}>
                    Benchmark: {activeFormula.nutrisi[0]?.benchmark||"NRC / SNI"}
                  </div>
                  {activeFormula.nutrisi.map((n,i)=>(
                    <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"6px 0", borderBottom:"1px solid #1c1e2b" }}>
                      <div>
                        <div style={{ fontSize:11, color:"#e2e4f0", fontWeight:600 }}>{n.label}</div>
                        <div style={{ fontSize:9, color:"#555a6a", marginTop:1 }}>{n.benchmark}</div>
                      </div>
                      <div style={{ textAlign:"right" }}>
                        <div style={{ color:activeFormula.color, fontWeight:800, fontSize:12 }}>{n.nilai}</div>
                        <div style={{ fontSize:9, color:"#555a6a" }}>ideal: {n.ideal}</div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* KOMPOSISI BAHAN */}
                <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16 }}>
                  <div style={{ color:"#22c55e", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:12 }}>
                    ⚗️ Komposisi Bahan per 100 kg
                  </div>
                  <div style={{ overflowY:"auto", maxHeight:360 }}>
                    <table style={{ width:"100%", borderCollapse:"collapse", fontSize:11 }}>
                      <thead>
                        <tr style={{ borderBottom:"1px solid #252535" }}>
                          {["Bahan","kg","Harga/kg","Nilai","Fungsi"].map(h=>(
                            <th key={h} style={{ padding:"5px 8px", color:"#555a6a", textAlign:"left", fontSize:9, fontWeight:800, textTransform:"uppercase", whiteSpace:"nowrap" }}>{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {activeFormula.bahan.map((b,i)=>(
                          <tr key={i} style={{ borderBottom:"1px solid #1c1e2b", background:i%2?"#ffffff02":"transparent" }}>
                            <td style={{ padding:"6px 8px", color:"#e2e4f0", fontWeight:600, fontSize:11 }}>{b.bahan}</td>
                            <td style={{ padding:"6px 8px", color:activeFormula.color, fontWeight:700, whiteSpace:"nowrap" }}>{b.pct} kg</td>
                            <td style={{ padding:"6px 8px", color:"#9097a8", whiteSpace:"nowrap" }}>{rp(b.harga)}</td>
                            <td style={{ padding:"6px 8px", color:"#22c55e", fontWeight:700, whiteSpace:"nowrap" }}>{rp(b.pct*b.harga/100)}</td>
                            <td style={{ padding:"6px 8px", color:"#555a6a", fontSize:10 }}>{b.fungsi}</td>
                          </tr>
                        ))}
                        <tr style={{ borderTop:"2px solid #22c55e33", background:"#22c55e0a" }}>
                          <td style={{ padding:"8px", color:"#22c55e", fontWeight:800 }}>TOTAL / 100 kg</td>
                          <td style={{ padding:"8px", color:activeFormula.color, fontWeight:800 }}>{activeFormula.bahan.reduce((s,b)=>s+b.pct,0).toFixed(1)} kg</td>
                          <td/>
                          <td style={{ padding:"8px", color:"#22c55e", fontWeight:800 }}>{rp(hargaFormula*100)}</td>
                          <td style={{ padding:"8px", color:"#3b82f6", fontSize:11, fontWeight:700 }}>≈ {rp(hargaFormula)}/kg</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>

              {/* PANDUAN PEMBERIAN */}
              <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16 }}>
                <div style={{ color:"#f97316", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:12 }}>
                  📋 Panduan Pemberian Pakan & Tips Praktis
                </div>
                <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(280px,1fr))", gap:8 }}>
                  {activeFormula.feeding.map((tip,i)=>(
                    <div key={i} style={{ background:tip.startsWith("⚠️")?"#ef444410":"#ffffff05", border:"1px solid "+(tip.startsWith("⚠️")?"#ef444428":"#252535"), borderRadius:9, padding:"9px 13px", display:"flex", gap:9, alignItems:"flex-start" }}>
                      <span style={{ color:tip.startsWith("⚠️")?"#ef4444":"#f97316", fontSize:14, lineHeight:1.2, marginTop:1 }}>{i+1}.</span>
                      <span style={{ color:tip.startsWith("⚠️")?"#fca5a5":C.muted, fontSize:12, lineHeight:1.5 }}>{tip}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Disclaimer */}
              <div style={{ background:"#3b82f60a", border:"1px solid #3b82f620", borderRadius:10, padding:"10px 14px", fontSize:11, color:"#555a6a", display:"flex", gap:8, alignItems:"flex-start" }}>
                <span style={{ color:"#3b82f6", fontSize:14 }}>ℹ️</span>
                <span>Formula ini berdasarkan standar NRC, SNI, dan panduan nutrisi Cobb/Ross/Lohmann Brown. Harga bahan baku adalah estimasi Juni 2026 — sesuaikan dengan kondisi pasar lokal. Konsultasikan dengan ahli nutrisi ternak atau penyuluh dinas peternakan setempat untuk implementasi skala besar.</span>
              </div>
            </>
          )}
        </div>
      )}
      {/* ════ TAB STANDAR INDUSTRI ════ */}
      {tabPakan === "industri" && (
        <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
          {/* Pilih jenis */}
          {[{v:"broiler",l:"🐔 Broiler",c:"#e879f9"},{v:"layer",l:"🥚 Layer",c:"#f59e0b"},{v:"sapi",l:"🐄 Sapi",c:"#f5c842"},{v:"domba",l:"🐑 Domba",c:"#a3e635"}].map(t=>(
            <button key={t.v} onClick={()=>{ setIndType(t.v); setIndIdx(0); }}
              style={{ background:indType===t.v?t.c+"20":"#0f1118", border:"1px solid "+(indType===t.v?t.c+"50":C.border), borderRadius:10, padding:"9px 18px", cursor:"pointer", color:indType===t.v?t.c:C.muted, fontWeight:700, fontSize:13, display:"inline-block", marginRight:8, marginBottom:8 }}>
              {t.l}
            </button>
          ))}

          {/* Pilih produk */}
          {(STANDAR_INDUSTRI[indType]||[]).length > 1 && (
            <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
              {(STANDAR_INDUSTRI[indType]||[]).map((r,i)=>(
                <button key={i} onClick={()=>setIndIdx(i)}
                  style={{ background:indIdx===i?r.warna+"18":"#0f1118", border:"1px solid "+(indIdx===i?r.warna+"40":C.border), borderRadius:8, padding:"7px 14px", cursor:"pointer", color:indIdx===i?r.warna:C.muted, fontWeight:700, fontSize:11 }}>
                  {r.kode}
                </button>
              ))}
            </div>
          )}

          {(() => {
            const prod = (STANDAR_INDUSTRI[indType]||[])[indIdx] || (STANDAR_INDUSTRI[indType]||[])[0];
            if (!prod) return null;
            return (
              <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
                {/* Header */}
                <div style={{ background:prod.warna+"0e", border:"1px solid "+prod.warna+"30", borderRadius:14, padding:"16px 20px" }}>
                  <div style={{ display:"flex", justifyContent:"space-between", flexWrap:"wrap", gap:10, marginBottom:10 }}>
                    <div>
                      <div style={{ color:prod.warna, fontFamily:"'DM Serif Display',serif", fontSize:18, fontWeight:700 }}>🏭 {prod.produk}</div>
                      <div style={{ color:"#9097a8", fontSize:12, marginTop:3 }}>📦 Kode: {prod.kode} &nbsp;|&nbsp; 🏢 {prod.produsen}</div>
                    </div>
                    <div style={{ display:"flex", flexDirection:"column", gap:5 }}>
                      <span style={{ background:prod.warna+"18", color:prod.warna, border:"1px solid "+prod.warna+"30", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>🎯 {prod.target}</span>
                      <span style={{ background:"#22c55e15", color:"#22c55e", border:"1px solid #22c55e28", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>⏱ Fase: {prod.fase}</span>
                      <span style={{ background:"#f5c84215", color:"#f5c842", border:"1px solid #f5c84228", borderRadius:20, padding:"3px 12px", fontSize:11, fontWeight:700 }}>💰 {prod.harga}</span>
                    </div>
                  </div>
                  <div style={{ background:"#3b82f60a", border:"1px solid #3b82f620", borderRadius:8, padding:"8px 12px", fontSize:11, color:"#9097a8" }}>
                    <span style={{ color:"#3b82f6", fontWeight:700 }}>📝 Catatan: </span>{prod.catatan}
                  </div>
                </div>

                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
                  {/* Kandungan Nutrisi */}
                  <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16 }}>
                    <div style={{ color:"#3b82f6", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:12 }}>🔬 Kandungan Nutrisi Resmi</div>
                    {prod.nutrisi.map((n,i)=>(
                      <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"6px 0", borderBottom:"1px solid #1c1e2b" }}>
                        <div>
                          <div style={{ fontSize:11, color:"#e2e4f0", fontWeight:600 }}>{n.label}</div>
                          <div style={{ fontSize:9, color:"#555a6a", marginTop:1 }}>{n.standar}</div>
                        </div>
                        <div style={{ color:n.label.includes("KRITIS")?"#ef4444":prod.warna, fontWeight:800, fontSize:12, textAlign:"right", maxWidth:140 }}>{n.nilai}</div>
                      </div>
                    ))}
                  </div>

                  {/* Bahan Baku + Program */}
                  <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
                    <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16, flex:1 }}>
                      <div style={{ color:"#22c55e", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:10 }}>⚗️ Komposisi Bahan Baku</div>
                      <div style={{ fontSize:11, color:"#9097a8", lineHeight:1.6 }}>{prod.bahan}</div>
                    </div>
                    <div style={{ background:"#0f1118", border:"1px solid #1c1e2b", borderRadius:13, padding:16, flex:1 }}>
                      <div style={{ color:"#f97316", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:10 }}>📋 Program Pemberian</div>
                      {prod.program.map((tip,i)=>(
                        <div key={i} style={{ background:tip.includes("⚠️")||tip.includes("WAJIB")?"#ef444410":"#ffffff04", border:"1px solid "+(tip.includes("⚠️")||tip.includes("WAJIB")?"#ef444428":"#252535"), borderRadius:7, padding:"7px 10px", marginBottom:5, display:"flex", gap:7 }}>
                          <span style={{ color:tip.includes("⚠️")||tip.includes("WAJIB")?"#ef4444":"#f97316", fontSize:12, flexShrink:0 }}>{i+1}.</span>
                          <span style={{ color:tip.includes("⚠️")||tip.includes("WAJIB")?"#fca5a5":"#9097a8", fontSize:11, lineHeight:1.5 }}>{tip}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                <div style={{ background:"#3b82f60a", border:"1px solid #3b82f620", borderRadius:10, padding:"9px 14px", fontSize:11, color:"#555a6a", display:"flex", gap:8 }}>
                  <span style={{ color:"#3b82f6" }}>ℹ️</span>
                  <span>Data nutrisi bersumber dari label resmi produk, e-Katalog LKPP, dan jurnal ilmiah terverifikasi. Kandungan aktual dapat berbeda per batch produksi — selalu cek label kemasan terbaru dan konsultasikan dengan sales representative CP/Japfa di daerah Anda.</span>
                </div>
              </div>
            );
          })()}
        </div>
      )}

      {/* ════ TAB PAKAN TRADISIONAL ════ */}
      {tabPakan === "tradisional" && (
        <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
          {/* Pilih jenis ternak */}
          <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
            {[{v:"sapi",l:"🐄 Sapi",c:"#f5c842"},{v:"domba",l:"🐑 Domba",c:"#a3e635"},{v:"broiler",l:"🐔 Broiler",c:"#e879f9"},{v:"petelur",l:"🥚 Layer",c:"#f59e0b"}].map(t=>(
              <button key={t.v} onClick={()=>{ setTradType(t.v); setTradIdx(null); }}
                style={{ background:tradType===t.v?t.c+"20":"#0f1118", border:"1px solid "+(tradType===t.v?t.c+"50":C.border), borderRadius:10, padding:"9px 18px", cursor:"pointer", color:tradType===t.v?t.c:C.muted, fontWeight:700, fontSize:13 }}>
                {t.l}
              </button>
            ))}
          </div>

          {/* Disclaimer */}
          <div style={{ background:"#22c55e0a", border:"1px solid #22c55e20", borderRadius:9, padding:"9px 14px", fontSize:11, color:"#555a6a", display:"flex", gap:8 }}>
            <span style={{ color:"#22c55e" }}>🌿</span>
            <span>Pakan tradisional adalah bahan yang umum digunakan peternak rakyat Indonesia — mudah didapat, murah, dan terbukti secara empiris. Kombinasikan dengan konsentrat pabrikan untuk hasil optimal.</span>
          </div>

          {/* Daftar bahan */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(320px,1fr))", gap:12 }}>
            {(PAKAN_TRADISIONAL[tradType]||[]).map((p,i)=>{
              const isOpen = tradIdx === i;
              return (
                <div key={i} style={{ background:"#0f1118", border:"1px solid "+(isOpen?p.warna+"50":"#1c1e2b"), borderRadius:13, overflow:"hidden", cursor:"pointer" }}
                  onClick={()=>setTradIdx(isOpen?null:i)}>
                  {/* Header */}
                  <div style={{ padding:"14px 16px", background:isOpen?p.warna+"0c":"transparent" }}>
                    <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:8 }}>
                      <div style={{ flex:1 }}>
                        <div style={{ color:p.warna, fontWeight:800, fontSize:14, marginBottom:3 }}>{p.nama}</div>
                        <div style={{ color:"#9097a8", fontSize:11, marginBottom:4 }}>{p.jenis}</div>
                        <div style={{ display:"flex", gap:6, flexWrap:"wrap" }}>
                          <span style={{ background:p.warna+"15", color:p.warna, border:"1px solid "+p.warna+"30", borderRadius:20, padding:"2px 9px", fontSize:10, fontWeight:700 }}>{p.kode}</span>
                          <span style={{ background:"#22c55e10", color:"#22c55e", border:"1px solid #22c55e25", borderRadius:20, padding:"2px 9px", fontSize:10, fontWeight:700 }}>{p.rating}</span>
                        </div>
                      </div>
                      <div style={{ color:"#555a6a", fontSize:14 }}>{isOpen?"▲":"▼"}</div>
                    </div>
                    <div style={{ marginTop:8, display:"flex", gap:10, flexWrap:"wrap" }}>
                      <span style={{ fontSize:11, color:"#555a6a" }}>💰 {p.biaya}</span>
                      <span style={{ fontSize:11, color:"#9097a8" }}>📍 {p.ketersediaan?.substring(0,45)}...</span>
                    </div>
                  </div>

                  {/* Detail accordion */}
                  {isOpen && (
                    <div style={{ padding:"0 16px 16px", borderTop:"1px solid #1c1e2b" }}>
                      {/* Kandungan Nutrisi */}
                      <div style={{ color:"#3b82f6", fontFamily:"'DM Serif Display',serif", fontSize:12, margin:"12px 0 8px" }}>🔬 Kandungan Nutrisi</div>
                      {p.nutrisi.map((n,ni)=>(
                        <div key={ni} style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", padding:"5px 0", borderBottom:"1px solid #1c1e2b20" }}>
                          <div style={{ flex:1 }}>
                            <div style={{ fontSize:11, color:"#e2e4f0", fontWeight:600 }}>{n.label}</div>
                            <div style={{ fontSize:9, color:"#555a6a", marginTop:1 }}>{n.ket}</div>
                          </div>
                          <div style={{ color:n.label.includes("WAJIB")||n.label.includes("⚠️")?"#ef4444":p.warna, fontWeight:800, fontSize:12, textAlign:"right", maxWidth:130, marginLeft:8 }}>{n.nilai}</div>
                        </div>
                      ))}

                      {/* Cara & Tips */}
                      <div style={{ marginTop:12, display:"flex", flexDirection:"column", gap:8 }}>
                        <div style={{ background:"#f97316" + "0a", border:"1px solid #f9731620", borderRadius:8, padding:"8px 11px" }}>
                          <span style={{ color:"#f97316", fontWeight:700, fontSize:11 }}>📋 Cara Pemberian: </span>
                          <span style={{ color:"#9097a8", fontSize:11 }}>{p.cara}</span>
                        </div>
                        <div style={{ background:p.tips?.includes("⚠️")?"#ef444408":"#22c55e08", border:"1px solid "+(p.tips?.includes("⚠️")?"#ef444420":"#22c55e20"), borderRadius:8, padding:"8px 11px" }}>
                          <span style={{ color:p.tips?.includes("⚠️")?"#ef4444":"#22c55e", fontWeight:700, fontSize:11 }}>💡 Tips: </span>
                          <span style={{ color:p.tips?.includes("⚠️")?"#fca5a5":"#9097a8", fontSize:11 }}>{p.tips}</span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ════ TAB KALKULATOR RANSUM ════ */}
      {tabPakan === "kalkulator" && <KalkulatorRansum />}

      {modal && (
        <Modal title={editId ? "Edit Pakan" : "Tambah Pakan"} onClose={() => { setModal(false); setEditId(null); }}>
          <div style={S.grid2}>
            <Inp label="Jenis Pakan" value={form.type} onChange={v => setForm({ ...form, type: v })} options={["Konsentrat Sapi","Konsentrat Domba","Broiler Starter","Broiler Grower","Broiler Finisher","Layer Mash Pre-layer","Layer Mash Peak","Layer Mash Afkir","Hijauan Segar","Dedak Padi","Ampas Tahu","Molases","Bungkil Kelapa","Jerami","Silase","Limestone/Kapur","Premix Vitamin Ayam","Probiotik EM4","Grit/Kerikil","Obat Cacing","Vitamin/Mineral","Garam Mineral","Mineral Block"]} />
            <Inp label="Merk / Brand" value={form.brand} onChange={v => setForm({ ...form, brand: v })} />
            <Inp label="Untuk Ternak" value={form.forAnimal} onChange={v => setForm({ ...form, forAnimal: v })} options={[{ v: "semua", l: "Semua" }, { v: "sapi", l: "🐄 Sapi" }, { v: "domba", l: "🐑 Domba" }, { v: "broiler", l: "🐔 Broiler" }, { v: "petelur", l: "🥚 Layer/Petelur" }]} />
            <Inp label="Satuan" value={form.unit} onChange={v => setForm({ ...form, unit: v })} options={["Kg", "Liter", "Karung", "Ikat", "Botol", "Blok"]} />
            <Inp label="Stok" value={form.stock} onChange={v => setForm({ ...form, stock: v })} type="number" />
            <Inp label="Harga per Satuan (Rp)" value={form.pricePerUnit} onChange={v => setForm({ ...form, pricePerUnit: v })} type="number" />
            <Inp label="Pemakaian per Hari" value={form.usagePerDay} onChange={v => setForm({ ...form, usagePerDay: v })} type="number" />
            <Inp label="Tanggal Masuk" value={form.date} onChange={v => setForm({ ...form, date: v })} type="date" />
            <Inp label="Supplier Pakan" value={form.supplier} onChange={v => setForm({ ...form, supplier: v })} span />
          </div>
          <BtnPrimary onClick={save} color={C.buy} full>Simpan Pakan</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ===== DATA REFERENSI PENYAKIT & OBAT ===== */
const REF_PENYAKIT = {
  sapi: [
    {
      penyakit:"Demam Tiga Hari (BEF)", gejala:"Demam tiba-tiba 40–41°C, gemetar, nafsu makan turun, lumpuh sementara",
      penyebab:"Bovine Ephemeral Fever Virus (arbovirus, vektor lalat)", tingkat:"⚠️ Sedang",
      obat:[
        {nama:"Flunixin Meglumine (NSAID)",dosis:"2.2 mg/kg BB IM/IV",frekuensi:"1×/hari, 3 hari",ket:"Anti-inflamasi + antipiretik utama"},
        {nama:"Meloxicam 15mg/mL",dosis:"0.5 mg/kg BB SC/IV",frekuensi:"1×/hari, 2–3 hari",ket:"NSAID alternatif, lebih aman lambung"},
        {nama:"Vitamin B kompleks injeksi",dosis:"10–20 mL IM",frekuensi:"1×/hari, 3–5 hari",ket:"Recovery saraf dan otot"},
        {nama:"Infus NaCl 0.9% / RL",dosis:"5–10 L IV pelan",frekuensi:"Sekali atau 2× jika dehidrasi",ket:"Terapi cairan — jaga hidrasi"},
      ],
      pencegahan:"Vaksin BEF (tahunan), kendalikan populasi lalat, kandang bersih",
      tradisional:[
        {nama:"Jahe Merah + Kunyit rebus",dosis:"250g jahe + 250g kunyit direbus 2L air, dinginkan",cara:"Campurkan ke minum 2× sehari",ket:"Antipiretik alami + anti-inflamasi rempah"},
        {nama:"Air Kelapa Muda",dosis:"2–3 liter per oral langsung",cara:"Berikan langsung dari buah segar",ket:"Rehidrasi alami + elektrolit — mengganti cairan saat demam"},
        {nama:"Daun Pepaya Muda (tumbuk)",dosis:"300–500g daun tumbuk halus + air 500mL",cara:"Peras, berikan 2× sehari",ket:"Antipiretik tradisional — enzim papain bantu recovery"},
        {nama:"Garam + Gula Merah (oralit tradisional)",dosis:"1 sdm garam + 2 sdm gula merah + 1L air hangat",cara:"Per oral 2–3× sehari",ket:"Pengganti elektrolit darurat sebelum drh tiba"},
      ],
    },
    {
      penyakit:"Kembung (Bloat / Tympani)", gejala:"Perut kiri membesar keras, sesak napas, gelisah, bisa mati dalam 30 menit",
      penyebab:"Gas terperangkap rumen — hijauan legum basah, perubahan pakan mendadak", tingkat:"🚨 Kritis",
      obat:[
        {nama:"Simethicone / Bloatex oral",dosis:"100–200 mL per oral langsung",frekuensi:"Sekali, ulang 30 menit jika belum membaik",ket:"Pecahkan busa rumen — PERTOLONGAN PERTAMA"},
        {nama:"Poloxalene (anti-bloat)",dosis:"25–30 g per oral",frekuensi:"Sekali atau campur pakan pencegahan",ket:"Surfaktan anti-buih terbaik"},
        {nama:"Minyak Kelapa / Nabati",dosis:"200–500 mL per oral",frekuensi:"Sekali darurat",ket:"Alternatif lokal — pecah busa darurat"},
        {nama:"Trokar + kanula (bedah darurat)",dosis:"Tusuk titik lapar kiri",frekuensi:"Hanya jika semua gagal + veteriner",ket:"Prosedur darurat oleh dokter hewan"},
      ],
      pencegahan:"Adaptasi pakan 14 hari, batasi legum segar pagi hari, hindari hijauan basah embun",
      tradisional:[
        {nama:"Minyak Kelapa Murni (VCO)",dosis:"200–500 mL per oral langsung",cara:"Masukkan lewat mulut, usap tenggorokan, bantu telan",ket:"Pecah busa gas rumen — PERTOLONGAN PERTAMA paling efektif secara lokal"},
        {nama:"Minyak Goreng biasa",dosis:"200–400 mL per oral",cara:"Campur sedikit garam, berikan langsung",ket:"Alternatif darurat — surfaktan alami pecah buih gas"},
        {nama:"Jalan / Gerak paksa",dosis:"Jalan 15–30 menit aktif",cara:"Tuntun berjalan cepat di tempat miring",ket:"Stimulasi gerakan rumen — bantu keluarkan gas secara mekanis"},
        {nama:"Pijat / Urut perut kiri",dosis:"Pijat melingkar 10–15 menit",cara:"Tekan lembut searah jarum jam pada lapar kiri",ket:"Stimulasi peristaltik rumen — kombinasikan dengan berjalan"},
        {nama:"Asap rokok / Jamu temulawak oral",dosis:"Setengah batang asap ditiup ke hidung ATAU 300g temulawak rebus",cara:"Stimulasi reflex sendawa (eructasi)",ket:"Cara lama peternak — efek psikologis + stimulasi saraf"},
      ],
    },
    {
      penyakit:"Cacingan (Helminthiasis)", gejala:"Kurus, bulu kusam, diare, submandibular edema (bottle jaw), anemia",
      penyebab:"Fasciola hepatica, Haemonchus, Ascaris spp.", tingkat:"⚠️ Sedang",
      obat:[
        {nama:"Albendazole 10%",dosis:"7.5 mg/kg BB PO (bolus/serbuk)",frekuensi:"Sekali, ulangi 30 hari",ket:"Broad-spectrum: cacing hati + lambung + paru"},
        {nama:"Ivermectin 1% injeksi",dosis:"0.2 mg/kg BB SC",frekuensi:"Sekali, ulangi 2 minggu",ket:"Cacing + ektoparasit (kutu, tungau, lalat)"},
        {nama:"Fenbendazole (Panacur)",dosis:"7.5 mg/kg BB PO",frekuensi:"1×/hari, 3–5 hari",ket:"Aman untuk sapi bunting"},
        {nama:"Rafoxanide 2.5%",dosis:"7.5 mg/kg BB PO",frekuensi:"Sekali",ket:"Khusus Fasciola (cacing hati) dewasa"},
      ],
      pencegahan:"Rotasi padang rumput, hindari penggembalaan area berair, program obcac 3 bulan sekali",
      tradisional:[
        {nama:"Biji Pepaya Kering (tumbuk)",dosis:"50–100g biji papaya kering tumbuk halus",cara:"Campur ke pakan konsentrat 1× seminggu",ket:"Enzim papain biji pepaya — anthelmintik alami terbukti riset"},
        {nama:"Tembakau Kering (suspensi)",dosis:"50g tembakau + 1L air, rendam semalam",cara:"Saring, berikan 200mL per oral — hati-hati dosis!",ket:"Nikotin alkaloid — anthelmintik tradisional tapi berisiko overdosis"},
        {nama:"Bawang Putih Tumbuk",dosis:"100–150g bawang putih tumbuk + 500mL air",cara:"Peras, berikan 2× sehari selama 5 hari",ket:"Allicin antifungal + antiparasit — efektif kombinasi cacing usus"},
        {nama:"Daun Neem / Mimba (Azadirachta indica)",dosis:"200g daun neem segar tumbuk + 500mL air",cara:"Peras dan berikan per oral 1× sehari, 5 hari",ket:"Azadirachtin — anthelmintik + anti-ektoparasit spektrum luas"},
        {nama:"Kulit Delima (Punica granatum)",dosis:"100g kulit delima kering + 500mL air rebus",cara:"Saring dingin, berikan 300mL 2× sehari",ket:"Tanin kulit delima — mengikat kulit cacing (tannin-bound)"},
      ],
    },
    {
      penyakit:"Mastitis (Radang Ambing)", gejala:"Ambing merah bengkak panas, susu berubah (gumpalan/darah), demam",
      penyebab:"Staphylococcus aureus, Streptococcus, E.coli", tingkat:"⚠️ Sedang",
      obat:[
        {nama:"Amoxicillin + Clav (Synulox) intramammary",dosis:"1 syringe/puting, 3 mL",frekuensi:"2×/hari, 3–5 hari",ket:"Antibiotik langsung ke ambing — STANDAR"},
        {nama:"Cloxacillin intramammary (dry cow)",dosis:"1 syringe/puting",frekuensi:"Sekali saat kering kandang",ket:"Pencegahan mastitis saat dry-off"},
        {nama:"Penisilin G prokain 300rb IU",dosis:"10.000–20.000 IU/kg BB IM",frekuensi:"2×/hari, 5–7 hari",ket:"Sistemik untuk mastitis berat"},
        {nama:"Oxytocin 10 IU",dosis:"10–20 IU IM/IV",frekuensi:"Sebelum pemerahan 3–4×/hari",ket:"Bantu pengosongan ambing — recovery cepat"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IV",frekuensi:"1×/hari, 3 hari",ket:"Reduksi inflamasi + demam"},
      ],
      pencegahan:"Dipping puting 0.5% iodine post-pemerahan, sanitasi kandang, dry cow therapy rutin",
      tradisional:[
        {nama:"Kompres air hangat + garam",dosis:"Air hangat 40°C + 1 sdm garam, kompres kain bersih",cara:"Kompres ambing 2–3× sehari 15 menit",ket:"Melancarkan peredaran darah + reduksi bengkak"},
        {nama:"Daun Sirih (Piper betle) rebus",dosis:"20 lembar daun sirih + 2L air rebus 15 menit",cara:"Dinginkan, gunakan untuk kompres + bilas puting",ket:"Eugenol + tanin daun sirih — antibakteri alami pada kulit ambing"},
        {nama:"Lidah Buaya (Aloe vera) gel",dosis:"Gel aloe murni secukupnya",cara:"Oleskan ke ambing yang bengkak 3× sehari",ket:"Anti-inflamasi + penyejuk jaringan — bantu reduksi edema"},
        {nama:"Minyak Kelapa + Kunyit (pasta)",dosis:"3 sdm VCO + 2 sdm kunyit bubuk, aduk rata",cara:"Oleskan di ambing, diamkan 1 jam lalu bersihkan",ket:"Kurkumin anti-inflamasi + VCO antibakteri kulit"},
        {nama:"Pijat ambing + perah sering",dosis:"Pijat lembut + perah 4–6× sehari",cara:"Kosongkan ambing sesering mungkin",ket:"KRITIS: ambing harus dikosongkan agar bakteri tidak berkembang"},
      ],
    },
    {
      penyakit:"Anthrax (Antraks)", gejala:"Kematian mendadak, darah hitam keluar lubang tubuh, tidak ada rigor mortis",
      penyebab:"Bacillus anthracis (spora tanah)", tingkat:"🚨 ZOONOSIS — Laporkan ke Dinas!",
      obat:[
        {nama:"Penisilin G prokain 300rb IU",dosis:"20.000–40.000 IU/kg BB IM",frekuensi:"2–3×/hari, 5–7 hari",ket:"⚠️ JANGAN buka bangkai — risiko spora!"},
        {nama:"Oxytetracycline 20% LA",dosis:"20 mg/kg BB IM",frekuensi:"1×/hari, 5 hari",ket:"Alternatif penisilin"},
        {nama:"Serum antianthrax 50–100 mL",dosis:"50 mL IV/IM",frekuensi:"Sekali — dosis awal",ket:"Diberikan bersama antibiotik"},
      ],
      pencegahan:"Vaksin Anthrax Sterne (setahun sekali), jangan buka bangkai di lapangan, laporkan ke Dinas Peternakan",
      tradisional:[
        {nama:"⚠️ TIDAK DISARANKAN pengobatan mandiri",dosis:"—",cara:"LAPOR ke Dinas Peternakan segera",ket:"Anthrax ZOONOSIS FATAL — jangan tangani sendiri tanpa APD. Obat tradisional TIDAK efektif untuk Bacillus anthracis"},
        {nama:"Biosekuriti darurat: kapur tohor",dosis:"Tabur kapur tohor (quicklime) tebal di sekitar bangkai",cara:"Gunakan sarung tangan + masker. Jangan buka bangkai!",ket:"Inaktivasi spora lingkungan — standar peternakan kasus anthrax"},
      ],
    },
    {
      penyakit:"PMK Sapi — Protokol Khusus Sapi Dewasa", gejala:"Produksi susu drop 50–80%, vesikel lidah/gusi/bibir, kuku terlepas, puting lecet, sapi induk tidak mau menyusui, kematian pedet tinggi",
      penyebab:"FMDV Serotype O (dominan) + Serotype A — sapi lebih parah dari domba karena anatomi kuku dan produksi susu", tingkat:"🚨 KRITIS untuk sapi perah & induk bunting",
      obat:[
        {nama:"Protokol PMK Sapi Perah — TERAPI SUPORTIF",dosis:"Seluruh obat bersifat suportif",frekuensi:"Durasi sakit 10–21 hari",ket:"TIDAK ADA antivirus. Tujuan: cegah infeksi sekunder, jaga produksi, selamatkan pedet"},
        {nama:"Penisilin G Prokain 300rb IU",dosis:"20.000–30.000 IU/kg BB IM",frekuensi:"2×/hari, 7–10 hari",ket:"Cegah mastitis sekunder + infeksi kuku Fusobacterium"},
        {nama:"Flunixin Meglumine 5%",dosis:"2.2 mg/kg BB IV/IM",frekuensi:"1×/hari, 5 hari",ket:"Anti-nyeri kuku + antipiretik — sapi akan mau makan setelah nyeri berkurang"},
        {nama:"Oxytocin 10 IU",dosis:"10–20 IU IM sebelum pemerahan",frekuensi:"3–4×/hari selama laktasi",ket:"Penting untuk sapi perah — pastikan ambing tetap kosong cegah mastitis"},
        {nama:"Intramammary Antibiotic (Cloxacillin / Amoxicillin)",dosis:"1 syringe/puting yang terinfeksi",frekuensi:"2×/hari sampai susu normal",ket:"Cegah mastitis sekunder — puting lecet sangat rentan infeksi Strep/Staph"},
        {nama:"Zinc Sulfate 10% foot bath",dosis:"Rendam kuku ZnSO₄ 10%, 20 menit",frekuensi:"2×/hari",ket:"Regenerasi tanduk kuku + antiseptik — kuku sapi lebih besar dan lebih parah dari domba"},
        {nama:"Vitamin E 500 IU + Selenium injeksi",dosis:"1 mL Se/50 kg BB SC",frekuensi:"Sekali per minggu, 2 kali",ket:"Antioksidan + imun — penting untuk induk bunting + pedet yang lemah"},
        {nama:"Kolostrum buatan / susu pengganti (pedet)",dosis:"2–3L per pedet per hari",frekuensi:"Setiap 6 jam untuk pedet 0–7 hari",ket:"Pedet yang induknya PMK HARUS diberi kolostrum buatan atau dari sapi sehat lain"},
        {nama:"Vaksin PMK Bivalent O+A inaktif",dosis:"3 mL IM (sapi dewasa)",frekuensi:"2× interval 4 minggu + booster 4–6 bulan",ket:"Program vaksinasi massal — efektif 21 hari setelah vaksin kedua"},
      ],
      pencegahan:"Vaksinasi massal 2× setahun, foot bath ZnSO₄ permanen di pintu kandang, biosekuriti ketat (orang masuk + kendaraan + peralatan), karantina sapi baru 14 hari, lapor Dinas",
      tradisional:[
        {nama:"Foot Bath Kapur Tohor 5% (pengganti ZnSO₄)",dosis:"500g kapur tohor / 10L air",cara:"Buat kolam kecil di pintu kandang, sapi lewat 2×/hari",ket:"Inaktivasi FMDV di kuku + antiseptik — pH tinggi kapur bunuh virus PMK"},
        {nama:"Air Garam + Cuka (rendam kuku)",dosis:"3 sdm garam + 3 sdm cuka / 5L air",cara:"Rendam kuku 20 menit pagi dan sore",ket:"Osmotik + asam asetat — kombinasi tradisional untuk desinfeksi kuku PMK"},
        {nama:"Rebusan Sirih + Tawas (cuci puting)",dosis:"20 lembar sirih + 2 sdm tawas + 2L air rebus",cara:"Dinginkan, lap puting dengan kain steril setelah pemerahan",ket:"Puting lecet PMK sangat rentan mastitis — antiseptik sirih+tawas paling praktis"},
        {nama:"Susu Pedet dari Induk PMK — PROSEDUR",dosis:"Pompa/perah susu induk PMK terpisah",cara:"JANGAN beri ke pedet langsung. Pasteurisasi 70°C 30 menit baru berikan",ket:"FMDV mati di susu yang dipasteurisasi — pedet harus tetap dapat susu induknya"},
        {nama:"Jamu Kunyit + Temulawak + Jahe oral",dosis:"400g kunyit + 200g temulawak + 200g jahe / 10L air",cara:"Rebus saring, campur ke air minum sapi 2×/hari",ket:"Imunomodulator + antipiretik + anti-inflamasi — bantu recovery + nafsu makan"},
        {nama:"Pakan Lunak Alternatif (silase / rumput dicacah halus)",dosis:"Berikan pakan 3× lebih sering dalam porsi kecil",cara:"Potong sangat halus, campur molases untuk palatabilitas",ket:"Mulut sapi PMK luka parah — pakan kasar TIDAK bisa dimakan, pakan lunak jaga kondisi tubuh"},
      ],
    },
    {
      penyakit:"Penyakit Jembrana (JD)", gejala:"Demam tinggi 40–42°C, pembengkakan kelenjar limfe, pendarahan, kematian 10–17%",
      penyebab:"Jembrana Disease Virus (Lentivirus) — khas sapi Bali, vektor lalat penghisap", tingkat:"🚨 Kritis — mortalitas tinggi",
      obat:[
        {nama:"Penisilin G Prokain 300rb IU",dosis:"20.000 IU/kg BB IM",frekuensi:"2×/hari, 7–10 hari",ket:"Cegah infeksi bakteri sekunder — tidak ada antivirus JD"},
        {nama:"Oxytetracycline 20% LA",dosis:"20 mg/kg BB IM",frekuensi:"1× setiap 3 hari",ket:"Broad-spectrum + long-acting"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IV/IM",frekuensi:"1×/hari, 3 hari",ket:"Antipiretik + anti-inflamasi"},
        {nama:"Dexamethasone 0.1–0.2 mg/kg",dosis:"0.1 mg/kg BB IM",frekuensi:"1×/hari, 3 hari (hati-hati!)",ket:"Kurangi inflamasi parah — hanya jika diindikasikan drh"},
        {nama:"Infus Dextrose 5% + RL",dosis:"5–10 L IV pelan",frekuensi:"1–2× sehari selama sakit",ket:"Jaga hidrasi + energi saat tidak mau makan"},
        {nama:"Vitamin C injeksi 200mg/mL",dosis:"10–20 mL IV/IM",frekuensi:"1×/hari, 5–7 hari",ket:"Antioksidan + boost imun"},
      ],
      pencegahan:"Vaksin JD (wajib di Bali/NTB), kendalikan lalat Stomoxys, karantina sapi masuk",
      tradisional:[
        {nama:"Air Kelapa Muda",dosis:"3–5 liter segar per hari",cara:"Berikan langsung sebagai minuman",ket:"Rehidrasi alami + elektrolit — pengganti infus darurat"},
        {nama:"Jamu Kunyit + Jahe + Temulawak",dosis:"300g kunyit + 150g jahe + 150g temulawak / 10L air",cara:"Rebus, saring, campur ke air minum",ket:"Imunomodulator + antipiretik rempah"},
        {nama:"Daun Pepaya 500g tumbuk",dosis:"500g daun pepaya tumbuk + 500mL air",cara:"Peras, berikan 2× sehari",ket:"Antipiretik + enzim papain — percepat recovery"},
        {nama:"Gula Merah + Garam (oralit)",dosis:"2 sdm gula merah + 1 sdm garam / 1L air hangat",cara:"Per oral 3× sehari",ket:"Darurat sebelum drh tiba — cegah dehidrasi"},
      ],
    },
    {
      penyakit:"Brucellosis (Keluron Menular)", gejala:"Keguguran mendadak pada trimester 3, radang testis jantan, sapi kelihatan sehat",
      penyebab:"Brucella abortus — ZOONOSIS penting, menular lewat cairan keguguran", tingkat:"🚨 ZOONOSIS — Wajib Lapor",
      obat:[
        {nama:"⚠️ Indonesia: kebijakan test & slaughter",dosis:"Tidak ada pengobatan resmi",frekuensi:"—",ket:"Hewan positif Brucella WAJIB diafkir sesuai kebijakan pemerintah"},
        {nama:"Oxytetracycline LA (terapi paliatif)",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 4 kali",ket:"Hanya jika keputusan afkir ditunda — tidak menyembuhkan"},
        {nama:"Vaksin RB51 (preventif)",dosis:"2 mL SC (betina <8 bulan)",frekuensi:"Sekali seumur hidup",ket:"Pencegahan terbaik — program pemerintah"},
      ],
      pencegahan:"Program vaksinasi S19/RB51, test serologis rutin (RBT), jangan biarkan anjing makan plasenta",
      tradisional:[
        {nama:"⚠️ Tidak ada pengobatan tradisional efektif",dosis:"—",cara:"WAJIB lapor ke Dinas Peternakan",ket:"Brucellosis zoonosis — manusia bisa terinfeksi lewat susu mentah / kontak cairan aborsi"},
        {nama:"Sanitasi area aborsi dengan kapur tohor",dosis:"Taburi kapur tohor area persalinan",cara:"Bakar atau kubur plasenta + janin",ket:"Inaktivasi Brucella di lingkungan"},
      ],
    },
    {
      penyakit:"Luka & Abses", gejala:"Bengkak berisi nanah, luka terbuka, demam lokal, hewan tampak tidak nyaman",
      penyebab:"Infeksi bakteri sekunder (Staph, Strep, Fusobacterium) lewat luka tusuk/gigitan/alat kandang", tingkat:"⚠️ Sedang",
      obat:[
        {nama:"Penisilin G Prokain",dosis:"20.000 IU/kg BB IM",frekuensi:"2×/hari, 5–7 hari",ket:"First-line untuk abses jaringan lunak"},
        {nama:"Amoxicillin-Clavulanate",dosis:"8.75 mg/kg BB IM/SC",frekuensi:"1×/hari, 5–7 hari",ket:"Efektif bakteri penghasil beta-laktamase"},
        {nama:"Iodine 10% (Betadine) spray",dosis:"Semprotkan langsung ke luka",frekuensi:"2–3×/hari",ket:"Antiseptik topikal — standar peternakan"},
        {nama:"Hidrogen Peroksida 3%",dosis:"Cuci luka dengan H₂O₂ 3%",frekuensi:"1–2×/hari (max 3 hari)",ket:"Debridemen biokimia — bersihkan jaringan mati"},
        {nama:"Drainase abses (insisi)",dosis:"Insisi di titik paling lunak abses",frekuensi:"Sekali — bersihkan nanah tuntas",ket:"Prosedur utama — antibiotik TIDAK efektif tanpa drainase"},
        {nama:"Oxytetracycline spray (Terramycin Spray)",dosis:"Semprotkan merata ke luka",frekuensi:"1–2×/hari",ket:"Antibiotik topikal + warna biru lindungi lalat"},
      ],
      pencegahan:"Hilangkan benda tajam di kandang, vaksin Blackleg, periksa luka tiap hari",
      tradisional:[
        {nama:"Madu Murni (topikal)",dosis:"Madu murni oleskan merata",cara:"Tutup luka dengan madu, balut kain bersih, ganti 2×/hari",ket:"H₂O₂ alami madu — antibakteri + stimulasi granulasi jaringan baru"},
        {nama:"Kunyit + Minyak Kelapa (pasta luka)",dosis:"3 sdm kunyit bubuk + 4 sdm VCO",cara:"Aduk rata jadi pasta, oleskan ke luka 2–3× sehari",ket:"Kurkumin anti-inflamasi + VCO antibakteri — klasik peternakan Jawa"},
        {nama:"Daun Sirih + Garam (cuci luka)",dosis:"15 lembar sirih + 1 sdt garam + 1L air rebus",cara:"Dinginkan, cuci luka 2× sehari",ket:"Tanin sirih + garam — antiseptik + osmotik tarik nanah"},
        {nama:"Getah Jarak Pagar (Jatropha)",dosis:"Oleskan getah segar tipis-tipis",cara:"Teteskan langsung ke luka bersih",ket:"Kurzasin + tanin — antiseptik + koagulan kuat, percepat tutup luka"},
        {nama:"Abu Gosok + Minyak Kelapa",dosis:"1 sdm abu bersih + 2 sdm VCO",cara:"Oleskan ke luka kering, ganti setiap hari",ket:"Cara lama peternak — alkali abu + antibakteri VCO"},
      ],
    },
    {
      penyakit:"Diare Neonatal (Pedet/Anak)", gejala:"Mencret encer putih/kuning, dehidrasi cepat, lemah, anak mati dalam 24–72 jam tanpa penanganan",
      penyebab:"E.coli K99 (paling umum), Rotavirus, Coronavirus, Salmonella, kekurangan kolostrum", tingkat:"🚨 Kritis pada anak sapi <2 minggu",
      obat:[
        {nama:"Oralit sapi (ORS veteriner)",dosis:"2–4 L per oral, 3–4× sehari",frekuensi:"Setiap 6 jam sampai membaik",ket:"TERAPI UTAMA — rehidrasi oral LEBIH PENTING dari antibiotik"},
        {nama:"NaCl 0.9% + Dextrose 5% IV",dosis:"40–80 mL/kg IV pelan (tetes)",frekuensi:"Kasus berat dehidrasi >8%",ket:"Infus intravena jika tidak bisa minum — oleh drh"},
        {nama:"Trimethoprim + Sulfamethoxazole",dosis:"15 mg/kg BB PO/IM (dosis kombinasi)",frekuensi:"2×/hari, 3–5 hari",ket:"Anti-E.coli + Salmonella — first-line diare bakteri"},
        {nama:"Neomycin Sulfate oral",dosis:"22 mg/kg BB PO",frekuensi:"2×/hari, 3–5 hari",ket:"Antibiotik usus lokal — minimal absorpsi sistemik"},
        {nama:"Probiotik veteriner (Lactobacillus)",dosis:"1 sachet per oral",frekuensi:"2×/hari, 5–7 hari",ket:"Restorasi flora usus — percepat recovery"},
        {nama:"Kolostrum (preventif)",dosis:"2–4 L kolostrum dalam 6 jam pertama",frekuensi:"Sekali setelah lahir",ket:"PENCEGAHAN TERBAIK — immunoglobulin pasif anti-E.coli K99"},
      ],
      pencegahan:"Pastikan kolostrum cukup dalam 6 jam pertama, sanitasi kandang beranak, vaksin induk (ScourGuard)",
      tradisional:[
        {nama:"Oralit tradisional (gula + garam + air)",dosis:"1L air matang + 1 sdm gula + 1/4 sdt garam",cara:"Berikan 300–500mL per jam via botol dot",ket:"Rehidrasi darurat — efektif sementara menunggu drh"},
        {nama:"Air Rebusan Daun Jambu Biji",dosis:"20 lembar jambu muda + 1L air rebus 15 menit",cara:"Saring dingin, berikan 200mL per oral 3× sehari",ket:"Tanin astringent — mengurangi diare + anti-bakteri usus"},
        {nama:"Nasi Kering Hangat + Garam",dosis:"300g nasi kering + 1 sdt garam + 500mL air hangat",cara:"Lumatkan, berikan via botol dot",ket:"Sumber karbohidrat mudah cerna + elektrolit darurat"},
        {nama:"Tepung Beras + Air Kelapa",dosis:"3 sdm tepung beras + 500mL air kelapa muda",cara:"Aduk rata, berikan hangat 2–3× sehari",ket:"Elektrolit alami + amilosa mudah serap — cegah dehidrasi"},
        {nama:"Arang Aktif / Arang Kayu Bakar",dosis:"1–2 sdm arang halus + 500mL air",cara:"Campurkan, berikan per oral 2× sehari",ket:"Adsorben toksin bakteri alami — dipakai peternak tradisional"},
      ],
    },
    {
      penyakit:"Radang Kuku / Pododermatitis (Foot Rot)", gejala:"Pincang parah, kuku merah bengkak, bau busuk, demam, sapi enggan berdiri",
      penyebab:"Fusobacterium necrophorum + Bacteroides melaninogenicus — infeksi bakteri anaerobik", tingkat:"⚠️ Sedang — sangat nyeri",
      obat:[
        {nama:"Penisilin G 300rb IU + Streptomisin",dosis:"20.000 IU/kg + 10 mg/kg IM",frekuensi:"2×/hari, 5–7 hari",ket:"First-line foot rot — penisilin sangat efektif untuk Fusobacterium"},
        {nama:"Oxytetracycline 20% LA",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 3 kali",ket:"Long-acting — praktis untuk foot rot"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IM/IV",frekuensi:"1×/hari, 3–5 hari",ket:"Anti-nyeri + anti-inflamasi kuku"},
        {nama:"Iodine 10% + Zinc Sulfate rendam",dosis:"10% iodine oleskan ATAU rendam ZnSO₄ 10%",frekuensi:"1–2×/hari selama perawatan",ket:"Topikal antiseptik + desinfeksi kuku"},
        {nama:"Perban kuku + Bedah nekrosis",dosis:"Potong jaringan mati, perban steril",frekuensi:"Ganti perban setiap 2–3 hari",ket:"Prosedur pendukung — debridemen jaringan nekrotik"},
      ],
      pencegahan:"Foot bath CuSO₄ 5% mingguan, kandang kering + bersih, hindari berlumpur, kuku dipotong rutin",
      tradisional:[
        {nama:"Rendam Kuku Air Garam Panas",dosis:"3 sdm garam / 5L air panas 45°C",cara:"Rendam kuku 20 menit, 2× sehari",ket:"Osmotik tarik nanah + antiseptik — klasik foot rot tradisional"},
        {nama:"Ter (Tar) / Aspal Panas (topikal)",dosis:"Oleskan ter cair hangat ke kuku sakit",cara:"Oleskan tipis, biarkan mengeras",ket:"Antiseptik anaerobik — membunuh Fusobacterium kontak"},
        {nama:"Tembakau Basah + Garam (kompres)",dosis:"100g tembakau basah + 2 sdm garam",cara:"Tempelkan ke kuku, balut karung goni, ganti setiap hari",ket:"Nikotin + osmotik garam — cara lama peternak untuk foot rot"},
        {nama:"Daun Sirih + Kunyit (kompres)",dosis:"20 lembar sirih tumbuk + 3 sdm kunyit bubuk",cara:"Tempelkan ke kuku bengkak, balut kain bersih",ket:"Tanin sirih + kurkumin — anti-inflamasi + antiseptik"},
        {nama:"Kandang Kering (non-obat, UTAMA)",dosis:"Keringkan kandang, ganti alas",cara:"Pastikan lantai tidak berlumpur, tabur kapur",ket:"Foot rot TIDAK AKAN sembuh di kandang basah berlumpur — ini lebih penting dari semua obat"},
      ],
    },
    {
      penyakit:"Kencing Darah — Babesiosis (Piroplasmosis)", gejala:"Urin merah tua/coklat seperti kopi atau darah segar, demam tinggi 41–42°C, anemia parah (selaput putih pucat), icterus (kuning), nafsu makan hilang, produksi susu drop, bisa mati 24–48 jam",
      penyebab:"Babesia bovis / B.bigemina — protozoa darah merah, vektor CAPLAK Boophilus (Rhipicephalus) microplus. Musim hujan = puncak serangan caplak.", tingkat:"🚨 Kritis — bisa mati dalam 48 jam tanpa penanganan",
      obat:[
        {nama:"Diminazene Aceturate (Berenil/Veriben) 7%",dosis:"3.5 mg/kg BB IM/SC (larutkan dengan air steril)",frekuensi:"Sekali — ulangi 48–72 jam jika belum membaik",ket:"OBAT SPESIFIK anti-Babesia terbaik — standar RPH nasional. Jangan overdosis (neurotoksik >7mg/kg)"},
        {nama:"Imidocarb Dipropionate (Imizol) 12%",dosis:"3 mg/kg BB IM",frekuensi:"Sekali, bisa diulang 14 hari",ket:"Lebih aman dari Berenil — efek residual protektif 4–6 minggu setelah injeksi"},
        {nama:"Oxytetracycline 20% LA",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 3 kali",ket:"Tambahan jika ada ko-infeksi Anaplasma — sering menyertai Babesia"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IV/IM",frekuensi:"1×/hari, 3 hari",ket:"Antipiretik + anti-inflamasi — turunkan demam tinggi cepat"},
        {nama:"Infus NaCl 0.9% + Dextrose 5%",dosis:"5–10 L IV drip pelan",frekuensi:"1–2× sehari sampai kondisi membaik",ket:"Terapi cairan KRITIS — hemolisis masif menyebabkan dehidrasi + hipoglikemia parah"},
        {nama:"Transfusi Darah Segar",dosis:"2–4 L darah segar dari sapi sehat kompatibel",frekuensi:"Sekali — kasus anemia sangat parah (PCV <10%)",ket:"Prosedur darurat — minta bantuan drh. Ambil darah dari sapi vaksin/imun Babesia"},
        {nama:"Vitamin B12 (Cyanocobalamin) 1mg/mL",dosis:"5–10 mL IM",frekuensi:"1×/hari, 5–7 hari",ket:"Stimulasi eritropoiesis — regenerasi sel darah merah pasca hemolisis"},
        {nama:"Fe-Dextran injeksi",dosis:"5–10 mL IM",frekuensi:"2–3× interval 3 hari",ket:"Suplementasi besi — regenerasi hemoglobin pasca Babesia"},
        {nama:"Ivermectin 1% + Amitraz (Tick Control)",dosis:"Ivermectin 0.2 mg/kg SC + Amitraz 0.05% semprot",frekuensi:"Ivermectin 1× + Amitraz setiap 2 minggu",ket:"Basmi caplak vektor Babesia — WAJIB dilakukan bersamaan dengan pengobatan"},
      ],
      pencegahan:"Program celup/semprot caplak rutin (Amitraz/Cypermethrin) setiap 2 minggu saat musim hujan, vaksin Babesia (tersedia di beberapa negara), rotasi kandang, periksa caplak tiap minggu",
      tradisional:[
        {nama:"Air Kelapa Muda + Madu",dosis:"3–5 liter air kelapa + 3 sdm madu per hari",cara:"Berikan langsung atau campur ke minum",ket:"Elektrolit alami + antioksidan madu — bantu recovery hemolisis + jaga hidrasi"},
        {nama:"Jus Daun Pepaya + Temulawak",dosis:"300g daun pepaya muda + 200g temulawak / 3L air",cara:"Blender saring, berikan 500mL 2×/hari",ket:"Papain + xanthorrhizol — stimulasi eritropoiesis + anti-inflamasi hati"},
        {nama:"Rebusan Daun Kumis Kucing (Orthosiphon)",dosis:"100g daun kumis kucing segar + 2L air rebus",cara:"Saring dingin, berikan 500mL–1L 2×/hari",ket:"Diuretik alami + antioksidan — bantu flush hemoglobin bebas dari ginjal, cegah gagal ginjal"},
        {nama:"Kunyit + Jahe + Gula Aren oral",dosis:"300g kunyit + 200g jahe + 100g gula aren / 5L air",cara:"Rebus saring, berikan hangat 2×/hari",ket:"Kurkumin hepatoprotektif + gingerol — lindungi hati dari kerusakan ikterus hemolitik"},
        {nama:"Basmi Caplak dengan Minyak Kelapa + Belerang",dosis:"200mL VCO + 2 sdm sulfur powder",cara:"Oleskan ke seluruh tubuh sapi, fokus lipatan kulit",ket:"Membunuh caplak secara mekanis + sulfur acarisida — lakukan BERSAMAAN dengan pengobatan"},
        {nama:"Daun Kemangi + Bawang Putih (repellent caplak)",dosis:"200g kemangi + 200g bawang putih + 2L air rebus",cara:"Semprotkan ke tubuh sapi sore hari",ket:"Eugenol + allicin — repellent alami caplak Boophilus, pencegahan jangka panjang"},
      ],
    },
    {
      penyakit:"Kencing Darah — Anaplasmosis", gejala:"Urin kemerahan ringan–sedang, anemia parah progresif, demam 40–41°C, icterus ringan, hewan sangat lemah, berdiri sempoyongan, tidak ada hemoglobin dalam urin (berbeda dari Babesia)",
      penyebab:"Anaplasma marginale — bakteri intraeritrositik (Rickettsiales), vektor CAPLAK + lalat penghisap. Sering ko-infeksi dengan Babesia.", tingkat:"⚠️ Kritis — anemia progresif lambat tapi fatal",
      obat:[
        {nama:"Oxytetracycline 20% LA (PILIHAN UTAMA)",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 4–5 kali (total 12–15 hari)",ket:"ANTIBIOTIK SPESIFIK Anaplasma — OTC long-acting paling efektif dan tersedia"},
        {nama:"Doxycycline 10% oral",dosis:"10 mg/kg BB PO",frekuensi:"1×/hari, 10–14 hari",ket:"Alternatif OTC oral — tetrasiklin terbaik kedua untuk Anaplasma"},
        {nama:"Diminazene Aceturate (Berenil) 7%",dosis:"3.5 mg/kg BB IM",frekuensi:"Sekali",ket:"Efektif Babesia ko-infeksi — kurang efektif Anaplasma sendiri"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IV",frekuensi:"1×/hari, 3 hari",ket:"Antipiretik + anti-inflamasi anemia hemolitik"},
        {nama:"Vitamin B12 + Fe-Dextran",dosis:"10 mL B12 IM + 10 mL Fe IM",frekuensi:"Setiap 3 hari, 3 kali",ket:"Regenerasi eritrosit — PENTING karena Anaplasma merusak sel darah merah masif"},
        {nama:"Infus Dextrose 5% + NaCl",dosis:"5–8 L IV pelan",frekuensi:"1×/hari saat lemah parah",ket:"Jaga energi + hidrasi — sapi Anaplasma sering tidak mau makan berminggu-minggu"},
      ],
      pencegahan:"Kontrol caplak + lalat Tabanus, program OTC pencegahan di daerah endemik (5 mg/kg BB IM setiap 28 hari), hindari stres (anaplasma carrier bisa kambuh saat stres)",
      tradisional:[
        {nama:"Rebusan Daun Kumis Kucing + Tempuyung",dosis:"100g kumis kucing + 100g tempuyung + 2L air rebus",cara:"Saring, berikan 500mL 2×/hari selama pemulihan",ket:"Diuretik + antioksidan — bantu eliminasi produk hemolisis via ginjal"},
        {nama:"Suplemen Darah: Hati Sapi + Bayam",dosis:"300g hati sapi cincang + 300g bayam / hari",cara:"Campur ke pakan",ket:"Besi organik + folat — regenerasi hemoglobin alami pasca anemia Anaplasma"},
        {nama:"Air Kelapa + Gula Aren",dosis:"3–4 liter air kelapa + 2 sdm gula aren",cara:"Berikan langsung 2–3× sehari",ket:"Elektrolit + energi cepat — sapi anemia sangat butuh energi"},
        {nama:"Basmi Caplak + Lalat (VCO + Sulfur)",dosis:"VCO + sulfur oleskan ke tubuh",cara:"Fokus ke telinga, lipatan kulit, ekor",ket:"Eliminasi vektor — Anaplasma tidak bisa sembuh permanen jika caplak masih ada"},
      ],
    },
  ],
  domba: [
    {
      penyakit:"Cacingan / Haemonchosis", gejala:"Anemia parah (FAMACHA score 4–5), bottle jaw, kematian mendadak pada anak",
      penyebab:"Haemonchus contortus — cacing lambung pengisap darah", tingkat:"🚨 Kritis pada domba",
      obat:[
        {nama:"Levamisole 7.5%",dosis:"7.5 mg/kg BB PO/SC",frekuensi:"Sekali, ulangi 2–4 minggu",ket:"Efektif H.contortus — cek resistensi"},
        {nama:"Closantel 10%",dosis:"10 mg/kg BB PO",frekuensi:"Sekali, efek residual 6–8 minggu",ket:"Terbaik untuk H.contortus + Fasciola"},
        {nama:"Monepantel (Zolvix)",dosis:"2.5 mg/kg BB PO",frekuensi:"Sekali",ket:"Golongan amino-acetonitrile — untuk kasus resisten"},
        {nama:"Ivermectin 1%",dosis:"0.2 mg/kg BB SC",frekuensi:"Sekali, ulangi 2 minggu",ket:"⚠️ JANGAN overdosis pada domba muda"},
        {nama:"Transfusi darah / Dekstran Fe",dosis:"Per indikasi drh.",frekuensi:"Kasus anemia berat",ket:"Suportif untuk anemia parah"},
      ],
      pencegahan:"FAMACHA scoring mingguan, rotasi anthelmintic tiap periode, hindari padang basah jam pagi",
      tradisional:[
        {nama:"Biji Pepaya + Biji Labu (Cucurbita)",dosis:"50g biji papaya + 50g biji labu tumbuk halus",cara:"Campur ke konsentrat 1× seminggu, 3–4 minggu",ket:"Cucurbitin (labu) + papain (pepaya) — anthelmintik alami, aman untuk domba"},
        {nama:"Daun Neem / Mimba segar",dosis:"150g daun neem segar tumbuk",cara:"Peras + 300mL air, oral 1× sehari 5 hari",ket:"Azadirachtin spektrum luas — efektif H.contortus muda"},
        {nama:"Bawang Putih tumbuk",dosis:"80–100g bawang putih + 300mL air",cara:"Peras, oral 2× sehari, 5 hari",ket:"Allicin — antiparasit intestinal + palatabilitas disukai domba"},
        {nama:"Jus Wortel + Jahe",dosis:"300mL jus wortel + 50g jahe parut",cara:"Campur, berikan segar 1× sehari",ket:"Beta-karoten + gingerol — boost imun + anti-inflamasi mukosa usus"},
        {nama:"Suplemen Besi (hati sapi/daun bayam tumbuk)",dosis:"100g hati sapi cincang ATAU 200g bayam segar",cara:"Campur pakan segar",ket:"Suplementasi Fe alami untuk anemia — FAMACHA score 4–5"},
      ],
    },
    {
      penyakit:"Scabies (Kudis / Scab)", gejala:"Gatal hebat, kulit berkerak tebal, bulu rontok, kurus, bisa fatal",
      penyebab:"Sarcoptes scabiei, Psoroptes ovis (tungau kulit)", tingkat:"⚠️ Menular ke kandang",
      obat:[
        {nama:"Ivermectin 1% injeksi",dosis:"0.3 mg/kg BB SC",frekuensi:"2× interval 14 hari",ket:"Sistemik — tangani semua tahap tungau"},
        {nama:"Doramectin 1%",dosis:"0.2 mg/kg BB IM",frekuensi:"2× interval 14 hari",ket:"Efek residual lebih panjang dari ivermectin"},
        {nama:"Amitraz 12.5% (Triatix) spray/dip",dosis:"0.05% larutan — semprot seluruh tubuh",frekuensi:"Setiap 7–10 hari, 3–4 kali",ket:"Topikal — efektif Psoroptes"},
        {nama:"Sulfur 5% salep / colek",dosis:"Oleskan merata ke area lesi",frekuensi:"Setiap 2 hari, 2–3 minggu",ket:"Alternatif lokal murah — antiseptik kulit"},
      ],
      pencegahan:"Karantina hewan baru 14 hari, celup / dip massal setahun 2×, sanitasi kandang",
      tradisional:[
        {nama:"Oli bekas + Belerang / Sulfur",dosis:"Campuran 1:1 oli bekas + sulfur powder",cara:"Oleskan ke area lesi dengan kuas, 2× seminggu",ket:"Cara TERTUA dan paling umum di peternakan tradisional — sulfur acarisida alami"},
        {nama:"Minyak Kelapa + Daun Tembakau (rendam)",dosis:"200mL minyak kelapa + 50g tembakau rendam 24 jam",cara:"Saring, oleskan ke kulit berkerak 3× seminggu",ket:"Nikotin dalam minyak — membunuh tungau kontak"},
        {nama:"Air Sabun + Abu Dapur (lye water)",dosis:"2L air sabun kasar + 200g abu dapur",cara:"Mandi/celup domba, diamkan 10 menit, bilas",ket:"pH basa tinggi — mengganggu kutikula tungau"},
        {nama:"Daun Sirsak (Annona muricata) tumbuk",dosis:"200g daun sirsak tumbuk + 500mL air",cara:"Oleskan pasta ke kulit 2× sehari",ket:"Acetogenin daun sirsak — insektisida + acarisida alami"},
        {nama:"Minyak Kemiri + Kunyit",dosis:"3 sdm minyak kemiri + 2 sdm kunyit bubuk",cara:"Oleskan tipis ke area lesi 2× sehari",ket:"Aleuronat kemiri + kurkumin — anti-inflamasi + regenerasi kulit"},
      ],
    },
    {
      penyakit:"Penyakit Mulut & Kuku (PMK / FMD)", gejala:"Lepuh/vesikel di mulut, lidah, gusi, sela kuku, puting — air liur berlebih, pincang parah, demam 40–41°C, anak mati mendadak, produksi susu drop 50–80%",
      penyebab:"Foot-and-Mouth Disease Virus (FMDV) — Picornavirus, 7 serotype (O,A,C,SAT1,SAT2,SAT3,Asia1). Di Indonesia dominan Serotype O + A.", tingkat:"🚨 WAJIB LAPOR — Penyakit Strategis Nasional",
      obat:[
        {nama:"⚠️ TIDAK ADA antivirus spesifik FMDV",dosis:"Semua pengobatan bersifat SUPORTIF",frekuensi:"—",ket:"Fokus: cegah infeksi sekunder + jaga kondisi hewan + laporkan ke Dinas"},
        {nama:"Povidone Iodine 10% (Betadine) spray mulut+kaki",dosis:"Larutan 0.5% — semprot/cuci lesi 2–3×/hari",frekuensi:"Setiap hari sampai lesi kering (7–14 hari)",ket:"Desinfeksi lesi utama — cegah infeksi bakteri sekunder di vesikel pecah"},
        {nama:"Kalium Permanganat (PK) 0.1%",dosis:"Larutkan 1g PK / 1L air bersih",frekuensi:"Rendam kaki 20 menit 2×/hari",ket:"Oksidan kuat — bunuh bakteri + jamur di kuku, murah dan efektif"},
        {nama:"Penisilin G Prokain 300rb IU + Streptomisin",dosis:"20.000 IU/kg BB + 10–15 mg/kg BB IM",frekuensi:"2×/hari, 5–7 hari",ket:"Antibiotik WAJIB — cegah Fusobacterium + Staph di lesi vesikel"},
        {nama:"Amoxicillin-Clavulanate (Synulox)",dosis:"8.75 mg/kg BB IM/SC",frekuensi:"1×/hari, 5–7 hari",ket:"Alternatif — efektif bakteri penghasil beta-laktamase di lesi"},
        {nama:"Flunixin Meglumine (Finadyne)",dosis:"2.2 mg/kg BB IV/IM",frekuensi:"1×/hari, 3–5 hari",ket:"NSAID — turunkan demam + anti-inflamasi + analgesik (kurangi nyeri)"},
        {nama:"Meloxicam 5mg/mL",dosis:"0.5 mg/kg BB SC/IV",frekuensi:"1×/hari, 3–5 hari",ket:"Alternatif NSAID — lebih aman lambung, efektif anti-nyeri kuku"},
        {nama:"Vitamin C injeksi 200mg/mL",dosis:"10–20 mL IM/IV (sapi) / 5–10 mL (domba/kambing)",frekuensi:"1×/hari, 7 hari",ket:"Antioksidan + imunomodulator — percepat penyembuhan lesi"},
        {nama:"Vitamin B kompleks injeksi",dosis:"10–20 mL IM (sapi) / 3–5 mL (domba)",frekuensi:"1×/hari, 5 hari",ket:"Recovery nafsu makan + metabolisme saraf — hewan sering tidak mau makan"},
        {nama:"Infus NaCl 0.9% + Dextrose 5%",dosis:"5–10 L IV pelan (sapi) / 1–2 L (domba)",frekuensi:"1–2× sehari saat tidak mau makan/minum",ket:"Terapi cairan — PMK berat sering menyebabkan dehidrasi + hipoglikemia"},
        {nama:"Oralit Sapi (ORS Veteriner)",dosis:"3–5 L per oral, 3×/hari (sapi)",frekuensi:"Selama fase akut 5–7 hari",ket:"Rehidrasi oral — lebih mudah dari infus, jaga kondisi tubuh"},
        {nama:"Zinc Sulfate 10% spray kuku",dosis:"Larutan ZnSO₄ 10%, semprot/rendam kuku",frekuensi:"1×/hari setelah cuci kaki",ket:"Regenerasi jaringan tanduk kuku + antibakteri — penting kasus foot lesion"},
        {nama:"Vaksin PMK Bivalent O+A (inaktif)",dosis:"3 mL IM (sapi dewasa) / 2 mL (sapi muda/domba)",frekuensi:"PRIMER: 2× interval 4 minggu. BOOSTER: setiap 4–6 bulan",ket:"WAJIB pasca wabah 2022 — vaksinasi seluruh populasi ruminansia"},
        {nama:"Oxytetracycline Spray 3% topikal",dosis:"Semprot langsung ke lesi mulut + kuku",frekuensi:"2×/hari",ket:"Antibiotik topikal + warna biru mengusir lalat dari lesi"},
      ],
      pencegahan:"Vaksin PMK Bivalent O+A WAJIB (Kementan Permentan 2023), biosekuriti maksimal, desinfeksi kendaraan + alat, LAPOR ke Dinas Peternakan + Satgas PMK Kabupaten, isolasi ketat hewan masuk",
      tradisional:[
        {nama:"Air Garam (NaCl) 1–2% kumur + rendam kaki",dosis:"2 sdm garam / 1L air hangat (40°C)",cara:"Kumur mulut 3×/hari + rendam kaki 20 menit 2×/hari",ket:"PERTOLONGAN PERTAMA terbaik — osmotik bersihkan vesikel + antiseptik alami"},
        {nama:"Rebusan Daun Sirih + Tawas (alum)",dosis:"15 lembar sirih + 1 sdm tawas + 1L air rebus 15 menit",cara:"Dinginkan, cuci mulut + kaki 3×/hari dengan kain bersih",ket:"Tanin sirih + alum (astringen) — antiseptik + percepat pengeringan lesi vesikel"},
        {nama:"Getah Batang Pepaya (latex)",dosis:"Teteskan getah segar dari batang papaya",cara:"Oleskan tipis ke vesikel pecah 2–3×/hari",ket:"Papain protease + antiseptik — debridemen alami jaringan mati, cegah infeksi"},
        {nama:"Madu Murni + Kunyit (pasta lesi)",dosis:"3 sdm madu + 1 sdm kunyit bubuk, aduk rata",cara:"Oleskan ke lesi mulut + kaki, biarkan 1 jam, cuci bersih",ket:"H₂O₂ antibakteri madu + kurkumin anti-inflamasi — mempercepat granulasi lesi"},
        {nama:"Daun Binahong + Daun Sirih tumbuk (kompres kaki)",dosis:"15 lembar binahong + 10 lembar sirih tumbuk halus",cara:"Tempelkan ke kuku yang lesi, balut kain kasa bersih, ganti 2×/hari",ket:"Saponin binahong + tanin sirih — wound healing tradisional terbukti empiris"},
        {nama:"Air Rebusan Kunyit + Jahe (oral)",dosis:"200g kunyit + 100g jahe / 5L air rebus",cara:"Saring dingin, berikan sebagai minum 2×/hari",ket:"Kurkumin antipiretik + anti-inflamasi + gingerol — membantu turunkan demam"},
        {nama:"Campuran Oralit Tradisional",dosis:"1L air matang + 1 sdm gula + 1/4 sdt garam + 1/4 sdt soda kue",cara:"Berikan 2–3L per oral 3–4×/hari saat hewan tidak mau minum",ket:"Rehidrasi + elektrolit darurat — PMK sapi dewasa sering dehidrasi karena tidak mau minum"},
        {nama:"Tepung Kambing Muda (nasi/beras lumat untuk mulut luka)",dosis:"500g nasi lunak + sedikit garam + 500mL air hangat",cara:"Berikan via tangan langsung atau ember rendah",ket:"Pakan lunak — hewan PMK tidak mau makan karena mulut sakit, nasi lunak tetap beri energi"},
        {nama:"Desinfeksi Kandang dengan Kapur Tohor + Abu",dosis:"1 kg kapur tohor + 10L air (larutan 10%), semprot kandang",cara:"Semprot lantai + dinding 2×/hari selama wabah",ket:"Inaktivasi FMDV di lingkungan — virus PMK mati pH <6 dan >9"},
        {nama:"⚠️ KEWAJIBAN HUKUM: Laporkan ke Dinas Peternakan",dosis:"—",cara:"Hubungi: Call Center PMK 0800-1234-567 atau Dinas Kab/Kota",ket:"PMK Penyakit Hewan Menular Strategis (PHMS) — wajib dilaporkan dalam 1×24 jam sesuai UU No.18/2009"},
      ],
    },
    {
      penyakit:"Orf (Ecthyma Contagiosa)", gejala:"Koreng/keropeng pada bibir, gusi, kaki — terutama anak domba",
      penyebab:"Parapoxvirus — zoonosis ringan", tingkat:"⚠️ Sedang, gunakan sarung tangan!",
      obat:[
        {nama:"Oxytetracycline spray / semprotan kulit",dosis:"Semprotkan langsung ke lesi 2–3×",frekuensi:"Setiap hari, 7–10 hari",ket:"Cegah infeksi bakteri sekunder"},
        {nama:"Betadine (Povidone Iodine 10%)",dosis:"Oleskan ke koreng",frekuensi:"2×/hari",ket:"Antiseptik topikal"},
        {nama:"Zinc Oxide cream",dosis:"Oleskan tipis",frekuensi:"1–2×/hari",ket:"Lindungi luka dari lalat"},
      ],
      pencegahan:"Hindari kontak langsung (zoonosis), vaksin orf tersedia di beberapa negara",
      tradisional:[
        {nama:"Minyak Kelapa + Abu Gosok",dosis:"2 sdm VCO + 1 sdt abu bersih halus",cara:"Oleskan pasta ke koreng 2× sehari (pakai sarung tangan!)",ket:"Abu (alkali) + VCO — membantu pengelupasan keropeng + antiseptik"},
        {nama:"Getah Pohon Pisang (topikal)",dosis:"Oleskan getah dari batang pisang segar",cara:"Usapkan langsung ke lesi, 3× sehari",ket:"Tanin + saponin getah pisang — antiseptik + astringent alami"},
        {nama:"Rebusan Daun Jambu Biji",dosis:"20 lembar daun jambu + 1L air, rebus 15 menit",cara:"Dinginkan, kompres ke lesi 3× sehari",ket:"Tanin + psidium — anti-virus topikal + menyembuhkan luka"},
        {nama:"⚠️ Pakai sarung tangan karet tebal",dosis:"—",cara:"WAJIB saat menangani domba orf",ket:"Orf adalah ZOONOSIS — virus bisa menular ke manusia lewat luka kecil"},
      ],
    },
    {
      penyakit:"Keracunan Tembaga (Copper Toxicosis)", gejala:"Domba tiba-tiba kritis: kuning (jaundice), urin merah gelap, lemas parah, mati mendadak",
      penyebab:"Akumulasi Cu hati selama berminggu-minggu lalu release massal — premix sapi, pakan komersial Cu tinggi", tingkat:"🚨 KRITIS — sering mematikan",
      obat:[
        {nama:"Ammonium Molybdate 50–500 mg/hari PO",dosis:"50–500 mg/hari per oral",frekuensi:"Setiap hari, 3–6 minggu",ket:"Antidotum Cu spesifik — chelasi Cu hati, SEGERA setelah diagnosis"},
        {nama:"Sodium Sulfate 0.1% air minum",dosis:"1 g/L air minum",frekuensi:"Setiap hari selama treatment",ket:"Kombinasi dengan Mo — chelasi Cu saluran cerna"},
        {nama:"Dexamethasone 0.1 mg/kg IV/IM",dosis:"0.1 mg/kg",frekuensi:"Sekali, saat krisis hemolisis",ket:"Stabilisasi hemolisis akut — simtomatis"},
        {nama:"Infus NaCl 0.9% + Dextrose",dosis:"5–10 L IV pelan",frekuensi:"Saat krisis, 1–2× sehari",ket:"Flush ginjal + jaga hidrasi saat hemolisis"},
        {nama:"Vitamin E + Selenium injeksi",dosis:"1 mg Se/kg BB SC (hati-hati!)",frekuensi:"Sekali per minggu",ket:"Antioksidan proteksi sel hati dari kerusakan Cu"},
      ],
      pencegahan:"⚠️ JANGAN berikan premix/mineral sapi ke domba! Pakai premix khusus domba Cu rendah (<15ppm Cu)",
      tradisional:[
        {nama:"⚠️ Tidak ada pengobatan tradisional efektif",dosis:"—",cara:"SEGERA hubungi dokter hewan",ket:"Keracunan Cu akut fatal dalam jam — pengobatan tradisional tidak cukup"},
        {nama:"Air minum banyak paksa (flush)",dosis:"Paksa minum sebanyak mungkin",cara:"Berikan air segar terus-menerus",ket:"Bantu flush Cu lewat urin — paliatif sambil menunggu drh"},
        {nama:"Biji Buah Labu (Cucurbita) — preventif",dosis:"30g biji labu kering tumbuk / ekor / minggu",cara:"Campur pakan sebagai suplemen zinc",ket:"Zinc kompetitor Cu — pencegahan akumulasi jangka panjang"},
      ],
    },
    {
      penyakit:"Enterotoksemia (Pulpy Kidney)", gejala:"Domba gemuk mati mendadak tanpa gejala, atau kejang-kejang lalu mati dalam jam",
      penyebab:"Clostridium perfringens tipe D — toksin epsilon, dipicu pakan konsentrat tinggi mendadak", tingkat:"🚨 Kritis — sering tak ada peringatan",
      obat:[
        {nama:"Antitoksin Clostridium perfringens D IV/IM",dosis:"10.000–20.000 IU IM/IV",frekuensi:"Sekali — sesegera mungkin",ket:"PALING EFEKTIF jika diberikan sebelum toksemia parah"},
        {nama:"Penisilin G Prokain",dosis:"20.000 IU/kg BB IM",frekuensi:"2×/hari, 3–5 hari",ket:"Hambat multiplikasi Clostridium usus"},
        {nama:"Metronidazole 500mg",dosis:"20 mg/kg BB PO/IV",frekuensi:"2×/hari, 5 hari",ket:"Anaerob spektrum luas — clostridia sensitif"},
        {nama:"Infus NaCl + Bicarbonat 5%",dosis:"2–5 L IV + 50–100 mL bicarbonat",frekuensi:"Kasus berat — 1× sehari",ket:"Koreksi asidosis metabolik akibat toksin"},
        {nama:"Vaksin Enterotoksemia (preventif)",dosis:"2 mL SC, booster 4 minggu",frekuensi:"2× awal + tahunan",ket:"PENCEGAHAN PALING EFEKTIF — lebih baik dari pengobatan"},
      ],
      pencegahan:"Vaksin Clostridium (4-way/8-way), adaptasi pakan konsentrat bertahap, hindari pakan mendadak tinggi karbohidrat",
      tradisional:[
        {nama:"Arang Aktif / Arang Kayu per oral",dosis:"50–100g arang halus + 500mL air",cara:"Berikan per oral segera saat gejala pertama",ket:"Adsorben toksin usus — darurat sebelum drh tiba"},
        {nama:"Minyak Kelapa 100mL per oral",dosis:"100mL VCO langsung",cara:"Masukkan paksa via botol ke mulut",ket:"Lapisi mukosa usus — kurangi absorpsi toksin"},
        {nama:"Puasa pakan konsentrat + hijauan saja",dosis:"Stop pakan konsentrat 24–48 jam",cara:"Berikan hijauan kering / hay saja",ket:"Kurangi substrat fermentasi Clostridium di usus"},
        {nama:"Air rebusan Kunyit + Jahe (stimulasi)",dosis:"200g kunyit + 100g jahe / 5L air rebus",cara:"Berikan hangat 2× sehari",ket:"Stimulasi motilitas usus + anti-inflamasi mukosa"},
      ],
    },
    {
      penyakit:"Pneumonia (Radang Paru)", gejala:"Napas cepat dangkal, batuk, demam 40–41°C, hidung berlendir, tidak mau makan",
      penyebab:"Pasteurella multocida / Mannheimia haemolytica — stres dingin + lembab sebagai pencetus", tingkat:"⚠️ Sedang — menjadi kritis cepat",
      obat:[
        {nama:"Oxytetracycline 20% LA",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 3–4 kali",ket:"First-line pneumonia domba — long-acting praktis"},
        {nama:"Enrofloxacin 10%",dosis:"5 mg/kg BB IM/SC",frekuensi:"1×/hari, 5 hari",ket:"Broad-spectrum — efektif Pasteurella + Mycoplasma"},
        {nama:"Flunixin Meglumine",dosis:"2.2 mg/kg BB IM/IV",frekuensi:"1×/hari, 3 hari",ket:"Antipiretik + anti-inflamasi paru"},
        {nama:"Vitamin C 200mg/mL injeksi",dosis:"5–10 mL IM",frekuensi:"1×/hari, 5 hari",ket:"Antioksidan paru + boost imun"},
        {nama:"Bromhexine / Ambroxol oral",dosis:"0.1 mL/kg BB",frekuensi:"2×/hari, 3–5 hari",ket:"Mukolitik — bersihkan lendir saluran napas"},
      ],
      pencegahan:"Hindari fluktuasi suhu ekstrem, kandang kering + ventilasi baik, vaksin Pasteurella, pisahkan hewan stres",
      tradisional:[
        {nama:"Uap Minyak Kayu Putih",dosis:"50mL minyak kayu putih + ember air mendidih",cara:"Dekatkan kepala domba ke uap 5–10 menit, 3× sehari",ket:"Eucalyptol — bronkodilator + antiseptik saluran napas"},
        {nama:"Jamu Jahe + Kencur + Madu",dosis:"150g jahe + 100g kencur + 3 sdm madu / 5L air",cara:"Rebus saring, berikan hangat 2× sehari",ket:"Ekspektoran alami + anti-inflamasi + antibakteri madu"},
        {nama:"Kompres Dada Hangat",dosis:"Kain hangat (45°C) kompres dada 15 menit",cara:"2–3× sehari",ket:"Melancarkan peredaran darah paru + menghangatkan domba"},
        {nama:"Bawang Putih + Madu (oral)",dosis:"5 siung bawang putih geprek + 2 sdm madu",cara:"Berikan langsung per oral 2× sehari",ket:"Allicin + antibakteri madu — suportif anti-Pasteurella"},
      ],
    },
    {
      penyakit:"Pink Eye (Keratokonjungtivitis Infeksiosa)", gejala:"Mata merah berair, kelopak bengkak, kekeruhan kornea, bisa buta sementara, menghindari cahaya",
      penyebab:"Moraxella ovis / Chlamydia pecorum — vektor lalat, penyebaran cepat antar kandang", tingkat:"⚠️ Sedang — menular cepat",
      obat:[
        {nama:"Oxytetracycline salep mata 1%",dosis:"Oleskan ke dalam kelopak bawah",frekuensi:"3–4×/hari, 5–7 hari",ket:"STANDAR — antibiotik topikal mata efektif Moraxella"},
        {nama:"Oxytetracycline 20% LA injeksi",dosis:"20 mg/kg BB IM",frekuensi:"1× per 3 hari, 2–3 kali",ket:"Sistemik untuk kasus berat / tidak respon topikal"},
        {nama:"Penisilin G Prokain subkonjungtiva",dosis:"250.000 IU injeksi subkonjungtiva",frekuensi:"1× (teknik drh)",ket:"Efektif cepat — langsung ke jaringan mata"},
        {nama:"Dexamethasone tetes mata 0.1%",dosis:"2 tetes per mata",frekuensi:"3×/hari, 3–5 hari",ket:"Kurangi peradangan + kekeruhan kornea"},
        {nama:"Tutup mata dengan perban",dosis:"Perban gelap satu mata",frekuensi:"Ganti setiap 2–3 hari",ket:"Lindungi dari cahaya + lalat — percepat penyembuhan"},
      ],
      pencegahan:"Kendalikan lalat, pisahkan hewan sakit, sterilisasi tangan saat pegang mata hewan, hindari debu berlebihan",
      tradisional:[
        {nama:"Tetes Air Susu Ibu (ASI) / Susu Segar",dosis:"2–3 tetes susu segar ke mata",cara:"Teteskan 3× sehari",ket:"Antibakteri laktoferrin susu — cara leluhur, efektif mild kasus"},
        {nama:"Air Rebusan Daun Sirih Dingin",dosis:"10 lembar sirih + 500mL air rebus, saring steril",cara:"Teteskan 2–3 tetes ke mata 3× sehari",ket:"Tanin + antiseptik sirih — eye drop tradisional klasik"},
        {nama:"Air Perasan Daun Binahong",dosis:"5–8 lembar binahong + 100mL air, peras steril",cara:"Teteskan ke mata 2× sehari",ket:"Saponin + flavonoid — anti-inflamasi + antibakteri ringan"},
        {nama:"Pisahkan dari flock + kandang gelap",dosis:"Isolasi minimal 7 hari",cara:"Kandang minim cahaya, jauh dari kawanan",ket:"Pink eye sangat menular lewat lalat — isolasi WAJIB dilakukan pertama"},
      ],
    },
    {
      penyakit:"Kencing Darah Domba — Haemoglobinuria Infeksiosa / Clostridium haemolyticum", gejala:"Urin merah tua mendadak, anemia akut, icterus, kematian sangat cepat (beberapa jam), domba ditemukan mati tanpa gejala jelas sebelumnya",
      penyebab:"Clostridium haemolyticum (C.novyi tipe D) — produksi beta-toxin phospholipase C yang hemolitik masif. Dipicu fasciola (cacing hati) yang aktif.", tingkat:"🚨 Kritis — kematian <24 jam, sering terlambat diobati",
      obat:[
        {nama:"Antitoksin Clostridium haemolyticum IV/IM",dosis:"50.000–100.000 IU IV/IM",frekuensi:"Sesegera mungkin — sekali",ket:"PALING EFEKTIF jika diberikan dalam jam pertama. Sering terlambat karena gejala cepat"},
        {nama:"Penisilin G Prokain 300rb IU",dosis:"20.000–30.000 IU/kg BB IM",frekuensi:"2×/hari, 5 hari",ket:"Bunuh Clostridium aktif — berikan BERSAMAAN dengan antitoksin"},
        {nama:"Rafoxanide 2.5% (anti-Fasciola)",dosis:"7.5 mg/kg BB PO",frekuensi:"Sekali",ket:"Bunuh Fasciola yang memicu Clostridium — PENTING untuk putus siklus"},
        {nama:"Infus NaCl 0.9% + Dextrose 5%",dosis:"1–2 L IV pelan (domba)",frekuensi:"1–2× sehari",ket:"Terapi cairan — hemolisis akut menyebabkan kollaps cepat"},
        {nama:"Vaksin Clostvax / Multivax (preventif)",dosis:"2 mL SC, booster 4 minggu",frekuensi:"2× awal + tahunan",ket:"PENCEGAHAN UTAMA — lebih efektif dari pengobatan karena penyakit terlalu cepat mematikan"},
      ],
      pencegahan:"Vaksin Clostridium multi-valent WAJIB di daerah endemik, program anti-Fasciola (rafoxanide) 2× setahun, hindari padang basah/tergenang, kandang kering",
      tradisional:[
        {nama:"⚠️ Haemoglobinuria Clostridial terlalu cepat untuk tradisional",dosis:"—",cara:"SEGERA hubungi dokter hewan",ket:"Kematian dalam jam — tidak ada waktu untuk obat tradisional. Fokus ke vaksinasi pencegahan"},
        {nama:"Arang Aktif per oral (darurat)",dosis:"100g arang + 500mL air",cara:"Berikan per oral segera saat gejala pertama",ket:"Adsorben toksin Clostridium di usus — paliatif darurat"},
        {nama:"Air Kelapa Muda (suportif)",dosis:"500mL–1L langsung dari buah",cara:"Paksa minum jika masih sadar",ket:"Elektrolit + antioksidan — supportif saat menunggu drh"},
        {nama:"Vaksin alami: hindari padang basah",dosis:"Pindahkan ternak dari area berair",cara:"Kandangkan saat musim hujan puncak",ket:"Fasciola berkembang di padang basah — manajemen padang = pencegahan terbaik"},
      ],
    },
  ],
  broiler: [
    {
      penyakit:"Newcastle Disease (ND / Tetelo)", gejala:"Torticollis (leher memutar), kelumpuhan kaki/sayap, suara 'kokoh', mati massal",
      penyebab:"Newcastle Disease Virus (NDV) — Velogenic VVND fatal", tingkat:"🚨 Kritis — bisa habiskan kandang!",
      obat:[
        {nama:"TIDAK ADA obat spesifik — VAKSINASI satu-satunya",dosis:"Vaksin ND La Sota tetes mata — D4",frekuensi:"D4 (tetes), D14 (IB spray), D28+ (suntik)",ket:"Program 3 vaksin untuk broiler komersial"},
        {nama:"Amoxicillin 70% serbuk",dosis:"0.5 g/L air minum (500 g/ton pakan)",frekuensi:"3–5 hari",ket:"Cegah infeksi bakteri sekunder"},
        {nama:"Vitamin C + Elektrolit",dosis:"1 g/L air minum",frekuensi:"5–7 hari",ket:"Support imun + rehidrasi"},
        {nama:"Probiotik Lactobacillus",dosis:"1 g/L air minum",frekuensi:"5–7 hari",ket:"Restorasi flora usus pasca sakit"},
      ],
      pencegahan:"Program vaksin 3× wajib, biosekuriti kandang ketat, desinfeksi kendaraan masuk",
      tradisional:[
        {nama:"Bawang Putih parut + madu (air minum)",dosis:"100g bawang putih parut + 3 sdm madu / 10L air",cara:"Berikan sebagai air minum selama 5–7 hari",ket:"Allicin antibakteri + antimikroba madu — boost imun flock, bukan antivirus"},
        {nama:"Kunyit + Jahe + Temulawak (jamu)",dosis:"200g kunyit + 100g jahe + 100g temulawak, rebus 5L",cara:"Saring dingin, campurkan ke air minum 3× seminggu",ket:"Kurkumin + gingerol + xanthorrhizol — imunomodulator + anti-inflamasi mukosa"},
        {nama:"Daun Sambiloto (Andrographis) rebus",dosis:"100g daun sambiloto + 3L air, rebus 20 menit",cara:"Saring, campurkan ke air minum (encer 1:10)",ket:"Andrographolide — antiviral + imunomodulator, riset terbukti pada unggas"},
        {nama:"Air Rebusan Jahe + Gula Merah",dosis:"300g jahe + 200g gula merah + 5L air",cara:"Berikan hangat ke air minum saat musim hujan",ket:"Gingerol + antioksidan — mencegah stres termal + jaga nafsu makan"},
      ],
    },
    {
      penyakit:"Gumboro (IBD — Infectious Bursal Disease)", gejala:"Mencret putih, imunodepresi, mortalitas spike hari ke-3–5, bulu acak-acakan",
      penyebab:"IBD Virus — menyerang Bursa Fabricius (organ imun)", tingkat:"🚨 Kritis — merusak imunitas permanen",
      obat:[
        {nama:"Vaksin Gumboro (Lukert/Winterfield) air minum",dosis:"1 dosis/ekor via air minum",frekuensi:"D10–14 + D21–24 (2 kali)",ket:"KRITIS: jadwal vaksin harus tepat sebelum titer maternal turun"},
        {nama:"Hipersensitif Serum Gumboro (HyperSerum)",dosis:"0.5 mL/kg BB IM",frekuensi:"Sekali saat outbreak",ket:"Terapi outbreak — efektif dalam 48 jam pertama"},
        {nama:"Vitamin A+D3+E+C kompleks",dosis:"2 mL/L air minum",frekuensi:"5–7 hari",ket:"Pemulihan sistem imun bursa"},
        {nama:"Elektrolit oral",dosis:"1 sachet/10L air",frekuensi:"3–5 hari",ket:"Rehidrasi + keseimbangan elektrolit"},
      ],
      pencegahan:"Monitoring titer maternal, program vaksin IBD berbasis titer, desinfeksi formaldehid pada kandang",
      tradisional:[
        {nama:"Kunyit + Kencur + Madu (jamu broiler)",dosis:"150g kunyit + 100g kencur + 3 sdm madu / 10L air",cara:"Rebus, saring dingin, campurkan ke air minum 5–7 hari",ket:"Imunomodulator alami — bantu recovery sistem imun pasca Gumboro"},
        {nama:"Propolis cair (bee propolis)",dosis:"0.5 mL propolis cair / L air minum",cara:"Campurkan ke air minum 7–10 hari",ket:"Flavonoid propolis — antivirus + antioksidan + boost limfosit"},
        {nama:"Air Gula Merah + Garam (oralit broiler)",dosis:"3 sdm gula merah + 1 sdt garam / 5L air",cara:"Berikan saat ayam lesu tidak minum",ket:"Rehidrasi cepat + energi — mengatasi dehidrasi diare Gumboro"},
        {nama:"Bawang Merah + Bawang Putih parut",dosis:"50g bawang merah + 50g bawang putih parut / 10L air",cara:"Peras saring, campurkan ke air minum",ket:"Quersetin + allicin — antiinflamasi + antibakteri sekunder"},
      ],
    },
    {
      penyakit:"CRD (Chronic Respiratory Disease)", gejala:"Ngorok, bersin, eksudat hidung, sesak, pertumbuhan terhambat, FCR naik",
      penyebab:"Mycoplasma gallisepticum + E.coli (kompleks), diperparah amonia tinggi", tingkat:"⚠️ Ekonomis tinggi — naik FCR 0.1–0.2",
      obat:[
        {nama:"Tylosin Tartrate 100g/L",dosis:"0.5 g/L air minum (500 mg/kg BW)",frekuensi:"5–7 hari",ket:"Anti-Mycoplasma terbaik — standar industri"},
        {nama:"Enrofloxacin 10% oral",dosis:"10 mg/kg BB (1 mL/L air minum)",frekuensi:"5 hari",ket:"⚠️ Perhatikan withdrawal 7 hari sebelum panen!"},
        {nama:"Doxycycline 10% serbuk",dosis:"25 mg/kg BB (2.5 g/10 L air)",frekuensi:"5–7 hari",ket:"Anti-Mycoplasma + anti-inflamasi saluran napas"},
        {nama:"Ambroxol / Bromhexine",dosis:"0.1 mL/kg BB oral",frekuensi:"3–5 hari",ket:"Mucolytics — bersihkan lendir saluran napas"},
        {nama:"Vitamin C + Menthol",dosis:"1 g/L + 0.1 mL/L",frekuensi:"5–7 hari",ket:"Anti-stres + buka saluran napas"},
      ],
      pencegahan:"Ventilasi optimal (amonia <25 ppm), vaksin MG, kepadatan kandang tidak melebihi 12 ekor/m²",
      tradisional:[
        {nama:"Uap Minyak Kayu Putih + Eucalyptus",dosis:"50 mL minyak kayu putih + ember air panas",cara:"Letakkan di dalam kandang 2–3 titik, biarkan menguap",ket:"Cineole + eucalyptol — membuka saluran napas + antimikroba udara"},
        {nama:"Kunyit + Jahe + Kencur (jamu pernapasan)",dosis:"300g kunyit + 200g jahe + 150g kencur / 20L air rebus",cara:"Saring, campurkan ke air minum 2× sehari, 7 hari",ket:"Ekspektoran alami + anti-Mycoplasma + anti-inflamasi mukosa hidung"},
        {nama:"Daun Mint / Peppermint segar",dosis:"200g daun mint segar + 5L air panas",cara:"Uapkan di kandang ATAU saring berikan ke air minum",ket:"Menthol — bronkodilator alami, melegakan napas sesak"},
        {nama:"Bawang Putih + Cuka Apel (Apple Cider Vinegar)",dosis:"100g bawang putih + 50 mL cuka apel / 10L air",cara:"Campurkan ke air minum 5–7 hari",ket:"Asam asetat + allicin — menurunkan pH air, hambat Mycoplasma + E.coli"},
        {nama:"Perbaikan ventilasi kandang (non-obat)",dosis:"Buka tirai/terpal sisi kandang 30–50%",cara:"Atur ventilasi silang — udara masuk dari bawah, keluar atas",ket:"UTAMA: amonia tinggi adalah pemicu CRD — ventilasi lebih penting dari semua obat"},
      ],
    },
    {
      penyakit:"Koksidiosis (Coccidiosis)", gejala:"Mencret berdarah, lesu, tidak mau makan, mortalitas tinggi D14–21",
      penyebab:"Eimeria tenella / E.brunetti — protozoa usus", tingkat:"⚠️ Sangat umum pada broiler non-vaksin",
      obat:[
        {nama:"Amprolium 20% serbuk",dosis:"125–250 mg/L air minum (0.6–1.25 g/L)",frekuensi:"5–7 hari",ket:"Anti-koksidia — aman untuk broiler muda"},
        {nama:"Toltrazuril 2.5% (Baycox)",dosis:"28 mg/kg BB (7 mg/L air minum)",frekuensi:"2 hari berturut-turut",ket:"Terbaik — membunuh semua stadium Eimeria"},
        {nama:"Diclazuril 0.5%",dosis:"1 ppm dalam air minum",frekuensi:"2 hari",ket:"Efektif dosis rendah"},
        {nama:"Sulfonamide + Trimethoprim",dosis:"30 mg/kg BB oral",frekuensi:"5 hari",ket:"Alternatif + anti-bakteri sekunder"},
      ],
      pencegahan:"Coccidiostat dalam starter (Salinomycin/Monensin), vaksin koksidia, litter kering dan bersih",
      tradisional:[
        {nama:"Kulit Manggis (Garcinia mangostana) rebus",dosis:"100g kulit manggis kering + 3L air rebus 20 menit",cara:"Saring dingin, campurkan ke air minum 5–7 hari",ket:"Xanthone manggis — antiprotozoal + antioksidan, riset terhadap Eimeria positif"},
        {nama:"Daun Pepaya + Bawang Putih (jamu koksi)",dosis:"200g daun pepaya + 100g bawang putih + 5L air",cara:"Rebus, saring, berikan ke air minum 5 hari",ket:"Papain + allicin — anti-Eimeria + perbaiki integritas usus"},
        {nama:"Kunyit + Temulawak (dosis tinggi)",dosis:"500g kunyit + 200g temulawak / 20L air rebus",cara:"Saring berikan ke air minum 2× sehari",ket:"Kurkumin dosis tinggi — antiprotozoal + regenerasi epitel usus terbukti"},
        {nama:"Gula Merah + Garam + Oralit (rehidrasi)",dosis:"4 sdm gula merah + 1 sdm garam / 5L air",cara:"Berikan saat ayam diare parah",ket:"Rehidrasi cepat — koksidiosis parah menyebabkan kehilangan darah + cairan"},
        {nama:"Litter kering (non-obat, UTAMA)",dosis:"Ganti litter basah, tabur kapur tohor tipis",cara:"Litter maks 25% kelembaban",ket:"Ookista Eimeria butuh litter lembab untuk sporulasi — litter kering = pencegahan terbaik"},
      ],
    },
    {
      penyakit:"Avian Influenza (AI) H5N1 / H5N8", gejala:"Kematian mendadak massal, jengger biru, pendarahan kaki, gejala saraf",
      penyebab:"Influenza A Virus H5N1 (HPAI) — ZOONOSIS FATAL", tingkat:"🚨 SANGAT KRITIS — LAPOR SEGERA!",
      obat:[
        {nama:"TIDAK ADA pengobatan — isolasi dan lapor",dosis:"—",frekuensi:"—",ket:"⚠️ HPAI = wajib depopulasi + lapor Dinas!"},
        {nama:"Vaksin AI H5N1 (killed)",dosis:"0.5 mL/ekor SC/IM",frekuensi:"D14 + booster D35, ulang 3–4 bulan",ket:"SATU-SATUNYA pencegahan efektif"},
      ],
      pencegahan:"Vaksin AI rutin, biosekuriti level 3, pakai APD saat penanganan, laporkan kematian massal ke Dinas",
      tradisional:[
        {nama:"⚠️ TIDAK ADA obat tradisional untuk HPAI",dosis:"—",cara:"LAPOR Dinas Peternakan SEGERA — jangan tangani sendiri",ket:"AI H5N1 HPAI = zoonosis fatal. Depopulasi WAJIB. Obat tradisional TIDAK EFEKTIF dan membahayakan keselamatan manusia"},
        {nama:"Biosekuriti darurat: desinfektan Virkon S",dosis:"1:100 larutan semprot seluruh area",cara:"Semprot area kandang, kendaraan, alas kaki",ket:"Kontrol penyebaran virus — lebih penting dari pengobatan"},
      ],
    },
    {
      penyakit:"Infectious Bronchitis (IB)", gejala:"Batuk, bersin massal, suara ngorok serentak, drop produksi (layer), nefrosis ginjal",
      penyebab:"Infectious Bronchitis Virus (Coronavirus) — banyak serotype, mutasi cepat", tingkat:"⚠️ Ekonomis tinggi + sulit dikontrol",
      obat:[
        {nama:"TIDAK ADA antivirus — vaksinasi primer",dosis:"Vaksin IB H120 + Ma5 spray D14 + D28",frekuensi:"2× + booster sesuai serotype lokal",ket:"Multi-serotype vaksin kritis — IB variant terus bermutasi"},
        {nama:"Enrofloxacin 10%",dosis:"10 mg/kg BB (1 mL/L air)",frekuensi:"5 hari",ket:"Cegah komplikasi E.coli sekunder"},
        {nama:"Tilosine Tartrate",dosis:"0.5 g/L air minum",frekuensi:"5 hari",ket:"Anti-Mycoplasma sekunder yang sering menyertai IB"},
        {nama:"Vitamin C + Elektrolit kompleks",dosis:"1–2 g/L air minum",frekuensi:"7–10 hari",ket:"Support recovery + rehidrasi"},
        {nama:"Ammonium klorida 0.5%",dosis:"5 g/L air minum",frekuensi:"3–5 hari",ket:"Diuretik ringan — bantu flush nefritis"},
      ],
      pencegahan:"Vaksin IB multi-serotype (H120+Ma5+QX), biosekuriti ketat, ventilasi baik, hindari stres dingin",
      tradisional:[
        {nama:"Uap Minyak Kayu Putih dalam kandang",dosis:"100mL minyak kayu putih + 2 ember air mendidih",cara:"Letakkan di sudut kandang, biarkan menguap",ket:"Eucalyptol — membuka saluran napas + antiseptik udara kandang"},
        {nama:"Jahe + Kunyit + Jeruk Nipis (jamu)",dosis:"300g jahe + 200g kunyit + 5 buah jeruk nipis / 10L air",cara:"Rebus saring, campurkan ke air minum 5–7 hari",ket:"Vitamin C alami + gingerol ekspektoran + kurkumin anti-inflamasi"},
        {nama:"Bawang Putih fermentasi air minum",dosis:"150g bawang putih blender + 10L air, fermentasi 12 jam",cara:"Saring, berikan ke air minum selama sakit",ket:"Allicin + alliin — anti-virus + antibakteri mukosa pernapasan"},
        {nama:"Melon / Mentimun parut ke pakan",dosis:"200g melon parut / 100 ekor",cara:"Campur ke pakan basah",ket:"Hidrasi + silika alami — bantu recovery mukosa saluran napas"},
      ],
    },
    {
      penyakit:"Colibacillosis (Colibasilosis)", gejala:"Mencret kuning-putih berbau, omphalitis (pusar bernanah DOC), airsacculitis, angka kematian tinggi D1–7",
      penyebab:"Escherichia coli patogen — APEC (Avian Pathogenic E.coli)", tingkat:"⚠️ Sangat umum — penyebab kematian #1 DOC",
      obat:[
        {nama:"Enrofloxacin 10% oral",dosis:"10 mg/kg BB (1 mL/L air minum)",frekuensi:"5 hari",ket:"First-line APEC — fluoroquinolon paling efektif, cek resistensi!"},
        {nama:"Amoxicillin 70% serbuk",dosis:"0.5–1 g/L air minum",frekuensi:"5–7 hari",ket:"Alternatif — beberapa strain masih sensitif"},
        {nama:"Gentamicin 4% injeksi",dosis:"5 mg/kg BB IM/SC",frekuensi:"1–2×/hari, 3–5 hari",ket:"DOC omphalitis — injeksi subcutan untuk kasus parah"},
        {nama:"Colistin Sulfate 240.000 IU/mL",dosis:"50.000–75.000 IU/kg BB PO",frekuensi:"5 hari",ket:"Last-resort — hanya kasus multi-drug resistant E.coli"},
        {nama:"Probiotik Lactobacillus + Bacillus",dosis:"1 g/L air minum",frekuensi:"7 hari pasca antibiotik",ket:"Restorasi flora usus + competitive exclusion E.coli"},
        {nama:"Zinc Oxide 3000 ppm dalam pakan",dosis:"3000 ppm ZnO dalam starter",frekuensi:"D1–7 saja",ket:"Astringen usus + anti-E.coli — perhatikan withdrawal"},
      ],
      pencegahan:"Kualitas DOC dari hatchery bersertifikat, sanitasi brooder ketat, air minum bersih pH 5–6, vaksin E.coli parent stock",
      tradisional:[
        {nama:"Kunyit + Bawang Putih + Air Kelapa",dosis:"200g kunyit + 100g bawang putih / 10L air kelapa",cara:"Blender saring, campurkan ke air minum DOC",ket:"Allicin + kurkumin + elektrolit — bantu rehabilitasi flora usus"},
        {nama:"Air Beras (rice water / tajin)",dosis:"Masak 100g beras + 1L air jadi bubur cair",cara:"Ambil air berasnya, berikan ke minum DOC",ket:"Amilosa + silika — lapisi dan lindungi mukosa usus dari E.coli"},
        {nama:"Cuka Apel (Apple Cider Vinegar)",dosis:"10 mL/L air minum",cara:"Campurkan ke air minum 5–7 hari",ket:"Asam asetat — turunkan pH air minum, hambat E.coli berkembang"},
        {nama:"Gula Merah + Garam ORS sederhana",dosis:"1 sdm gula merah + 1/4 sdt garam / 1L air",cara:"Berikan ke DOC yang lemas, tidak mau minum",ket:"Rehidrasi oral darurat — jaga DOC tidak dehidrasi"},
      ],
    },
    {
      penyakit:"Gangrenous Dermatitis (Cellulitis)", gejala:"Kulit menghitam, basah berlendir, berbau busuk, bulu mudah cabut, mati cepat",
      penyebab:"Clostridium septicum / C.perfringens + Staphylococcus — menyerang flock pasca Gumboro (imunodepresi)", tingkat:"🚨 Kritis — mortalitas tinggi",
      obat:[
        {nama:"Penisilin G Prokain 300rb IU",dosis:"20.000–30.000 IU/kg BB IM",frekuensi:"2×/hari, 5–7 hari",ket:"FIRST-LINE — Clostridium sangat sensitif penisilin"},
        {nama:"Metronidazole 500mg",dosis:"20 mg/kg BB PO/IV",frekuensi:"2×/hari, 5 hari",ket:"Anti-anaerob spektrum luas — sinergi penisilin"},
        {nama:"Oxytetracycline spray (topikal kulit)",dosis:"Semprot area lesi 2–3×",frekuensi:"2×/hari",ket:"Kontrol infeksi kulit + lindungi dari lalat"},
        {nama:"Vitamin E + Se injeksi",dosis:"0.1 mg Se/kg SC",frekuensi:"Sekali per minggu",ket:"Antioksidan — mencegah kerusakan sel lebih lanjut"},
      ],
      pencegahan:"Program vaksin Gumboro ketat (jangan sampai imunodepresi), litter kering, sanitasi berkala formalin",
      tradisional:[
        {nama:"Madu + Kunyit (topikal lesi)",dosis:"3 sdm madu + 2 sdm kunyit bubuk",cara:"Oleskan tebal ke area lesi, tutup kain",ket:"Antibakteri madu + kurkumin — suportif pada lesi terbatas"},
        {nama:"Arang Aktif per oral",dosis:"1 sdm arang halus / 1L air minum",cara:"Campurkan ke minum 3–5 hari",ket:"Adsorben toksin Clostridium di usus — suportif"},
        {nama:"Isolasi ketat + desinfeksi kandang",dosis:"Keluarkan semua hewan sakit",cara:"Semprot kandang dengan kreolin 2% atau kapur",ket:"LANGKAH PERTAMA — gangrenous dermatitis sangat menular dalam flock"},
      ],
    },
    {
      penyakit:"Snot (Coryza Infeksiosa)", gejala:"Ingus kental berbau busuk, bengkak wajah/sinus, bersin, napas berbunyi, nafsu makan turun",
      penyebab:"Avibacterium (Haemophilus) paragallinarum — bakteri, wabah cepat di kandang padat", tingkat:"⚠️ Ekonomis tinggi — FCR naik",
      obat:[
        {nama:"Sulfadimethoxine 25% oral",dosis:"1 g/L air minum (0.05% larutan)",frekuensi:"7–10 hari",ket:"First-line Coryza — sulfa sangat efektif Haemophilus"},
        {nama:"Sulfaquinoxaline 33%",dosis:"0.04% dalam air minum",frekuensi:"5–7 hari",ket:"Alternatif sulfa — konsentrasi lebih tinggi"},
        {nama:"Amoxicillin 70%",dosis:"0.5–1 g/L air minum",frekuensi:"5–7 hari",ket:"Alternatif beta-laktam — beberapa strain responsif"},
        {nama:"Erythromycin serbuk",dosis:"0.5 g/L air minum",frekuensi:"5 hari",ket:"Makrolid — jika sulfa resisten"},
        {nama:"Vaksin Coryza (inaktif)",dosis:"0.5 mL IM, booster 4 minggu",frekuensi:"2× awal + 6 bulanan",ket:"Pencegahan terbaik untuk flock endemik snot"},
      ],
      pencegahan:"Vaksin Coryza rutin, hindari membawa hewan baru tanpa karantina, desinfeksi intensif, kepadatan optimal",
      tradisional:[
        {nama:"Uap Kayu Putih + Menthol",dosis:"50mL kayu putih + sejumput menthol kristal + ember air panas",cara:"Letakkan di tengah kandang, uapkan 2× sehari pagi-sore",ket:"Membuka sinus tersumbat + antiseptik aerosol — bantu bersihkan ingus"},
        {nama:"Bawang Putih blender + Cuka (semprot)",dosis:"200g bawang putih + 200mL cuka / 5L air",cara:"Saring, semprotkan halus ke udara kandang",ket:"Allicin aerosol — antibakteri Haemophilus di udara kandang"},
        {nama:"Air Jahe + Jeruk Nipis + Madu",dosis:"300g jahe + 5 jeruk nipis + 5 sdm madu / 10L air",cara:"Rebus jahe saring, tambah jeruk + madu, ke air minum",ket:"Vitamin C + gingerol + antibakteri madu — suportif imun flock"},
        {nama:"Bersihkan ingus manual",dosis:"Lap basah hangat, bersihkan hidung 2× sehari",cara:"Gunakan kain bersih hangat, usap lembut lubang hidung",ket:"Mencegah sumbatan + komplikasi sinusitis — penting di awal gejala"},
      ],
    },
  ],
  petelur: [
    {
      penyakit:"Egg Drop Syndrome (EDS-76)", gejala:"Produksi telur turun 10–40%, cangkang lembek/tanpa cangkang, kuning pucat",
      penyebab:"Adenovirus EDS-76 — atau defisiensi Ca/Vit D3", tingkat:"⚠️ Ekonomis besar",
      obat:[
        {nama:"Tidak ada antivirus — suportif",dosis:"—",frekuensi:"—",ket:"Fokus pada perbaikan nutrisi dan imun"},
        {nama:"Vitamin D3 + Ca oral (Calcivet)",dosis:"2 mL/L air minum",frekuensi:"7–14 hari",ket:"Pulihkan Ca serum + kualitas cangkang"},
        {nama:"Limestone/Oyster shell kasar",dosis:"4–5% ransum atau free-choice",frekuensi:"Terus-menerus",ket:"Ca slow-release untuk malam hari (pembentukan cangkang)"},
        {nama:"Vitamin E 500 IU/kg + Se",dosis:"100–200 mg vit E per liter air",frekuensi:"7 hari",ket:"Antioksidan — recovery sistem reproduksi"},
        {nama:"Probiotik + MOS",dosis:"1 g/L air minum",frekuensi:"10–14 hari",ket:"Restorasi gut health + absorpsi Ca"},
      ],
      pencegahan:"Vaksin EDS (sebelum produksi), kualitas kalsium pakan cek rutin, hindari stres panas",
      tradisional:[
        {nama:"Cangkang Tiram / Oyster Shell (free-choice)",dosis:"Sediakan bebas atau 5% ransum",cara:"Taruh di tempat tersendiri, ayam ambil sendiri",ket:"Ca slow-release alami — paling efektif untuk cangkang telur, lebih baik dari kapur halus"},
        {nama:"Tulang Ikan Giling (bone meal lokal)",dosis:"2–3% campuran ransum",cara:"Campur ke pakan",ket:"Ca + P organik dari tulang ikan — bioavailabilitas tinggi"},
        {nama:"Kulit Pisang + Limbah Sayur (fermentasi)",dosis:"10–15% dari total ransum",cara:"Fermentasi 3–5 hari dengan EM4, berikan ke ayam",ket:"Probiotik + vitamin B + mineral — perbaiki penyerapan Ca usus"},
        {nama:"Jamu Kunyit + Temu Ireng + Temulawak",dosis:"200g kunyit + 100g temu ireng + 100g temulawak / 20L air",cara:"Rebus saring, campurkan ke air minum 3× seminggu",ket:"Imunomodulator + anti-stres panas — mempertahankan produksi saat EDS"},
        {nama:"Pengaturan suhu kandang (kipas/misting)",dosis:"Suhu kandang 18–24°C target",cara:"Aktifkan kipas + misting sore hari",ket:"Stres panas adalah trigger EDS — manajemen suhu = obat terbaik EDS non-virus"},
      ],
    },
    {
      penyakit:"Avian Influenza (AI) H5N1 HPAI", gejala:"Kematian massal tiba-tiba, produksi telur stop total, gejala saraf",
      penyebab:"Influenza A HPAI — ZOONOSIS FATAL", tingkat:"🚨 KRITIS — LAPOR SEGERA!",
      obat:[
        {nama:"TIDAK ADA — DEPOPULASI WAJIB",dosis:"—",frekuensi:"—",ket:"Hubungi Dinas Peternakan segera"},
        {nama:"Vaksin AI H5N1 killed 0.5 mL",dosis:"0.5 mL/ekor SC",frekuensi:"Minggu ke-8, 12, 16 + booster setiap 4–6 bulan",ket:"WAJIB untuk semua layer komersial di Indonesia"},
      ],
      pencegahan:"Program vaksin AI wajib, biosekuriti tinggi, monitoring serologi berkala",
      tradisional:[
        {nama:"⚠️ TIDAK ADA obat tradisional untuk HPAI",dosis:"—",cara:"LAPOR Dinas Peternakan dan Satgas AI kabupaten",ket:"HPAI zoonosis fatal — jangan tangani sendiri, evacuate area, pakai APD"},
      ],
    },
    {
      penyakit:"Marek's Disease", gejala:"Kelumpuhan kaki/sayap, tumor organ dalam, mata abu-abu (ocular Marek's)",
      penyebab:"Marek's Disease Virus (Herpesvirus) — menular lewat debu bulu", tingkat:"⚠️ Sangat umum, tidak bisa diobati",
      obat:[
        {nama:"TIDAK ADA obat — PENCEGAHAN MUTLAK",dosis:"—",frekuensi:"—",ket:"Hewan terinfeksi tidak bisa sembuh"},
        {nama:"Vaksin Marek's (HVT/Rispens) 1 dosis",dosis:"1 dosis/ekor SC sayap D1 (DOC)",frekuensi:"Sekali seumur hidup — diberikan di hatchery",ket:"WAJIB diberikan saat DOC, tidak bisa menyusul"},
        {nama:"Vitamin E + Se + Beta-glucan",dosis:"100 IU vit E/L air minum",frekuensi:"Suportif",ket:"Boost imun flock yang belum divaksin"},
      ],
      pencegahan:"Vaksin Marek's D1 di hatchery MUTLAK, DOC harus dari hatchery terpercaya",
      tradisional:[
        {nama:"Tidak ada pengobatan — PENCEGAHAN MUTLAK",dosis:"—",cara:"Fokus pada pencegahan vaksin dan sanitasi",ket:"Marek's tidak bisa disembuhkan. Ayam terinfeksi sebaiknya diafkir"},
        {nama:"Jamu Imunomodulator (pencegahan flock)",dosis:"Kunyit + sambiloto + jahe (400g total) / 20L air",cara:"Berikan ke seluruh flock 2× seminggu sebagai pencegahan",ket:"Boost imunitas flock yang belum vaksin atau vaksin terlambat"},
        {nama:"Ventilasi + sanitasi debu bulu",dosis:"Kontrol debu bulu di kandang",cara:"Semprot air kabut + sapu rutin, ventilasi baik",ket:"Marek's menular lewat debu bulu kering — sanitasi kandang = pencegahan non-vaksin"},
      ],
    },
    {
      penyakit:"Kolera Unggas (Fowl Cholera)", gejala:"Kematian mendadak, mencret kuning-hijau, jengger biru, napas cepat",
      penyebab:"Pasteurella multocida — bakteri", tingkat:"⚠️ Akut bisa mati massal",
      obat:[
        {nama:"Sulfonamide (Sulfadimethoxine) 25%",dosis:"1 g/L air minum (0.05% larutan)",frekuensi:"5–7 hari",ket:"First-line treatment kolera unggas"},
        {nama:"Enrofloxacin 10%",dosis:"10 mg/kg BB (1 mL/L air minum)",frekuensi:"5 hari",ket:"Broad-spectrum — efektif Pasteurella"},
        {nama:"Amoxicillin 70%",dosis:"10–15 mg/kg BB (0.5–1 g/L air)",frekuensi:"5–7 hari",ket:"Alternatif penisilin grup"},
        {nama:"Doxycycline 10%",dosis:"25 mg/kg BB oral",frekuensi:"5 hari",ket:"Efektif + terjangkau"},
      ],
      pencegahan:"Vaksin Fowl Cholera (beberapa produsen), sanitasi air minum, biosekuriti hewan masuk",
      tradisional:[
        {nama:"Bawang Putih + Cuka Apel ke air minum",dosis:"100g bawang putih parut + 50mL cuka apel / 10L air",cara:"Campurkan ke air minum 5–7 hari",ket:"Allicin antibakteri Pasteurella + asam asetat menurunkan pH air — hambat bakteri"},
        {nama:"Jahe + Kunyit + Gula Merah (jamu)",dosis:"200g jahe + 200g kunyit + 100g gula merah / 10L air",cara:"Rebus saring, campurkan ke air minum 2× sehari",ket:"Gingerol + kurkumin — anti-inflamasi + antibakteri gram-negatif"},
        {nama:"Air Kelapa Muda",dosis:"1L air kelapa segar / 5L air minum",cara:"Campurkan ke air minum",ket:"Elektrolit + lauric acid antibakteri — bantu rehidrasi + mencret kolera"},
        {nama:"Sanitasi air minum ketat",dosis:"Cuci tempat minum 2× sehari + klorinasi 3 ppm",cara:"Rendam tempat minum air panas atau bleach 0.5%",ket:"Kolera menular lewat air — sanitasi water system adalah pencegahan utama"},
      ],
    },
    {
      penyakit:"Infectious Coryza (Snot) Layer", gejala:"Ingus kental busuk, bengkak wajah sinus, produksi telur turun 10–40%, nafsu makan turun",
      penyebab:"Avibacterium paragallinarum — bakteri, endemik di farm layer lama, rekuren tiap musim hujan", tingkat:"⚠️ Ekonomis besar — produksi turun lama",
      obat:[
        {nama:"Sulfadimethoxine 25% oral",dosis:"1 g/L air minum",frekuensi:"7–10 hari",ket:"First-line Coryza layer"},
        {nama:"Erythromycin serbuk",dosis:"0.5 g/L air minum",frekuensi:"5–7 hari",ket:"Makrolid — efektif + aman produksi telur"},
        {nama:"Vaksin Coryza inaktif",dosis:"0.5 mL IM",frekuensi:"2× interval 4 minggu + 6 bulan",ket:"Program vaksin rutin di farm endemik snot"},
        {nama:"Vitamin A 30.000 IU/kg pakan",dosis:"Tambahkan ke ransum",frekuensi:"Selama pemulihan 14 hari",ket:"Regenerasi epitel mukosa hidung + saluran pernapasan"},
      ],
      pencegahan:"Vaksin Coryza sebelum produksi (umur 10 minggu + 14 minggu), karantina hewan baru, biosekuriti ketat",
      tradisional:[
        {nama:"Uap Kayu Putih + Bawang Merah",dosis:"50mL kayu putih + 5 bawang merah iris / ember panas",cara:"Uapkan di sudut kandang 3× sehari",ket:"Membuka sinus + quercetin bawang merah anti-inflamasi"},
        {nama:"Jamu Jahe + Kunyit + Madu (imunomodulator)",dosis:"300g jahe + 300g kunyit + 5 sdm madu / 20L air",cara:"Rebus saring, campur ke air minum 2× seminggu rutin",ket:"Pencegahan rekuren snot — boost imun mukosa saluran napas"},
        {nama:"Peningkatan ventilasi kandang",dosis:"Tambah celah ventilasi 20–30%",cara:"Buka tirai sisi kandang lebih lebar saat musim hujan",ket:"Kelembaban tinggi = trigger snot — ventilasi adalah pencegahan primer"},
      ],
    },
    {
      penyakit:"Salmonellosis (Pullorum / Typhoid)", gejala:"DOC: mencret putih kapur (white diarrhea), lemah, menumpuk dekat pemanas. Dewasa: drop produksi, infertilitas",
      penyebab:"Salmonella Pullorum / S.Gallinarum — bakteri, vertikal (telur) + horizontal (feses)", tingkat:"🚨 Kritis DOC + ZOONOSIS ringan",
      obat:[
        {nama:"Enrofloxacin 10%",dosis:"10 mg/kg BB (1 mL/L air minum)",frekuensi:"5–7 hari",ket:"First-line Salmonella layer dan broiler"},
        {nama:"Trimethoprim + Sulfadiazine",dosis:"30 mg/kg BB oral kombinasi",frekuensi:"5–7 hari",ket:"Kombinasi sinergis anti-Salmonella"},
        {nama:"Amoxicillin 70%",dosis:"10–15 mg/kg BB oral",frekuensi:"5–7 hari",ket:"Alternatif — cek sensitivitas isolat lokal"},
        {nama:"Probiotik Lactobacillus competitive exclusion",dosis:"1 g/L air minum DOC mulai D1",frekuensi:"7–14 hari pertama",ket:"Competitive exclusion — PENCEGAHAN terbaik non-antibiotik"},
        {nama:"Sanitasi telur tetas (fumigasi formalin)",dosis:"Fumigasi formaldehid 3% di setter",frekuensi:"Setiap batch penetasan",ket:"Eliminasi Salmonella vertikal dari permukaan telur"},
      ],
      pencegahan:"Program NPIP (test & eliminate), sanitasi hatchery, competitive exclusion DOC, hindari susu mentah unggas",
      tradisional:[
        {nama:"Kunyit + Temulawak + Bawang Putih",dosis:"200g kunyit + 100g temulawak + 100g bawang putih / 10L air",cara:"Rebus saring, campurkan ke air minum DOC",ket:"Anti-Salmonella alami — allicin + kurkumin kombinasi"},
        {nama:"Air Beras + Gula Merah (oralit)",dosis:"Air tajin 500mL + 1 sdm gula merah / L air",cara:"Berikan ke DOC sakit sebagai minum",ket:"Rehidrasi + lapisi mukosa usus dari Salmonella"},
        {nama:"Cuka Apel 5% dalam air minum",dosis:"50mL cuka apel / 1L air minum",cara:"Campurkan ke air minum 5–7 hari",ket:"Asam asetat pH rendah — hambat Salmonella di saluran cerna"},
        {nama:"Arang Aktif oral",dosis:"0.5 sdm / L air minum",cara:"Campurkan ke air minum DOC",ket:"Adsorben toksin Salmonella LPS — bantu kurangi diare"},
      ],
    },
    {
      penyakit:"Aspergillosis (Brooder Pneumonia)", gejala:"DOC kesulitan napas, anak ayam mengantuk, mulut terbuka, kematian D3–10, lesi nodular paru",
      penyebab:"Aspergillus fumigatus — spora jamur dari sekam/litter lembab, kotoran, pakan berjamur", tingkat:"🚨 Kritis DOC — tidak ada antijamur murah",
      obat:[
        {nama:"Itraconazole 10 mg/mL oral",dosis:"10 mg/kg BB PO",frekuensi:"1×/hari, 7–14 hari",ket:"Antijamur azole — efektif Aspergillus, MAHAL"},
        {nama:"Voriconazole (kasus parah)",dosis:"12.5 mg/kg BB PO 2× hari pertama, lalu 6.25 mg/kg",frekuensi:"2×/hari, 7–14 hari",ket:"Second-line — lebih efektif dari itraconazole tapi sangat mahal"},
        {nama:"Copper Sulfate 0.05% air minum",dosis:"0.5 g/L air minum (larutan biru sangat encer)",frekuensi:"3–5 hari",ket:"Fungisida ringan air minum — bantu cegah kolonisasi"},
        {nama:"Vitamin A + E tinggi",dosis:"Vit A 30.000 IU/kg + Vit E 100 IU/L air",frekuensi:"10–14 hari",ket:"Regenerasi epitel paru + boost imun mukosal"},
      ],
      pencegahan:"Ganti litter SEBELUM lembab, fumigasi brooder formalin sebelum DOC masuk, hindari pakan berjamur, ventilasi brooder",
      tradisional:[
        {nama:"⚠️ Antijamur tradisional TIDAK cukup untuk Aspergillus",dosis:"—",cara:"Fokus pada pencegahan dan manajemen brooder",ket:"Aspergillosis sistemik fatal — butuh antijamur kuat. Tradisional hanya preventif"},
        {nama:"Cengkeh + Kayu Manis (fumigasi alami brooder)",dosis:"Rebus 100g cengkeh + 50g kayu manis / 5L air",cara:"Uapkan di dalam brooder kosong sebelum DOC masuk",ket:"Eugenol cengkeh + cinnamaldehyde — antijamur udara alami"},
        {nama:"Litter kering + kapur tohor (UTAMA)",dosis:"Taburi kapur tohor tipis sebelum sekam baru",cara:"Pastikan litter maks 20% kelembaban saat chick-in",ket:"Aspergillus hanya tumbuh di litter lembab — litter kering = pencegahan #1"},
        {nama:"Kunyit + Bawang Putih (air minum preventif)",dosis:"200g kunyit + 100g bawang putih / 10L air",cara:"Rebus saring, campurkan ke air minum DOC",ket:"Kurkumin + allicin — antijamur + imunomodulator preventif DOC"},
      ],
    },
  ]
};

/* ===== HALAMAN: KESEHATAN ===== */
const PageKesehatan = ({ health, setHealth, cattle, sheep, layerFlocks, broilerFlocks, stokObat=[], setStokObat }) => {
  const allA = [...cattle, ...sheep, ...(broilerFlocks||[]), ...(layerFlocks||[])];
  const blank = { animalId:"", animalName:"", animalType:"sapi", date:todayStr(), type:"Sakit", diagnosis:"", treatment:"", cost:"", vet:"", status:"Dalam Perawatan", notes:"" };
  const [form, setForm]         = useState(blank);
  const [modal, setModal]       = useState(false);
  const [filterType, setFilterType] = useState("semua");
  const [search, setSearch]     = useState("");
  const [tabSehat, setTabSehat] = useState("catatan");
  const [refType, setRefType]   = useState("sapi");
  const [refOpen, setRefOpen]   = useState(null);

  const filtered   = health.filter(h =>
    (filterType==="semua" || h.animalType===filterType || h.type===filterType) &&
    (h.animalName.toLowerCase().includes(search.toLowerCase()) || h.diagnosis.toLowerCase().includes(search.toLowerCase()))
  );
  const totalBiaya = health.reduce((s,h)=>s+h.cost,0);
  const aktif      = health.filter(h=>h.status==="Dalam Perawatan").length;

  const save = () => {
    const a = allA.find(x=>x.id===form.animalId);
    setHealth([{ id:newId("KS",health), ...form, cost:+form.cost, animalName:a?a.name:form.animalName }, ...health]);
    setModal(false); setForm(blank);
  };

  const tingkatColor = t => t.startsWith("🚨")?"#ef4444":t.startsWith("⚠️")?"#f59e0b":"#22c55e";
  const refTypeOpts = [{v:"sapi",l:"🐄 Sapi",c:"#f5c842"},{v:"domba",l:"🐑 Domba",c:"#a3e635"},{v:"broiler",l:"🐔 Broiler",c:"#e879f9"},{v:"petelur",l:"🥚 Layer",c:"#f59e0b"}];

  return (
    <div style={S.col}>
      {/* STAT CARDS */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))", gap:12 }}>
        <KartuStat label="Total Catatan" value={health.length}                                                                            color={C.health} icon="sehat" />
        <KartuStat label="Aktif Dirawat" value={aktif}                                                                                   color={C.buy}    icon="warn"  />
        <KartuStat label="Sedang Sakit"  value={health.filter(h=>h.type==="Sakit"&&h.status==="Dalam Perawatan").length}                  color={C.expense}icon="sehat" />
        <KartuStat label="Total Biaya"   value={rp(totalBiaya)}                                                                          color={C.breed}  icon="biaya" />
      </div>

      {/* MAIN TABS */}
      <div style={{ display:"flex", borderBottom:"1px solid #1c1e2b" }}>
        {[{id:"catatan",l:"📋 Catatan Kesehatan"},{id:"stokobat",l:"💊 Stok Obat & Vaksin"},{id:"jadwalvaksin",l:"💉 Jadwal Vaksin"},{id:"referensi",l:"📚 Referensi Penyakit & Obat"}].map(t=>(
          <button key={t.id} onClick={()=>setTabSehat(t.id)}
            style={{background:"none",border:"none",borderBottom:"2px solid "+(tabSehat===t.id?C.health:"transparent"),
              color:tabSehat===t.id?C.health:"#555a6a",padding:"8px 18px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>
            {t.l}
          </button>
        ))}
      </div>

      {/* ════ TAB CATATAN ════ */}
      {tabSehat==="catatan" && (
        <>
          <div style={{ ...S.row, justifyContent:"space-between", flexWrap:"wrap", gap:8 }}>
            <div style={{ ...S.row, flexWrap:"wrap", gap:6 }}>
              <FilterBar active={filterType} items={[{v:"semua",l:"Semua"},{v:"Sakit",l:"Sakit"},{v:"Vaksin",l:"Vaksin"},{v:"Rutin",l:"Rutin"},{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer"}]} onChange={setFilterType} color={C.health} />
              <Cari value={search} onChange={setSearch} placeholder="Cari..." />
            </div>
            <BtnSec onClick={()=>setModal(true)} color={C.health}><Ico n="plus" size={13} color={C.health}/> Catat Kesehatan</BtnSec>
          </div>
          <TableWrap>
            <thead><tr>{["ID","Hewan","Jenis","Tanggal","Tipe","Diagnosa","Penanganan","Biaya","Dokter/Mantri","Status"].map(h=><TH key={h} color={C.health}>{h}</TH>)}</tr></thead>
            <tbody>
              {filtered.length===0 ? <tr><td colSpan={10}><Empty/></td></tr> :
                filtered.map((h,i)=>(
                  <TR key={h.id} i={i} color={C.health}>
                    <TD color={C.dim} mono>{h.id}</TD>
                    <TD bold>{h.animalName}</TD>
                    <td style={S.td}><Badge text={h.animalType}/></td>
                    <TD color={C.dim}>{h.date}</TD>
                    <td style={S.td}><Badge text={h.type}/></td>
                    <TD color={C.muted}>{h.diagnosis||"-"}</TD>
                    <td style={{...S.td,maxWidth:180,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{h.treatment}</td>
                    <TD color={C.breed} bold>{rp(h.cost)}</TD>
                    <TD color={C.muted}>{h.vet}</TD>
                    <td style={S.td}><Badge text={h.status}/></td>
                  </TR>
                ))}
            </tbody>
          </TableWrap>
        </>
      )}

      {/* ════ TAB REFERENSI ════ */}
      

      {/* ════ TAB STOK OBAT ════ */}
      {tabSehat==="stokobat" && (
        <div style={{display:"flex",flexDirection:"column",gap:12}}>
          {(stokObat||[]).filter(s=>s.stok<=s.minStok).length>0 && (
            <div style={{background:"#ef444408",border:"1px solid #ef444425",borderRadius:10,padding:12}}>
              <div style={{color:"#ef4444",fontWeight:700,fontSize:13,marginBottom:6}}>⚠️ STOK KRITIS — ORDER SEGERA!</div>
              {(stokObat||[]).filter(s=>s.stok<=s.minStok).map(s=>(
                <div key={s.id} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #ef444415",fontSize:11}}>
                  <span style={{color:"#fca5a5"}}>{s.nama}</span>
                  <span style={{color:"#ef4444",fontWeight:700}}>Stok: {s.stok} {s.satuan} / Min: {s.minStok}</span>
                </div>
              ))}
            </div>
          )}
          {(()=>{const in90d=new Date();in90d.setDate(in90d.getDate()+90);const exp=(stokObat||[]).filter(s=>s.kadaluarsa&&new Date(s.kadaluarsa)<=in90d);return exp.length>0?(<div style={{background:"#f59e0b08",border:"1px solid #f59e0b25",borderRadius:10,padding:12}}><div style={{color:"#f59e0b",fontWeight:700,fontSize:13,marginBottom:6}}>📅 Kadaluarsa dalam 90 Hari</div>{exp.map(s=>(<div key={s.id} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",fontSize:11}}><span style={{color:"#fde68a"}}>{s.nama}</span><span style={{color:"#f59e0b",fontWeight:700}}>Exp: {s.kadaluarsa} · {s.stok} {s.satuan}</span></div>))}</div>):null;})()}
          <TableWrap>
            <thead><tr>{["Nama","Jenis","Stok","Min","Kadaluarsa","Harga","Nilai","Status"].map(h=><TH key={h} color="#ec4899">{h}</TH>)}</tr></thead>
            <tbody>
              {(stokObat||[]).map((s,i)=>{const kritis=s.stok<=s.minStok;const exp90=s.kadaluarsa&&new Date(s.kadaluarsa)<=new Date(Date.now()+90*86400000);return(<TR key={s.id} i={i} color="#ec4899"><TD bold>{s.nama}</TD><td style={S.td}><Badge text={s.jenis}/></td><TD color={kritis?"#ef4444":"#22c55e"} bold>{s.stok} {s.satuan}</TD><TD color={C.dim}>{s.minStok}</TD><TD color={exp90?"#f59e0b":C.muted}>{s.kadaluarsa||"—"}{exp90?" ⚠️":""}</TD><TD color={C.muted}>{rp(s.hargaSatuan)}</TD><TD color="#22c55e" bold>{rp(s.stok*s.hargaSatuan)}</TD><td style={S.td}><Badge text={kritis?"KRITIS":"Aman"}/></td></TR>);})}
            </tbody>
          </TableWrap>
        </div>
      )}

      {/* ════ TAB JADWAL VAKSIN ════ */}
      {tabSehat==="jadwalvaksin" && (
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          {[{jenis:"🐔 Broiler",data:JADWAL_VAKSIN_BROILER,kf:"hari",color:"#e879f9"},{jenis:"🥚 Layer",data:JADWAL_VAKSIN_LAYER,kf:"minggu",color:"#f59e0b"},{jenis:"🐄 Sapi",data:JADWAL_VAKSIN_SAPI,kf:"bulan",color:"#f5c842"}].map(({jenis,data,kf,color})=>(
            <div key={jenis} style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
              <div style={{color,fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>{jenis}</div>
              <TableWrap>
                <thead><tr>{["Waktu","Vaksin","Cara","Dosis","Catatan"].map(h=><TH key={h} color={color}>{h}</TH>)}</tr></thead>
                <tbody>{(data||[]).map((v,i)=>(<TR key={i} i={i} color={color}><TD bold color={color}>{kf==="hari"?"D"+v[kf]:v[kf]}</TD><TD bold>{v.vaksin}</TD><td style={S.td}><Badge text={v.cara}/></td><TD color={C.muted}>{v.dosis||"—"}</TD><TD color={v.catatan?.includes("WAJIB")?"#f59e0b":C.muted}>{v.catatan||"—"}</TD></TR>))}</tbody>
              </TableWrap>
            </div>
          ))}
        </div>
      )}

      {tabSehat==="referensi" && (
        <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
          {/* Pilih jenis */}
          <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
            {refTypeOpts.map(t=>(
              <button key={t.v} onClick={()=>{ setRefType(t.v); setRefOpen(null); }}
                style={{ background:refType===t.v?t.c+"20":"#0f1118", border:"1px solid "+(refType===t.v?t.c+"50":C.border), borderRadius:10, padding:"9px 18px", cursor:"pointer", color:refType===t.v?t.c:C.muted, fontWeight:700, fontSize:13 }}>
                {t.l}
              </button>
            ))}
          </div>

          {/* Disclaimer */}
          <div style={{ background:"#3b82f60a", border:"1px solid #3b82f620", borderRadius:9, padding:"9px 14px", fontSize:11, color:"#555a6a", display:"flex", gap:8 }}>
            <span style={{ color:"#3b82f6" }}>ℹ️</span>
            <span>Dosis adalah panduan umum berdasarkan referensi veteriner standar. Selalu konsultasikan dengan dokter hewan / mantri sebelum pengobatan. Patuhi withdrawal period antibiotik sebelum panen / pemerahan.</span>
          </div>

          {/* Daftar penyakit */}
          <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
            {(REF_PENYAKIT[refType]||[]).map((ref,idx)=>{
              const isOpen  = refOpen===idx;
              const tc      = tingkatColor(ref.tingkat);
              const refCol  = refTypeOpts.find(x=>x.v===refType)?.c || C.health;
              return (
                <div key={idx} style={{ background:"#0f1118", border:"1px solid "+(isOpen?refCol+"40":"#1c1e2b"), borderRadius:13, overflow:"hidden", transition:"border 0.15s" }}>
                  {/* Header — klik untuk buka/tutup */}
                  <div onClick={()=>setRefOpen(isOpen?null:idx)}
                    style={{ padding:"14px 18px", cursor:"pointer", display:"flex", justifyContent:"space-between", alignItems:"center", gap:12, background:isOpen?refCol+"0c":"transparent" }}>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ display:"flex", alignItems:"center", gap:10, flexWrap:"wrap", marginBottom:4 }}>
                        <span style={{ color:C.text, fontWeight:800, fontSize:15 }}>{ref.penyakit}</span>
                        <span style={{ background:tc+"15", color:tc, border:"1px solid "+tc+"30", borderRadius:20, padding:"2px 10px", fontSize:10, fontWeight:700 }}>{ref.tingkat}</span>
                      </div>
                      <div style={{ color:"#9097a8", fontSize:12 }}>{ref.gejala}</div>
                      <div style={{ color:"#555a6a", fontSize:11, marginTop:3 }}>
                        <span style={{ color:"#60a5fa" }}>Penyebab:</span> {ref.penyebab}
                      </div>
                    </div>
                    <div style={{ color:refCol, fontSize:16, flexShrink:0 }}>{isOpen?"▲":"▼"}</div>
                  </div>

                  {/* Detail — accordion */}
                  {isOpen && (
                    <div style={{ padding:"0 18px 18px" }}>
                      {/* Tabel obat */}
                      <div style={{ color:C.health, fontFamily:"'DM Serif Display',serif", fontSize:13, margin:"12px 0 10px" }}>
                        💊 Obat & Dosis Penanganan
                      </div>
                      <div style={{ overflowX:"auto" }}>
                        <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
                          <thead>
                            <tr style={{ background:refCol+"0a", borderBottom:"1px solid "+refCol+"28" }}>
                              {["Nama Obat","Dosis per kg/ekor","Frekuensi & Durasi","Keterangan"].map(h=>(
                                <th key={h} style={{ padding:"8px 11px", color:refCol, textAlign:"left", fontSize:9, fontWeight:800, textTransform:"uppercase", whiteSpace:"nowrap" }}>{h}</th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {ref.obat.map((o,oi)=>(
                              <tr key={oi} style={{ borderBottom:"1px solid #1c1e2b", background:oi%2?"#ffffff02":"transparent" }}>
                                <td style={{ padding:"9px 11px", color:"#e2e4f0", fontWeight:700, fontSize:12 }}>{o.nama}</td>
                                <td style={{ padding:"9px 11px" }}>
                                  <span style={{ background:refCol+"15", color:refCol, border:"1px solid "+refCol+"28", borderRadius:8, padding:"3px 9px", fontSize:11, fontWeight:800, whiteSpace:"nowrap" }}>{o.dosis}</span>
                                </td>
                                <td style={{ padding:"9px 11px", color:"#f59e0b", fontSize:12, fontWeight:600, whiteSpace:"nowrap" }}>{o.frekuensi}</td>
                                <td style={{ padding:"9px 11px", color:"#9097a8", fontSize:11, lineHeight:1.4 }}>{o.ket}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>

                      {/* Tradisional */}
                      {ref.tradisional && ref.tradisional.length > 0 && (
                        <div style={{ marginTop:14 }}>
                          <div style={{ color:"#a3e635", fontFamily:"'DM Serif Display',serif", fontSize:13, marginBottom:10 }}>
                            🌿 Penanganan & Obat Tradisional
                          </div>
                          <div style={{ fontSize:10, color:"#555a6a", marginBottom:9, background:"#a3e63508", border:"1px solid #a3e63520", borderRadius:7, padding:"7px 11px" }}>
                            ⚠️ Obat tradisional bersifat <strong style={{color:"#f59e0b"}}>suportif & pendamping</strong> — bukan pengganti obat modern. Efektivitas bervariasi. Gunakan sebagai pertolongan pertama atau saat akses veteriner terbatas.
                          </div>
                          <div style={{ overflowX:"auto" }}>
                            <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
                              <thead>
                                <tr style={{ background:"#a3e6350a", borderBottom:"1px solid #a3e63528" }}>
                                  {["Bahan / Ramuan","Dosis / Takaran","Cara Pemberian","Keterangan"].map(h=>(
                                    <th key={h} style={{ padding:"8px 11px", color:"#a3e635", textAlign:"left", fontSize:9, fontWeight:800, textTransform:"uppercase", whiteSpace:"nowrap" }}>{h}</th>
                                  ))}
                                </tr>
                              </thead>
                              <tbody>
                                {ref.tradisional.map((t,ti)=>(
                                  <tr key={ti} style={{ borderBottom:"1px solid #1c1e2b", background:t.nama.startsWith("⚠️")?"#ef444408":ti%2?"#ffffff02":"transparent" }}>
                                    <td style={{ padding:"9px 11px", color:t.nama.startsWith("⚠️")?"#fca5a5":"#a3e635", fontWeight:700, fontSize:12 }}>{t.nama}</td>
                                    <td style={{ padding:"9px 11px" }}>
                                      <span style={{ background:"#a3e63512", color:"#a3e635", border:"1px solid #a3e63525", borderRadius:8, padding:"3px 9px", fontSize:11, fontWeight:700 }}>{t.dosis}</span>
                                    </td>
                                    <td style={{ padding:"9px 11px", color:"#f59e0b", fontSize:12, lineHeight:1.4 }}>{t.cara}</td>
                                    <td style={{ padding:"9px 11px", color:"#9097a8", fontSize:11, lineHeight:1.4 }}>{t.ket}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      )}

                      {/* Pencegahan */}
                      <div style={{ marginTop:14, background:"#22c55e0a", border:"1px solid #22c55e22", borderRadius:9, padding:"10px 14px" }}>
                        <span style={{ color:"#22c55e", fontWeight:700, fontSize:12 }}>🛡️ Pencegahan: </span>
                        <span style={{ color:"#9097a8", fontSize:12 }}>{ref.pencegahan}</span>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ════ MODAL CATAT ════ */}
      {modal && (
        <Modal title="Catat Kesehatan Hewan" onClose={()=>setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Jenis Ternak" value={form.animalType} onChange={v=>setForm({...form,animalType:v,animalId:""})} options={[{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer/Petelur"}]} />
            <div>
              <label style={S.label}>Pilih Kandang/Hewan</label>
              <select value={form.animalId} onChange={e=>{ const a=allA.find(x=>x.id===e.target.value); setForm({...form,animalId:e.target.value,animalName:a?a.name:""}); }} style={S.select}>
                <option value="">-- Pilih --</option>
                {(form.animalType==="sapi"?cattle:form.animalType==="domba"?sheep:form.animalType==="broiler"?(broilerFlocks||[]):(layerFlocks||[])).map(a=>(
                  <option key={a.id} value={a.id}>{a.name}{a.health?" — "+a.health:a.status?" — "+a.status:""}</option>
                ))}
              </select>
            </div>
            {!form.animalId && <Inp label="Nama Hewan/Kandang" value={form.animalName} onChange={v=>setForm({...form,animalName:v})} span />}
            <Inp label="Tanggal" value={form.date} onChange={v=>setForm({...form,date:v})} type="date" />
            <Inp label="Tipe" value={form.type} onChange={v=>setForm({...form,type:v})} options={["Sakit","Vaksin","Rutin","Operasi","Cedera"]} />
            <Inp label="Diagnosa / Penyakit" value={form.diagnosis} onChange={v=>setForm({...form,diagnosis:v})} placeholder="ND, Gumboro, CRD, Kembung, Cacingan..." />
            <Inp label="Biaya (Rp)" value={form.cost} onChange={v=>setForm({...form,cost:v})} type="number" />
            <Inp label="Penanganan / Obat + Dosis" value={form.treatment} onChange={v=>setForm({...form,treatment:v})} span />
            <Inp label="Dokter / Mantri" value={form.vet} onChange={v=>setForm({...form,vet:v})} />
            <Inp label="Status" value={form.status} onChange={v=>setForm({...form,status:v})} options={["Dalam Perawatan","Selesai","Meninggal"]} />
            <Textarea label="Catatan" value={form.notes} onChange={v=>setForm({...form,notes:v})} span />
          </div>
          <BtnPrimary onClick={save} color={C.health} full>Simpan Catatan</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ===== HALAMAN: BREEDING ===== */
const PageBreeding = ({ breeding=[], setBreeding, cattle=[], sheep=[], layerFlocks=[], broilerFlocks=[] }) => {
  const isAyam   = t => t === "petelur" || t === "broiler";
  const tcColor  = t => t==="sapi"?C.sapi:t==="domba"?C.domba:t==="broiler"?"#e879f9":"#f59e0b";
  const tcLabel  = t => t==="sapi"?"🐄 Sapi":t==="domba"?"🐑 Domba":t==="broiler"?"🐔 Broiler":"🥚 Layer";
  const tcEmoji  = t => t==="sapi"?"🐄":t==="domba"?"🐑":t==="broiler"?"🐔":"🥚";

  const blank = {
    indukId:"", indukName:"", animalType:"sapi",
    pejantan:"", method:"IB", date:todayStr(),
    status:"Menunggu", estimasiLahir:"", anakLahir:"",
    telurDitetaskan:"", fertilitasPct:"", daya_tetas_pct:"",
    notes:""
  };
  const [form, setForm]         = useState(blank);
  const [modal, setModal]       = useState(false);
  const [filterType, setFilterType] = useState("semua");

  const femaleCattle  = cattle.filter(c => c.gender === "Betina");
  const femaleSheep   = sheep.filter(d => d.gender === "Betina");
  const filtered = filterType === "semua" ? breeding : breeding.filter(b => b.animalType === filterType);

  // Stat aggregates
  const totalLahir   = breeding.reduce((s,b) => s+(+b.anakLahir||0), 0);
  const totalTetaskan= breeding.filter(b=>isAyam(b.animalType)).reduce((s,b)=>s+(+b.telurDitetaskan||0),0);
  const totalDOC     = breeding.filter(b=>isAyam(b.animalType)).reduce((s,b)=>s+(+b.anakLahir||0),0);
  const avgDayaTetas = (() => {
    const rows = breeding.filter(b=>isAyam(b.animalType)&&(+b.daya_tetas_pct||0)>0);
    return rows.length ? (rows.reduce((s,b)=>s+(+b.daya_tetas_pct||0),0)/rows.length).toFixed(1) : "—";
  })();

  const statusColor = {
    Bunting:C.breed, Melahirkan:C.sell, Menunggu:C.buy, Gagal:C.expense,
    Bertelur:"#f59e0b", Inkubasi:"#60a5fa", Menetas:C.sell, Batal:C.expense
  };

  const save = () => {
    let indukName = form.indukName;
    if (!indukName) {
      const src = form.animalType==="sapi" ? femaleCattle : form.animalType==="domba" ? femaleSheep : form.animalType==="broiler" ? (broilerFlocks||[]) : (layerFlocks||[]);
      const found = src.find(a => a.id === form.indukId);
      if (found) indukName = found.name;
    }
    setBreeding([...breeding, {
      id: newId("BR", breeding), ...form,
      anakLahir: +form.anakLahir||0,
      telurDitetaskan: +form.telurDitetaskan||0,
      fertilitasPct: +form.fertilitasPct||0,
      daya_tetas_pct: +form.daya_tetas_pct||0,
      indukName,
    }]);
    setModal(false); setForm(blank);
  };

  // Modal field set varies by type
  const isAyamForm = isAyam(form.animalType);
  const methodOpts = isAyamForm
    ? ["Mesin Tetas","Tetasan","Kawin Alam (Kandang)","IB Unggas"]
    : ["IB","Kawin Alam","ET"];
  const statusOpts = isAyamForm
    ? ["Menunggu","Bertelur","Inkubasi","Menetas","Batal"]
    : ["Menunggu","Bunting","Melahirkan","Gagal"];

  const srcList = form.animalType==="sapi" ? femaleCattle
    : form.animalType==="domba" ? femaleSheep
    : form.animalType==="broiler" ? (broilerFlocks||[])
    : (layerFlocks||[]);

  return (
    <div style={S.col}>
      {/* ── STAT CARDS ── */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))", gap:12 }}>
        <KartuStat label="Program Sapi"    value={breeding.filter(b=>b.animalType==="sapi").length}   color={C.sapi}    icon="sapi"   />
        <KartuStat label="Bunting Sapi"    value={breeding.filter(b=>b.status==="Bunting"&&b.animalType==="sapi").length}  color={C.breed}  icon="kawin"  />
        <KartuStat label="Program Domba"   value={breeding.filter(b=>b.animalType==="domba").length}  color={C.domba}   icon="domba"  />
        <KartuStat label="Bunting Domba"   value={breeding.filter(b=>b.status==="Bunting"&&b.animalType==="domba").length} color={C.health} icon="kawin"  />
        <KartuStat label="Broiler Breed"   value={breeding.filter(b=>b.animalType==="broiler").length} color="#e879f9"  icon="broiler" />
        <KartuStat label="Layer Breed"     value={breeding.filter(b=>b.animalType==="petelur").length} color="#f59e0b"  icon="petelur" />
        {(()=>{const ib=breeding.filter(b=>b.jenis==="IB"||b.type==="IB"||b.method==="IB").length; const bnt=breeding.filter(b=>b.status==="Bunting").length; const sc=bnt>0?(ib/bnt).toFixed(2):"—"; return <KartuStat label="S/C Ratio" value={sc} sub={"IB "+ib+"× Bunting "+bnt+"×"} color={sc!=="—"&&parseFloat(sc)<=1.5?"#22c55e":"#f59e0b"} icon="breed"/>; })()}
        <KartuStat label="Total DOC Tetas" value={totalDOC+" ekor"}   color={C.sell}   icon="sehat"  />
        <KartuStat label="Avg Daya Tetas"  value={avgDayaTetas+(avgDayaTetas!=="—"?"%":"")} color="#60a5fa" icon="laporan" />
      </div>

      {/* Ringkasan hatchery jika ada ayam */}
      {totalTetaskan > 0 && (
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))", gap:10 }}>
          {[
            ["🥚 Total Telur Ditetaskan", totalTetaskan+" butir", "#f59e0b"],
            ["🐣 Total DOC Menetas",       totalDOC+" ekor",       C.sell],
            ["📊 Avg Daya Tetas",          avgDayaTetas+(avgDayaTetas!=="—"?"%":""),   "#60a5fa"],
            ["🌡️ Batch Inkubasi Aktif",   breeding.filter(b=>b.status==="Inkubasi").length+" batch", C.breed],
          ].map(([l,v,col])=>(
            <div key={l} style={{background:col+"0c",border:"1px solid "+col+"25",borderRadius:11,padding:"12px 15px"}}>
              <div style={{fontSize:10,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:4}}>{l}</div>
              <div style={{color:col,fontWeight:800,fontSize:16}}>{v}</div>
            </div>
          ))}
        </div>
      )}

      {/* ── FILTER + TOMBOL ── */}
      <div style={{ ...S.row, justifyContent:"space-between", flexWrap:"wrap", gap:8 }}>
        <FilterBar active={filterType}
          items={[{v:"semua",l:"Semua"},{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer"}]}
          onChange={setFilterType} color={C.breed} />
        <BtnSec onClick={() => setModal(true)} color={C.breed}><Ico n="plus" size={13} color={C.breed} /> Catat Breeding</BtnSec>
      </div>

      {/* ── KARTU BREEDING ── */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(270px,1fr))", gap:14 }}>
        {filtered.length === 0 && <div style={{ color:C.dim, padding:40, textAlign:"center", gridColumn:"1/-1" }}>Belum ada data breeding</div>}
        {filtered.map(b => {
          const sc2  = statusColor[b.status] || C.muted;
          const tc   = tcColor(b.animalType);
          const ayam = isAyam(b.animalType);
          return (
            <div key={b.id} style={{ background:C.breed+"07", border:"1px solid "+C.breed+"20", borderRadius:13, padding:16 }}>
              {/* Header */}
              <div style={{ ...S.row, justifyContent:"space-between", alignItems:"flex-start", marginBottom:12 }}>
                <div>
                  <div style={{ color:C.text, fontWeight:700, fontSize:14 }}>{b.indukName}</div>
                  <span style={{ background:tc+"14", color:tc, border:"1px solid "+tc+"28", borderRadius:20, padding:"2px 8px", fontSize:10, fontWeight:700, marginTop:4, display:"inline-block" }}>
                    {tcLabel(b.animalType)}
                  </span>
                </div>
                <span style={{ background:sc2+"14", color:sc2, border:"1px solid "+sc2+"28", borderRadius:20, padding:"4px 10px", fontSize:11, fontWeight:700 }}>{b.status}</span>
              </div>

              {/* Info grid sapi/domba */}
              {!ayam && (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:7, marginBottom:10 }}>
                  {[["PEJANTAN",b.pejantan,C.breed],["METODE",b.method,C.text],["TGL KAWIN",b.date,C.muted],["EST. LAHIR",b.estimasiLahir||"-",C.sell]].map(([k,v,col])=>(
                    <InfoBox key={k} label={k} value={v} color={col} />
                  ))}
                </div>
              )}

              {/* Info grid ayam — hatchery */}
              {ayam && (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:7, marginBottom:10 }}>
                  {[
                    ["METODE",      b.method,                                                   "#60a5fa"],
                    ["TGL MASUK",   b.date,                                                     C.muted],
                    ["EST. MENETAS",b.estimasiLahir||"—",                                       C.sell],
                    ["TELUR",       (b.telurDitetaskan||0)+" butir",                            "#f59e0b"],
                    ["FERTILITAS",  (b.fertilitasPct||0)+"%",                                   C.breed],
                    ["DAYA TETAS",  b.daya_tetas_pct?(b.daya_tetas_pct+"%"):"(belum)",         b.daya_tetas_pct>=80?C.sell:b.daya_tetas_pct>0?"#f59e0b":C.dim],
                  ].map(([k,v,col])=>(
                    <InfoBox key={k} label={k} value={v} color={col} />
                  ))}
                </div>
              )}

              {/* Hasil */}
              {(+b.anakLahir||0) > 0 && (
                <div style={{ background:C.sell+"10", border:"1px solid "+C.sell+"22", borderRadius:7, padding:"8px 10px", marginBottom:8, color:C.sell, fontWeight:700, fontSize:12 }}>
                  {ayam ? "🐣 DOC Menetas: " : "🐣 Lahir: "}{b.anakLahir} ekor
                  {ayam && b.telurDitetaskan > 0 && (
                    <span style={{ color:C.muted, fontWeight:400, fontSize:11, marginLeft:8 }}>
                      ({((+b.anakLahir/+b.telurDitetaskan)*100).toFixed(1)}% dari {b.telurDitetaskan} butir)
                    </span>
                  )}
                </div>
              )}
              {b.notes && <div style={{ background:"#ffffff04", borderRadius:7, padding:8, color:C.muted, fontSize:11 }}>📝 {b.notes}</div>}
            </div>
          );
        })}
      </div>

      {/* ── MODAL FORM ── */}
      {modal && (
        <Modal title="Catat Program Breeding" onClose={() => setModal(false)}>
          <div style={S.grid2}>
            {/* Jenis ternak */}
            <Inp label="Jenis Ternak" value={form.animalType}
              onChange={v => setForm({ ...form, animalType:v, indukId:"", method: (v==="petelur"||v==="broiler")?"Mesin Tetas":"IB", status:(v==="petelur"||v==="broiler")?"Menunggu":"Menunggu" })}
              options={[{v:"sapi",l:"🐄 Sapi"},{v:"domba",l:"🐑 Domba"},{v:"broiler",l:"🐔 Broiler"},{v:"petelur",l:"🥚 Layer/Petelur"}]} />

            {/* Pilih induk / kandang */}
            <div>
              <label style={S.label}>{isAyamForm ? "Kandang Induk" : "Induk Betina"}</label>
              <select value={form.indukId} onChange={e => setForm({ ...form, indukId:e.target.value })} style={S.select}>
                <option value="">-- Pilih atau isi manual --</option>
                {srcList.map(a => (
                  <option key={a.id} value={a.id}>
                    {a.name} — {a.breed||a.type}{a.age?" — "+a.age+"bln":a.jumlah?" — "+a.jumlah.toLocaleString("id-ID")+" ekor":""}
                  </option>
                ))}
              </select>
            </div>

            {/* Nama manual jika tidak pilih */}
            {!form.indukId && (
              <Inp label={isAyamForm?"Nama Kandang/Batch":"Nama Induk"} value={form.indukName} onChange={v => setForm({ ...form, indukName:v })} span />
            )}

            {/* Pejantan — hanya sapi/domba & broiler parent stock */}
            {!isAyamForm && (
              <Inp label="Pejantan / Semen" value={form.pejantan} onChange={v => setForm({ ...form, pejantan:v })} placeholder={form.animalType==="sapi"?"Simental (IB)":"Garut Super"} />
            )}

            <Inp label={isAyamForm?"Metode Penetasan":"Metode Perkawinan"} value={form.method}
              onChange={v => setForm({ ...form, method:v })} options={methodOpts} />
            <Inp label={isAyamForm?"Tanggal Masuk Tetas":"Tanggal Kawin"} value={form.date}
              onChange={v => setForm({ ...form, date:v })} type="date" />
            <Inp label={isAyamForm?"Estimasi Menetas":"Estimasi Lahir"} value={form.estimasiLahir}
              onChange={v => setForm({ ...form, estimasiLahir:v })} type="date" />
            <Inp label="Status" value={form.status}
              onChange={v => setForm({ ...form, status:v })} options={statusOpts} />

            {/* Field khusus ayam — hatchery */}
            {isAyamForm && (
              <>
                <Inp label="Jumlah Telur Ditetaskan (butir)" value={form.telurDitetaskan}
                  onChange={v => setForm({ ...form, telurDitetaskan:v })} type="number" placeholder="0" />
                <Inp label="Fertilitas (%)" value={form.fertilitasPct}
                  onChange={v => setForm({ ...form, fertilitasPct:v })} type="number" placeholder="88–92" />
                <Inp label="Daya Tetas / HDR (%)" value={form.daya_tetas_pct}
                  onChange={v => setForm({ ...form, daya_tetas_pct:v })} type="number" placeholder="0 jika belum" />
              </>
            )}

            <Inp label={isAyamForm?"DOC Menetas (ekor)":"Jumlah Anak Lahir"} value={form.anakLahir}
              onChange={v => setForm({ ...form, anakLahir:v })} type="number" placeholder="0" />

            {/* Preview daya tetas live */}
            {isAyamForm && form.telurDitetaskan && form.anakLahir && (
              <div style={{ gridColumn:"1/-1", background:"#60a5fa0a", border:"1px solid #60a5fa22", borderRadius:9, padding:"10px 14px" }}>
                <span style={{ fontSize:12, color:"#60a5fa" }}>
                  📊 Daya Tetas: <strong>{((+form.anakLahir/+form.telurDitetaskan)*100).toFixed(1)}%</strong>
                  {" · "}Mortalitas telur: <strong>{+form.telurDitetaskan-(+form.anakLahir||0)} butir</strong>
                  {form.fertilitasPct && " · Fertilitas: "+form.fertilitasPct+"%"}
                </span>
              </div>
            )}

            <Textarea label="Catatan" value={form.notes} onChange={v => setForm({ ...form, notes:v })} span />
          </div>
          <BtnPrimary onClick={save} color={C.breed} full>Simpan Breeding</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ===== HALAMAN: PENGELUARAN ===== */
const PageBiaya = ({ expenses=[], setExpenses }) => {
  const blank = { category: "Pakan", description: "", amount: "", date: todayStr(), animalType: "semua", notes: "" };
  const [form, setForm] = useState(blank);
  const [modal, setModal] = useState(false);
  const [filter, setFilter] = useState("semua");

  const catColors = { "Pakan": C.sell, "Kesehatan": C.health, "Tenaga Kerja": C.info, "Transportasi": C.buy, "Kandang": C.breed, "Peralatan": C.muted, "Lainnya": C.dim };
  const filtered = filter === "semua" ? expenses : expenses.filter(e => e.category === filter || e.animalType === filter);
  const total = expenses.reduce((s, e) => s + e.amount, 0);
  const byCategory = expenses.reduce((acc, e) => { acc[e.category] = (acc[e.category] || 0) + e.amount; return acc; }, {});

  const save = () => {
    setExpenses([...expenses, { id: newId("OP", expenses), ...form, amount: +form.amount }]);
    setModal(false); setForm(blank);
  };
  return (
    <div style={S.col}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        <KartuStat label="Total Pengeluaran" value={rp(total)} color={C.expense} icon="biaya" />
        {Object.entries(byCategory).slice(0, 4).map(([cat, amt]) => (
          <KartuStat key={cat} label={cat} value={rp(amt)} color={catColors[cat] || C.muted} icon="chart" />
        ))}
      </div>

      <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 13, padding: 18 }}>
        <div style={{ color: C.expense, fontWeight: 700, fontSize: 14, marginBottom: 14, fontFamily: "'DM Serif Display',serif" }}>Distribusi Pengeluaran</div>
        {Object.entries(byCategory).map(([cat, amt]) => (
          <div key={cat} style={{ marginBottom: 10 }}>
            <div style={{ ...S.row, justifyContent: "space-between", marginBottom: 4 }}>
              <span style={{ color: C.muted, fontSize: 12 }}>{cat}</span>
              <span style={{ color: catColors[cat] || C.muted, fontWeight: 700, fontSize: 12 }}>{rp(amt)}</span>
            </div>
            <div style={{ height: 4, background: C.border, borderRadius: 3 }}>
              <div style={{ height: 4, borderRadius: 3, background: catColors[cat] || C.muted, width: `${total > 0 ? (amt / total) * 100 : 0}%`, transition: "width 0.4s" }} />
            </div>
          </div>
        ))}
      </div>

      <div style={{ ...S.row, justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
        <FilterBar active={filter} items={[{ v: "semua", l: "Semua" }, ...Object.keys(catColors).map(k => ({ v: k, l: k }))]} onChange={setFilter} color={C.expense} />
        <BtnSec onClick={() => setModal(true)} color={C.expense}><Ico n="plus" size={13} color={C.expense} /> Tambah Pengeluaran</BtnSec>
      </div>

      <TableWrap>
        <thead><tr>{["ID", "Kategori", "Deskripsi", "Jumlah", "Tanggal", "Untuk", "Catatan"].map(h => <TH key={h} color={C.expense}>{h}</TH>)}</tr></thead>
        <tbody>
          {filtered.length === 0 ? <tr><td colSpan={7}><Empty /></td></tr> :
            filtered.map((e, i) => (
              <TR key={e.id} i={i} color={C.expense}>
                <TD color={C.dim} mono>{e.id}</TD>
                <td style={S.td}><span style={{ color: catColors[e.category] || C.muted, fontWeight: 700 }}>{e.category}</span></td>
                <TD>{e.description}</TD>
                <TD color={C.expense} bold>{rp(e.amount)}</TD>
                <TD color={C.dim}>{e.date}</TD>
                <td style={S.td}><Badge text={e.animalType} /></td>
                <TD color={C.dim}>{e.notes || "-"}</TD>
              </TR>
            ))}
        </tbody>
      </TableWrap>

      {modal && (
        <Modal title="Catat Pengeluaran" onClose={() => setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Kategori" value={form.category} onChange={v => setForm({ ...form, category: v })} options={["Pakan", "Kesehatan", "Tenaga Kerja", "Transportasi", "Kandang", "Peralatan", "Lainnya"]} />
            <Inp label="Untuk Ternak" value={form.animalType} onChange={v => setForm({ ...form, animalType: v })} options={[{ v: "semua", l: "Semua" }, { v: "sapi", l: "🐄 Sapi" }, { v: "domba", l: "🐑 Domba" }]} />
            <Inp label="Deskripsi" value={form.description} onChange={v => setForm({ ...form, description: v })} required span />
            <Inp label="Jumlah (Rp)" value={form.amount} onChange={v => setForm({ ...form, amount: v })} type="number" />
            <Inp label="Tanggal" value={form.date} onChange={v => setForm({ ...form, date: v })} type="date" />
            <Textarea label="Catatan" value={form.notes} onChange={v => setForm({ ...form, notes: v })} span />
          </div>
          <BtnPrimary onClick={save} color={C.expense} full>Simpan Pengeluaran</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ===== HALAMAN: DASHBOARD ===== */
const Dashboard = ({ cattle=[], sheep=[], sales=[], feed=[], expenses=[], health=[], breeding=[], broilerFlocks=[], layerFlocks=[], harvests=[], target=[], absensi=[], karyawan=[] }) => {
  const bf = broilerFlocks||[]; const lf = layerFlocks||[]; const hv = harvests||[];
  const allA = [...cattle, ...sheep];
  const totalNilai = allA.reduce((s,a)=>s+nilaiEst(a),0);
  const totalProfit = sales.reduce((s,t)=>s+t.profit,0);
  const totalOps = expenses.reduce((s,e)=>s+e.amount,0);
  const profitBersih = totalProfit - totalOps;
  const totalSakit = allA.filter(a=>a.health==="Sakit").length;
  const lowFeed = feed.filter(f=>f.usagePerDay>0&&f.stock/f.usagePerDay<7).length;
  const siapJual = allA.filter(a=>a.status==="Siap Jual");
  const broilerAktif = bf.filter(f=>f.status==="Pembesaran"||f.status==="Siap Panen");
  const totalBroilerEkor = broilerAktif.reduce((s,f)=>s+f.jumlah,0);
  const layerAktif = lf.filter(f=>f.status==="Produksi");
  const totalLayerEkor = layerAktif.reduce((s,f)=>s+f.jumlah,0);
  const totalHDP = layerAktif.length ? (layerAktif.reduce((s,f)=>s+(parseFloat(f.produksiHarian||0)/f.jumlah),0)/layerAktif.length*100).toFixed(1) : 0;
  // IP Broiler = (BB rata × Liveability % ÷ FCR ÷ Umur) × 100 — standar Cobb
  const avgIP = broilerAktif.length ? broilerAktif.reduce((s,f)=>{
    const liv=(f.jumlah/Math.max(f.jumlahAwal||1,1)*100)||100;
    const ip=f.beratRata&&f.fcr&&f.umurHari ? (f.beratRata*liv/f.fcr/f.umurHari*100) : 0;
    return s+ip;
  },0)/broilerAktif.length : 0;
  const avgFCRDash = broilerAktif.length ? (broilerAktif.reduce((s,f)=>s+(parseFloat(f.fcr)||0),0)/broilerAktif.length).toFixed(2) : 0;
  // IOFC broiler — Income Over Feed Cost (per ekor)
  const avgIOFC = bf.filter(f=>f.status==="Sudah Panen").length ?
    hv.slice(-3).reduce((s,h)=>s+(h.totalPendapatan-(h.jumlahPanen*(h.beratRata||2)*4500)),0) / Math.max(hv.slice(-3).reduce((s,h)=>s+(h.jumlahPanen||0),0), 1) : 0;
  // S/C breeding
  const totalIB = breeding.filter(b=>b.type==="IB"||b.jenis==="IB"||b.method==="IB").length;
  const bunting = breeding.filter(b=>b.status==="Bunting"||b.hasilIB==="Bunting").length;
  const sc = totalIB>0?(totalIB/Math.max(bunting,1)).toFixed(1):"—";
  // Upcoming vaksin 7 hari
  const today = new Date(); const in7 = new Date(today); in7.setDate(today.getDate()+7);
  const upcomingVaksin = health.filter(h=>{
    if(!h.nextVaksin) return false;
    const d = new Date(h.nextVaksin);
    return d>=today && d<=in7;
  });
  // Cashflow ringkas
  const pemasukan = sales.reduce((s,t)=>s+t.totalPrice,0);
  const pengeluaran = expenses.reduce((s,e)=>s+e.amount,0) + (cattle.reduce((s,a)=>s+a.priceBuy,0));
  const cashflow = pemasukan - pengeluaran;

  // Sapi bunting mendekati lahir (< 30 hari)
  const mendekatiLahir = (breeding||[]).filter(b=>{
    if(!b.estimasiLahir&&!b.tanggalEstLahir) return false;
    const d=new Date(b.estimasiLahir||b.tanggalEstLahir); const diff=Math.round((d-today)/86400000);
    return diff>=0 && diff<=30;
  });
  const alerts = [
    ...(totalSakit>0?[{text:`🔴 ${totalSakit} hewan sakit — segera tangani!`,color:C.expense}]:[]),
    ...(lowFeed>0?[{text:`⚠️ ${lowFeed} jenis pakan stok < 7 hari`,color:C.buy}]:[]),
    ...(upcomingVaksin.length>0?[{text:`💉 ${upcomingVaksin.length} jadwal vaksin dalam 7 hari ke depan`,color:"#a855f7"}]:[]),
    ...(bf.filter(f=>f.status==="Siap Panen").length>0?[{text:`🐔 ${bf.filter(f=>f.status==="Siap Panen").length} kandang broiler SIAP PANEN — hubungi jagal/buyer!`,color:"#e879f9"}]:[]),
    ...(mendekatiLahir.length>0?[{text:`🐄 ${mendekatiLahir.length} sapi/domba mendekati kelahiran (<30 hari)`,color:"#10b981"}]:[]),
    ...(bf.filter(f=>f.mortalitas/f.jumlahAwal>0.05).length>0?[{text:`⚠️ Mortalitas tinggi (>5%) di ${bf.filter(f=>f.mortalitas/f.jumlahAwal>0.05).length} kandang broiler`,color:"#f59e0b"}]:[]),
  ];

  // Harga referensi pasar (bisa diupdate manual)
  const hargaRef = {
    sapiHidup: 52000,   // Rp/kg hidup — update sesuai kondisi pasar
    dombaPotong: 48000, // Rp/kg
    broilerHidup: 22000,// Rp/kg
    telurTray: 58000,   // Rp/tray 30 butir
    susarSegar: 7000,   // Rp/liter
  };

  return (
    <div style={S.col}>
      <AlertBar items={alerts}/>

      {/* ── KPI EKSEKUTIF — Semua Divisi ── */}
      <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:16}}>
        <div style={{color:C.info,fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          📊 KPI Eksekutif — Semua Divisi
          <span style={{fontSize:10,color:"#555a6a"}}>{new Date().toLocaleDateString("id-ID",{weekday:"long",year:"numeric",month:"long",day:"numeric"})}</span>
        </div>
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(120px,1fr))",gap:8}}>
          {[
            {l:"🐄 Sapi",v:cattle.length+" ekor",s:cattle.filter(c=>c.status==="Siap Jual").length+" siap jual",c:C.sapi,ok:cattle.filter(c=>c.health==="Sakit").length===0},
            {l:"🐑 Domba",v:sheep.length+" ekor",s:sheep.filter(d=>d.status==="Siap Jual").length+" siap jual",c:C.domba,ok:sheep.filter(d=>d.health==="Sakit").length===0},
            {l:"🐔 Broiler",v:totalBroilerEkor.toLocaleString("id-ID"),s:broilerAktif.length+" kandang · FCR "+avgIP,c:"#e879f9",ok:parseFloat(avgFCRDash||2)<=1.70},
            {l:"🥚 Layer",v:totalLayerEkor.toLocaleString("id-ID"),s:"HDP "+totalHDP+"%",c:"#f59e0b",ok:parseFloat(totalHDP)>=80},
            {l:"💰 Laba Bersih",v:rp(profitBersih),s:profitBersih>=0?"✅ Untung":"❌ Rugi",c:profitBersih>=0?C.sell:C.expense,ok:profitBersih>=0},
            {l:"🏦 Net Cashflow",v:rp(cashflow),s:cashflow>=0?"Positif":"Negatif",c:cashflow>=0?"#22c55e":"#ef4444",ok:cashflow>=0},
          ].map(({l,v,s,c,ok})=>(
            <div key={l} style={{background:c+"0c",border:"1px solid "+c+(ok?"30":"50"),borderRadius:10,padding:"10px 12px",position:"relative"}}>
              <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{l}</div>
              <div style={{fontSize:15,color:c,fontWeight:800,lineHeight:1.2}}>{v}</div>
              <div style={{fontSize:10,color:ok?"#22c55e":"#f59e0b",marginTop:2}}>{s}</div>
              <div style={{position:"absolute",top:6,right:8,fontSize:12}}>{ok?"✅":"⚠️"}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Target vs Realisasi Bulan Ini ── */}
      {(()=>{
        const bln = new Date().toISOString().slice(0,7);
        const tgts = (target||[]).filter(t=>t.bulan===bln);
        if(!tgts.length) return null;
        return (
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>🎯 Target vs Realisasi Bulan Ini</div>
            <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))",gap:8}}>
              {tgts.map(t=>{
                let aktual = 0;
                if(t.metric==="FCR Rata") aktual = parseFloat(avgFCRDash||0);
                else if(t.metric==="HDP") aktual = parseFloat(totalHDP||0);
                else if(t.metric==="Ekor Panen") aktual = bf.filter(f=>f.status==="Sudah Panen").reduce((s,f)=>s+(f.jumlahAwal||0),0);
                else if(t.metric==="Total Pendapatan") aktual = sales.reduce((s,x)=>s+(x.totalPrice||0),0);
                const pct = t.target>0 ? Math.min(120,(aktual/t.target*100)) : 0;
                const ok = t.metric==="FCR Rata" ? aktual<=t.target : aktual>=t.target*0.9;
                return (
                  <div key={t.id} style={{background:"#ffffff05",borderRadius:8,padding:10}}>
                    <div style={{display:"flex",justifyContent:"space-between",fontSize:11,marginBottom:4}}>
                      <span style={{color:"#e2e4f0",fontWeight:600}}>{t.komoditi} — {t.metric}</span>
                      <span style={{color:ok?"#22c55e":"#f59e0b",fontWeight:700,fontSize:10}}>{ok?"✓ OK":"↓ Kurang"}</span>
                    </div>
                    <div style={{height:5,background:"#252535",borderRadius:3,marginBottom:4}}>
                      <div style={{height:5,borderRadius:3,background:ok?"#22c55e":"#f59e0b",width:Math.min(100,pct)+"%",transition:"width 0.3s"}}/>
                    </div>
                    <div style={{fontSize:10,color:"#9097a8"}}>
                      Aktual: <span style={{color:ok?"#22c55e":"#f59e0b",fontWeight:700}}>{aktual}{t.satuan}</span>
                      {" "}/ Target: <span style={{color:"#555a6a"}}>{t.target}{t.satuan}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      {/* ── SDM Hadir Hari Ini ── */}
      {(()=>{
        const todayStr2 = new Date().toISOString().split("T")[0];
        const absHari = (absensi||[]).filter(a=>a.tanggal===todayStr2);
        const totalKar = (karyawan||[]).filter(k=>k.status==="Aktif").length;
        const hadir = absHari.filter(a=>a.status==="Hadir").length;
        const izin  = absHari.filter(a=>a.status==="Izin"||a.status==="Sakit").length;
        if(!totalKar) return null;
        return (
          <div style={{background:"#60a5fa08",border:"1px solid #60a5fa20",borderRadius:13,padding:14}}>
            <div style={{color:"#60a5fa",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>👥 SDM Hari Ini</div>
            <div style={{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"}}>
              <div style={{fontSize:22,color:"#22c55e",fontWeight:800}}>{hadir}<span style={{fontSize:12,color:"#555a6a",fontWeight:400}}>/{totalKar} hadir</span></div>
              {izin>0 && <div style={{background:"#f59e0b15",border:"1px solid #f59e0b25",borderRadius:8,padding:"4px 10px",fontSize:11,color:"#f59e0b"}}>{izin} izin/sakit</div>}
              {totalKar-hadir-izin>0 && <div style={{background:"#ef444415",border:"1px solid #ef444425",borderRadius:8,padding:"4px 10px",fontSize:11,color:"#ef4444"}}>{totalKar-hadir-izin} belum absen</div>}
              <div style={{marginLeft:"auto",display:"flex",gap:8,flexWrap:"wrap"}}>
                {["Pagi","Siang","Sore","Malam"].map(s=>{
                  const n=(karyawan||[]).filter(k=>k.shift===s&&k.status==="Aktif").length;
                  return n>0?<span key={s} style={{background:"#ffffff08",borderRadius:6,padding:"3px 8px",fontSize:10,color:"#9097a8"}}>{s}: {n}org</span>:null;
                })}
              </div>
            </div>
          </div>
        );
      })()}

      {/* ── Stat Grid Utama ── */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))",gap:10}}>
        <KartuStat label="🐄 Sapi" value={cattle.length+" ekor"} sub={cattle.filter(c=>c.status==="Siap Jual").length+" siap jual"} color={C.sapi} icon="sapi"/>
        <KartuStat label="🐑 Domba" value={sheep.length+" ekor"} sub={sheep.filter(d=>d.status==="Siap Jual").length+" siap jual"} color={C.domba} icon="domba"/>
        <KartuStat label="🐔 Broiler" value={totalBroilerEkor.toLocaleString("id-ID")+" ekor"} sub={broilerAktif.length+" kandang aktif"} color="#e879f9" icon="broiler"/>
        <KartuStat label="🥚 Layer" value={totalLayerEkor.toLocaleString("id-ID")+" ekor"} sub={"HDP "+totalHDP+"%"} color="#f59e0b" icon="petelur"/>
        <KartuStat label="Total Aset" value={rp(totalNilai)} sub="Estimasi pasar" color={C.info} icon="chart"/>
        <KartuStat label="Profit Bersih" value={rp(profitBersih)} sub="Penjualan−Biaya" color={profitBersih>=0?C.sell:C.expense} icon="laporan"/>
      </div>

      {/* ── KPI Unggas Row ── */}
      {(broilerAktif.length>0||layerAktif.length>0) && (
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))",gap:10}}>
          {broilerAktif.length>0 && <>
            <div style={{background:"#e879f908",border:"1px solid #e879f920",borderRadius:12,padding:14}}>
              <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>IP Broiler (Rata)</div>
              <div style={{fontSize:22,color:avgIP>=300?"#22c55e":avgIP>=250?"#f59e0b":"#ef4444",fontWeight:800}}>{avgIP.toFixed(0)}</div>
              <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>
                {avgIP>=350?"🏆 Excellent":avgIP>=300?"✅ Good":avgIP>=250?"⚠️ Average":"❌ Poor"}
                {" "}· Target ≥300
              </div>
              <div style={{fontSize:9,color:"#555a6a",marginTop:4}}>IP = BB×Liveability÷FCR÷Umur×100</div>
            </div>
            <div style={{background:"#e879f908",border:"1px solid #e879f920",borderRadius:12,padding:14}}>
              <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>FCR Rata-rata</div>
              <div style={{fontSize:22,color:broilerAktif.reduce((s,f)=>s+(parseFloat(f.fcr)||0),0)/broilerAktif.length<=1.65?"#22c55e":"#f59e0b",fontWeight:800}}>
                {(broilerAktif.reduce((s,f)=>s+(parseFloat(f.fcr)||0),0)/broilerAktif.length).toFixed(2)}
              </div>
              <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>Target ≤1.65 · Std Cobb 500</div>
            </div>
          </>}
          {layerAktif.length>0 && <>
            <div style={{background:"#f59e0b08",border:"1px solid #f59e0b20",borderRadius:12,padding:14}}>
              <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>HDP Layer</div>
              <div style={{fontSize:22,color:totalHDP>=85?"#22c55e":totalHDP>=75?"#f59e0b":"#ef4444",fontWeight:800}}>{totalHDP}%</div>
              <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>{totalHDP>=90?"🏆 Excellent":totalHDP>=85?"✅ Good":totalHDP>=75?"⚠️ Average":"❌ Poor"} · Target ≥85%</div>
            </div>
            <div style={{background:"#f59e0b08",border:"1px solid #f59e0b20",borderRadius:12,padding:14}}>
              <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>Prod. Telur/Hari</div>
              <div style={{fontSize:22,color:"#f59e0b",fontWeight:800}}>
                {layerAktif.reduce((s,f)=>s+(parseInt(f.produksiHarian||0)),0).toLocaleString("id-ID")}
              </div>
              <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>butir/hari · {layerAktif.length} kandang</div>
            </div>
          </>}
          <div style={{background:"#10b98108",border:"1px solid #10b98120",borderRadius:12,padding:14}}>
            <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>S/C Breeding</div>
            <div style={{fontSize:22,color:"#10b981",fontWeight:800}}>{sc}</div>
            <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>IB {totalIB}× → Bunting {bunting}× · Target ≤1.5</div>
          </div>
          <div style={{background:"#3b82f608",border:"1px solid #3b82f620",borderRadius:12,padding:14}}>
            <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>Harga Ref Pasar</div>
            <div style={{fontSize:10,color:"#e2e4f0",lineHeight:1.7}}>
              🐄 Sapi: {rp(hargaRef.sapiHidup)}/kg<br/>
              🐑 Domba: {rp(hargaRef.dombaPotong)}/kg<br/>
              🐔 Broiler: {rp(hargaRef.broilerHidup)}/kg<br/>
              🥚 Telur: {rp(hargaRef.telurTray)}/tray
            </div>
            <div style={{fontSize:9,color:"#555a6a",marginTop:4}}>Update harga di kode App</div>
          </div>
          <div style={{background:cashflow>=0?"#22c55e08":"#ef444408",border:"1px solid "+(cashflow>=0?"#22c55e20":"#ef444420"),borderRadius:12,padding:14}}>
            <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4}}>Net Cashflow</div>
            <div style={{fontSize:18,color:cashflow>=0?"#22c55e":"#ef4444",fontWeight:800}}>{cashflow>=0?"+":""}{rp(cashflow)}</div>
            <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>Masuk {rp(pemasukan)} · Keluar {rp(pengeluaran)}</div>
          </div>
        </div>
      )}

      {/* ── Siap Jual ── */}
      {siapJual.length>0 && (
        <div style={{background:C.sell+"08",border:"1px solid "+C.sell+"20",borderRadius:13,padding:16}}>
          <div style={{color:C.sell,fontWeight:700,fontSize:14,marginBottom:10}}>🔔 Siap Dijual ({siapJual.length} ekor)</div>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            {siapJual.map(a=>(
              <div key={a.id} style={{background:(a.type==="sapi"?C.sapi:C.domba)+"10",border:"1px solid "+(a.type==="sapi"?C.sapi:C.domba)+"22",borderRadius:9,padding:"8px 12px"}}>
                <div style={{color:C.text,fontWeight:700,fontSize:12}}>{a.name}</div>
                <div style={{color:C.muted,fontSize:11}}>{a.breed} • {a.weightCurrent}kg</div>
                <div style={{color:C.sell,fontWeight:700,fontSize:12,marginTop:2}}>{rp(nilaiEst(a))}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Broiler Siap Panen ── */}
      {bf.filter(f=>f.status==="Siap Panen").length>0 && (
        <div style={{background:"#e879f908",border:"1px solid #e879f920",borderRadius:13,padding:16}}>
          <div style={{color:"#e879f9",fontWeight:700,fontSize:14,marginBottom:10}}>🐔 Broiler Siap Panen Sekarang!</div>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            {bf.filter(f=>f.status==="Siap Panen").map(f=>(
              <div key={f.id} style={{background:"#e879f910",border:"1px solid #e879f925",borderRadius:9,padding:"8px 12px"}}>
                <div style={{color:"#e2e4f0",fontWeight:700,fontSize:12}}>{f.name}</div>
                <div style={{color:"#9097a8",fontSize:11}}>{f.jumlah} ekor · D{f.umurHari} · {f.beratRata}kg</div>
                <div style={{color:"#22c55e",fontWeight:700,fontSize:11,marginTop:2}}>
                  Est. nilai: {rp((f.jumlah||0)*(f.beratRata||2)*22000)}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Grid Status Sapi+Domba ── */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
        {[{label:"🐄 Status Sapi",data:cattle,color:C.sapi},{label:"🐑 Status Domba",data:sheep,color:C.domba}].map(({label,data,color})=>{
          const grouped=data.reduce((acc,a)=>{acc[a.status]=(acc[a.status]||0)+1;return acc;},{});
          const sColors={"Penggemukan":color,"Siap Jual":C.sell,"Breeding":C.breed,"Sakit":C.expense};
          return (
            <div key={label} style={{background:color+"07",border:"1px solid "+color+"20",borderRadius:13,padding:18}}>
              <div style={{color,fontFamily:"'DM Serif Display',serif",fontSize:14,fontWeight:700,marginBottom:12}}>{label}</div>
              {Object.entries(grouped).map(([s,n])=>(
                <div key={s} style={{...S.row,justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid "+C.border}}>
                  <Badge text={s}/>
                  <span style={{color:sColors[s]||C.muted,fontWeight:800,fontSize:16}}>{n}</span>
                </div>
              ))}
              {!Object.keys(grouped).length && <div style={{color:C.muted,fontSize:12}}>Belum ada data</div>}
            </div>
          );
        })}
      </div>

      {/* ── Kalender Vaksin 7 Hari ── */}
      {upcomingVaksin.length>0 && (
        <div style={{background:"#a855f708",border:"1px solid #a855f720",borderRadius:13,padding:16}}>
          <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:14,fontWeight:700,marginBottom:10}}>💉 Jadwal Vaksin / Kontrol 7 Hari ke Depan</div>
          <div style={{display:"flex",flexDirection:"column",gap:6}}>
            {upcomingVaksin.map((h,i)=>(
              <div key={i} style={{background:"#a855f70a",border:"1px solid #a855f718",borderRadius:8,padding:"8px 12px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                <div>
                  <div style={{color:"#e2e4f0",fontWeight:700,fontSize:12}}>{h.animalName||h.animal}</div>
                  <div style={{color:"#9097a8",fontSize:11}}>{h.treatment||h.diagnosa}</div>
                </div>
                <div style={{color:"#a855f7",fontWeight:800,fontSize:12}}>{h.nextVaksin}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Transaksi Terbaru ── */}
      <div style={{background:C.sell+"07",border:"1px solid "+C.sell+"20",borderRadius:13,padding:18}}>
        <div style={{color:C.sell,fontFamily:"'DM Serif Display',serif",fontSize:14,fontWeight:700,marginBottom:12}}>📋 Transaksi Terbaru</div>
        <TableWrap>
          <thead><tr>{["Hewan","Jenis","Pembeli","Tanggal","Total","Profit"].map(h=><TH key={h} color={C.sell}>{h}</TH>)}</tr></thead>
          <tbody>
            {sales.slice(0,5).map((s,i)=>(
              <TR key={s.id} i={i} color={C.sell}>
                <TD bold>{s.animalName}</TD>
                <td style={S.td}><Badge text={s.animalType}/></td>
                <TD color={C.muted}>{s.buyer}</TD>
                <TD color={C.dim}>{s.date}</TD>
                <TD color={C.info} bold>{rp(s.totalPrice)}</TD>
                <TD color={C.sell} bold>+{rp(s.profit)}</TD>
              </TR>
            ))}
          </tbody>
        </TableWrap>
      </div>
    </div>
  );
};

/* ===== HALAMAN: LAPORAN ===== */
const PageLaporan = ({ cattle=[], sheep=[], sales=[], feed=[], expenses=[], breeding=[], health=[], broilerFlocks=[], layerFlocks=[], broilerHarvest=[], eggProduction=[], karyawan=[], invoices=[], hutangPiutang=[], anggaran=[], proyeksi=[], target=[] }) => {
  const [tab, setTab] = React.useState("overview");
  const [bulan, setBulan] = React.useState(new Date().toISOString().slice(0,7)); // YYYY-MM

  // ── Helper ──
  const filterBulan = (arr, key="date") => arr.filter(x => (x[key]||"").startsWith(bulan));
  const allA = [...cattle, ...sheep];

  // ── OVERVIEW ──
  const totalNilaiSapi   = cattle.reduce((s,c)=>s+nilaiEst(c),0);
  const totalNilaiDomba  = sheep.reduce((s,d)=>s+nilaiEst(d),0);
  const totalModalSapi   = cattle.reduce((s,c)=>s+(c.priceBuy||0),0);
  const totalModalDomba  = sheep.reduce((s,d)=>s+(d.priceBuy||0),0);
  const totalPenjualan   = sales.reduce((s,t)=>s+(t.totalPrice||0),0);
  const totalBeliHewan   = [...cattle,...sheep].reduce((s,a)=>s+(a.priceBuy||0),0);
  const totalOps         = expenses.reduce((s,e)=>s+(e.amount||0),0);
  const totalInvoice     = (invoices||[]).reduce((s,i)=>s+(i.totalTagihan||0),0);
  const totalHutang      = (hutangPiutang||[]).filter(h=>h.tipe==="Hutang"&&!h.statusLunas).reduce((s,h)=>s+(h.jumlah||0),0);
  const totalPiutang     = (hutangPiutang||[]).filter(h=>h.tipe==="Piutang"&&!h.statusLunas).reduce((s,h)=>s+(h.jumlah||0),0);
  const totalGaji        = (karyawan||[]).filter(k=>k.status==="Aktif").reduce((s,k)=>s+(parseInt(k.gajiPokok)||0),0);

  // ── LABA RUGI ──
  const pemasukan = totalPenjualan + totalInvoice;
  const pengeluaran = totalBeliHewan + totalOps + totalGaji;
  const labaKotor  = totalPenjualan - totalBeliHewan;
  const labaBersih = pemasukan - pengeluaran;

  // ── BROILER ANALYTICS ──
  const brFlocks = broilerFlocks||[];
  const brHarvest = broilerHarvest||[];
  const brAktif = brFlocks.filter(f=>f.status==="Pembesaran"||f.status==="Siap Panen");
  const totalPanenBroiler = brHarvest.reduce((s,h)=>s+(h.totalPendapatan||0),0);
  const avgFCR = brAktif.length ? (brAktif.reduce((s,f)=>s+(parseFloat(f.fcr)||0),0)/brAktif.length).toFixed(2) : "—";
  const avgIP  = brAktif.length ? (brAktif.reduce((s,f)=>{
    const liv=(f.jumlah/Math.max(f.jumlahAwal||1,1)*100)||100;
    return s+(f.beratRata&&f.fcr&&f.umurHari?(f.beratRata*liv/f.fcr/f.umurHari*100):0);
  },0)/brAktif.length).toFixed(0) : "—";
  const totalMortBroiler = brFlocks.reduce((s,f)=>s+(f.mortalitas||0),0);
  const totalEkorBroiler = brFlocks.reduce((s,f)=>s+(f.jumlahAwal||0),0);
  const deplesiPct = totalEkorBroiler>0 ? (totalMortBroiler/totalEkorBroiler*100).toFixed(1) : 0;

  // HPP Broiler (per kg hidup)
  const hppBroiler = brHarvest.length ? brHarvest.map(h=>{
    const biayaDOC = (h.jumlahAwal||h.jumlahPanen||1)*(h.hargaDOC||7500);
    const biayaPakan = (h.totalBerat||0)*4500; // estimasi pakan 4.500/kg
    const biayaOps   = (h.jumlahAwal||1)*3000; // estimasi ops 3.000/ekor
    const hpp = ((biayaDOC+biayaPakan+biayaOps)/Math.max(h.totalBerat||1,1));
    return {periode:h.name||h.id, hpp:hpp.toFixed(0), pendapatan:h.totalPendapatan||0, ekor:h.jumlahPanen||0, berat:h.totalBerat||0};
  }) : [];

  // BEP Broiler
  const biayaTetap = totalGaji + expenses.filter(e=>['Peralatan','Kandang','Listrik'].some(k=>e.category?.includes(k))).reduce((s,e)=>s+(e.amount||0),0);
  const biayaVarPerKg = 16500; // DOC+pakan+ops per kg standar
  const bepHarga = biayaVarPerKg + (biayaTetap/(totalEkorBroiler*2||1));
  const bepEkor  = biayaTetap / Math.max(22000 - biayaVarPerKg, 1);

  // ── LAYER ANALYTICS ──
  const lyFlocks = layerFlocks||[];
  const lyAktif = lyFlocks.filter(f=>f.status==="Produksi");
  const totalTelur = (eggProduction||[]).reduce((s,e)=>s+(e.produksiHarian||0),0);
  const totalPendTelur = (eggProduction||[]).reduce((s,e)=>s+(e.totalPendapatan||0),0);
  const avgHDP = lyAktif.length ? (lyAktif.reduce((s,f)=>s+(parseFloat(f.produksiHarian||0)/Math.max(f.jumlah,1)*100),0)/lyAktif.length).toFixed(1) : 0;

  // HPP Telur (per butir)
  const totalLayerEkor = lyFlocks.reduce((s,f)=>s+(f.jumlah||0),0);
  const biayaPakanLayer = totalLayerEkor * 110 * 7000; // 110g/hr × harga layer 7000/kg
  const hppTelur = totalTelur > 0 ? ((biayaPakanLayer + totalGaji*0.3) / totalTelur).toFixed(0) : 0;

  // ── SAPI/DOMBA ANALYTICS ──
  const sapiPenggemukan = cattle.filter(c=>c.status==="Penggemukan");
  const avgADGSapi = sapiPenggemukan.length ? (sapiPenggemukan.reduce((s,c)=>{
    const hari = c.age||90;
    return s + ((c.weightCurrent-c.weightBuy)/Math.max(hari,1));
  },0)/sapiPenggemukan.length*1000).toFixed(0) : 0;
  const roiSapi = totalModalSapi > 0 ? ((totalNilaiSapi-totalModalSapi)/totalModalSapi*100).toFixed(1) : 0;

  // ── REKAP BULANAN ──
  const salesBulan    = filterBulan(sales);
  const expBulan      = filterBulan(expenses);
  const pemasukanBulan = salesBulan.reduce((s,t)=>s+(t.totalPrice||0),0);
  const pengeluaranBulan = expBulan.reduce((s,e)=>s+(e.amount||0),0);
  const labaBulan = pemasukanBulan - pengeluaranBulan;

  // ── PAYBACK PERIOD ──
  const investasiAwal = totalBeliHewan + expenses.filter(e=>e.category==="Kandang"||e.category==="Peralatan").reduce((s,e)=>s+(e.amount||0),0);
  const netProfitPerBulan = labaBersih / 12 || 1;
  const paybackBulan = investasiAwal > 0 ? Math.ceil(investasiAwal / Math.max(netProfitPerBulan,1)) : 0;

  const tabList = [
    {id:"overview",  l:"📊 Overview"},
    {id:"proyeksi",  l:"📈 Proyeksi & Budget"},
    {id:"labaugi",   l:"💰 Laba Rugi"},
    {id:"broiler",   l:"🐔 Broiler"},
    {id:"layer",     l:"🥚 Layer"},
    {id:"sapi",      l:"🐄 Sapi & Domba"},
    {id:"bulanan",   l:"📅 Rekap Bulanan"},
    {id:"keuangan",  l:"🏦 Keuangan"},
  ];

  const AC = C.report;

  // ── PRINT FUNCTION ──
  const handlePrint = () => {
    const el = document.getElementById("laporan-print-area");
    const w = window.open("","_blank");
    w.document.write(`<html><head><title>Laporan TernakPro</title>
      <style>body{font-family:Arial,sans-serif;padding:20px;color:#000}
      table{width:100%;border-collapse:collapse;margin:10px 0}
      th,td{border:1px solid #ccc;padding:6px 8px;text-align:left;font-size:12px}
      th{background:#f0f0f0;font-weight:bold}
      h2{color:#333;border-bottom:2px solid #333;padding-bottom:5px}
      .stat{display:inline-block;margin:8px;padding:10px 16px;background:#f8f8f8;border:1px solid #ddd;border-radius:6px;min-width:150px}
      .stat-val{font-size:20px;font-weight:bold;color:#1a1a1a}
      .stat-lbl{font-size:11px;color:#666;margin-top:2px}
      @media print{.no-print{display:none}}</style>
    </head><body>${el.innerHTML}</body></html>`);
    w.document.close(); w.focus(); w.print();
  };

  // ── JSON EXPORT ──
  const handleExport = () => {
    const data = {
      exported: new Date().toISOString(), app:"TernakPro",
      cattle, sheep, sales, expenses, breeding, health,
      broilerFlocks, layerFlocks, broilerHarvest, eggProduction,
      karyawan, invoices, hutangPiutang,
    };
    const blob = new Blob([JSON.stringify(data,null,2)],{type:"application/json"});
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `ternakpro-backup-${new Date().toISOString().slice(0,10)}.json`;
    a.click();
  };

  const statCard = (label, value, sub, color="#60a5fa") => (
    <div key={label} style={{background:color+"0d",border:"1px solid "+color+"25",borderRadius:12,padding:"14px 18px",minWidth:130}}>
      <div style={{fontSize:9,color:"#555a6a",fontWeight:800,textTransform:"uppercase",marginBottom:4,letterSpacing:0.8}}>{label}</div>
      <div style={{fontSize:18,color,fontWeight:800,lineHeight:1.2}}>{value}</div>
      {sub&&<div style={{fontSize:10,color:"#9097a8",marginTop:3}}>{sub}</div>}
    </div>
  );

  return (
    <div style={S.col}>
      {/* Header actions */}
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:8}}>
        <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
          {tabList.map(t=>(
            <button key={t.id} onClick={()=>setTab(t.id)}
              style={{background:tab===t.id?AC+"18":"#0f1118",border:"1px solid "+(tab===t.id?AC+"50":C.border),
                borderRadius:9,padding:"7px 14px",cursor:"pointer",color:tab===t.id?AC:C.muted,fontWeight:700,fontSize:12}}>
              {t.l}
            </button>
          ))}
        </div>
        <div style={{display:"flex",gap:8}}>
          <BtnSec onClick={handleExport} color="#22c55e">💾 Backup JSON</BtnSec>
          <BtnSec onClick={handlePrint}  color="#60a5fa">🖨️ Print / PDF</BtnSec>
        </div>
      </div>

      <div id="laporan-print-area">

      {/* ══ TAB OVERVIEW ══ */}
      {tab==="overview" && (
        <div style={S.col}>
          <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:16,marginBottom:4}}>📊 Ringkasan Usaha Peternakan</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Total Sapi",cattle.length+" ekor","Nilai "+rp(totalNilaiSapi),C.sapi)}
            {statCard("Total Domba",sheep.length+" ekor","Nilai "+rp(totalNilaiDomba),C.domba)}
            {statCard("Broiler Aktif",brAktif.length+" kandang","FCR "+avgFCR,"#e879f9")}
            {statCard("Layer Aktif",lyAktif.length+" kandang","HDP "+avgHDP+"%","#f59e0b")}
            {statCard("Total Penjualan",rp(totalPenjualan),sales.length+" transaksi",C.sell)}
            {statCard("Laba Bersih",rp(labaBersih),labaBersih>=0?"✅ Untung":"❌ Rugi",labaBersih>=0?"#22c55e":"#ef4444")}
            {statCard("Total Hutang",rp(totalHutang),hutangPiutang.filter(h=>h.tipe==="Hutang"&&!h.statusLunas).length+" item","#ef4444")}
            {statCard("Total Piutang",rp(totalPiutang),hutangPiutang.filter(h=>h.tipe==="Piutang"&&!h.statusLunas).length+" item","#f97316")}
            {statCard("Payback Period",paybackBulan+" bulan","Modal "+rp(investasiAwal),"#a855f7")}
            {statCard("ROI Sapi",roiSapi+"%","Nilai vs Modal",parseFloat(roiSapi)>0?"#22c55e":"#ef4444")}
          </div>

          {/* Tabel Neraca Singkat */}
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
              <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:10}}>📈 PEMASUKAN</div>
              {[["Penjualan Ternak",rp(totalPenjualan)],
                ["Invoice Terbayar",rp(invoices.filter(i=>i.statusBayar==="Lunas").reduce((s,i)=>s+(i.totalTagihan||0),0))],
                ["Nilai Aset Ternak",rp(totalNilaiSapi+totalNilaiDomba)],
              ].map(([k,v])=>(
                <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid #1c1e2b",fontSize:12}}>
                  <span style={{color:"#9097a8"}}>{k}</span>
                  <span style={{color:"#22c55e",fontWeight:700}}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
              <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:10}}>📉 PENGELUARAN</div>
              {[["Beli Hewan",rp(totalBeliHewan)],
                ["Operasional",rp(totalOps)],
                ["Gaji Karyawan",rp(totalGaji*12)+" /thn"],
                ["Hutang Aktif",rp(totalHutang)],
              ].map(([k,v])=>(
                <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid #1c1e2b",fontSize:12}}>
                  <span style={{color:"#9097a8"}}>{k}</span>
                  <span style={{color:"#ef4444",fontWeight:700}}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ══ TAB LABA RUGI ══ */}
      {tab==="labaugi" && (
        <div style={S.col}>
          <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:16}}>💰 Laporan Laba Rugi</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(150px,1fr))",gap:10}}>
            {statCard("Gross Revenue",rp(pemasukan),"Total pemasukan","#22c55e")}
            {statCard("Laba Kotor",rp(labaKotor),"Jual − Beli hewan",labaKotor>=0?"#22c55e":"#ef4444")}
            {statCard("Total Biaya",rp(pengeluaran),"Semua pengeluaran","#ef4444")}
            {statCard("Laba Bersih",rp(labaBersih),"Revenue − Biaya",labaBersih>=0?"#22c55e":"#ef4444")}
            {statCard("Margin %",(pemasukan>0?(labaBersih/pemasukan*100).toFixed(1):0)+"%","Net profit margin",labaBersih>=0?"#22c55e":"#ef4444")}
            {statCard("Payback",paybackBulan+" bulan","Balik modal","#a855f7")}
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:12}}>📋 Rincian Laba Rugi</div>
            {[
              {label:"PENDAPATAN",items:[
                ["Penjualan Hewan",rp(totalPenjualan),"#22c55e"],
                ["Invoice Tertagih",rp(invoices.filter(i=>i.statusBayar==="Lunas").reduce((s,i)=>s+i.totalTagihan,0)),"#22c55e"],
                ["Panen Broiler",rp(totalPanenBroiler),"#22c55e"],
                ["Penjualan Telur",rp(totalPendTelur),"#22c55e"],
              ]},
              {label:"PENGELUARAN",items:[
                ["Pembelian Hewan",rp(totalBeliHewan),"#ef4444"],
                ["Biaya Operasional",rp(totalOps),"#ef4444"],
                ["Gaji Karyawan/Bln",rp(totalGaji),"#ef4444"],
                ["Pakan (estimasi)",rp(Math.round(feed.reduce((s,f)=>s+(f.stock||0)*(f.price||0),0))),"#ef4444"],
              ]},
            ].map(grp=>(
              <div key={grp.label} style={{marginBottom:12}}>
                <div style={{color:"#555a6a",fontWeight:800,fontSize:10,textTransform:"uppercase",letterSpacing:1,marginBottom:6}}>{grp.label}</div>
                {grp.items.map(([k,v,c])=>(
                  <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"7px 0",borderBottom:"1px solid #1c1e2b",fontSize:12}}>
                    <span style={{color:"#9097a8"}}>{k}</span>
                    <span style={{color:c,fontWeight:700}}>{v}</span>
                  </div>
                ))}
              </div>
            ))}
            <div style={{display:"flex",justifyContent:"space-between",padding:"10px 0",borderTop:"2px solid "+AC+"30",fontSize:14}}>
              <span style={{color:AC,fontWeight:800}}>LABA / RUGI BERSIH</span>
              <span style={{color:labaBersih>=0?"#22c55e":"#ef4444",fontWeight:800,fontSize:16}}>{rp(labaBersih)}</span>
            </div>
          </div>
        </div>
      )}

      {/* ══ TAB BROILER ══ */}
      {tab==="broiler" && (
        <div style={S.col}>
          <div style={{color:"#e879f9",fontFamily:"'DM Serif Display',serif",fontSize:16}}>🐔 Analitik Broiler</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Kandang Aktif",brAktif.length+" kandang","","#e879f9")}
            {statCard("Total Ekor",brFlocks.reduce((s,f)=>s+(f.jumlah||0),0).toLocaleString("id-ID"),"populasi aktif","#e879f9")}
            {statCard("FCR Rata",avgFCR,"target ≤1.65",parseFloat(avgFCR)<=1.65?"#22c55e":"#f59e0b")}
            {statCard("IP Rata",avgIP,"target ≥300",parseInt(avgIP)>=300?"#22c55e":parseInt(avgIP)>=250?"#f59e0b":"#ef4444")}
            {statCard("Deplesi %",deplesiPct+"%","target <5%",parseFloat(deplesiPct)<5?"#22c55e":"#ef4444")}
            {statCard("Total Panen",rp(totalPanenBroiler),brHarvest.length+" siklus","#22c55e")}
          </div>
          {/* BEP Broiler */}
          <div style={{background:"#e879f908",border:"1px solid #e879f920",borderRadius:13,padding:16}}>
            <div style={{color:"#e879f9",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:10}}>📐 BEP & HPP Broiler</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10}}>
              {[
                ["HPP /kg (estimasi)",rp(Math.round(biayaVarPerKg+biayaTetap/(totalEkorBroiler*2||1))),"Biaya produksi per kg hidup"],
                ["BEP Harga Jual",rp(Math.round(bepHarga)),"Harga jual minimal balik modal"],
                ["BEP Volume",Math.round(bepEkor)+" ekor/siklus","Jumlah panen minimal BEP"],
              ].map(([k,v,s])=>(
                <div key={k} style={{background:"#e879f90a",border:"1px solid #e879f918",borderRadius:9,padding:12}}>
                  <div style={{fontSize:9,color:"#9097a8",fontWeight:700,textTransform:"uppercase",marginBottom:4}}>{k}</div>
                  <div style={{color:"#e879f9",fontWeight:800,fontSize:16}}>{v}</div>
                  <div style={{color:"#555a6a",fontSize:10,marginTop:3}}>{s}</div>
                </div>
              ))}
            </div>
          </div>
          {/* Tabel HPP per siklus */}
          {hppBroiler.length > 0 && (
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
              <div style={{color:"#e879f9",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>📋 HPP Per Siklus Panen</div>
              <TableWrap>
                <thead><tr>{["Periode","Ekor Panen","Total Kg","HPP/kg","Pendapatan","IOFC"].map(h=><TH key={h} color="#e879f9">{h}</TH>)}</tr></thead>
                <tbody>
                  {hppBroiler.map((h,i)=>{
                    const iofc = h.pendapatan - (h.berat*4500);
                    return (
                      <TR key={h.periode} i={i} color="#e879f9">
                        <TD bold>{h.periode}</TD>
                        <TD color={C.muted}>{h.ekor}</TD>
                        <TD color={C.muted}>{h.berat} kg</TD>
                        <TD color={parseInt(h.hpp)<20000?"#22c55e":"#f59e0b"} bold>{rp(parseInt(h.hpp))}</TD>
                        <TD color="#22c55e" bold>{rp(h.pendapatan)}</TD>
                        <TD color={iofc>0?"#22c55e":"#ef4444"} bold>{rp(iofc)}</TD>
                      </TR>
                    );
                  })}
                </tbody>
              </TableWrap>
            </div>
          )}
          {/* Tabel semua kandang */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#e879f9",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>📋 Performa Semua Kandang</div>
            <TableWrap>
              <thead><tr>{["Kandang","Strain","Ekor","Umur","BB","FCR","IP","Deplesi%","Status"].map(h=><TH key={h} color="#e879f9">{h}</TH>)}</tr></thead>
              <tbody>
                {brFlocks.map((f,i)=>{
                  const liv=(f.jumlah/Math.max(f.jumlahAwal||1,1)*100)||100;
                  const ip=f.beratRata&&f.fcr&&f.umurHari?(f.beratRata*liv/f.fcr/f.umurHari*100).toFixed(0):"—";
                  const depl=((f.mortalitas||0)/(f.jumlahAwal||1)*100).toFixed(1);
                  return (
                    <TR key={f.id} i={i} color="#e879f9">
                      <TD bold>{f.name}</TD>
                      <TD color={C.muted}>{f.breed}</TD>
                      <TD color={C.muted}>{f.jumlah}</TD>
                      <TD color={C.muted}>D{f.umurHari}</TD>
                      <TD color={C.muted}>{f.beratRata}kg</TD>
                      <TD color={parseFloat(f.fcr)<=1.65?"#22c55e":"#f59e0b"} bold>{f.fcr||"—"}</TD>
                      <TD color={parseInt(ip)>=300?"#22c55e":parseInt(ip)>=250?"#f59e0b":"#ef4444"} bold>{ip}</TD>
                      <TD color={parseFloat(depl)<5?"#22c55e":"#ef4444"} bold>{depl}%</TD>
                      <td style={S.td}><Badge text={f.status}/></td>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      {/* ══ TAB LAYER ══ */}
      {tab==="layer" && (
        <div style={S.col}>
          <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:16}}>🥚 Analitik Layer</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Kandang Aktif",lyAktif.length,"","#f59e0b")}
            {statCard("Total Ekor",totalLayerEkor.toLocaleString("id-ID"),"","#f59e0b")}
            {statCard("HDP Rata",avgHDP+"%","target ≥85%",parseFloat(avgHDP)>=85?"#22c55e":"#f59e0b")}
            {statCard("Total Telur",(totalTelur).toLocaleString("id-ID")+" butir","","#f59e0b")}
            {statCard("Pendapatan Telur",rp(totalPendTelur),"","#22c55e")}
            {statCard("HPP/Butir",rp(parseInt(hppTelur)),"target <Rp1.500","#f59e0b")}
          </div>
          {/* Layer table */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>📋 Performa Semua Kandang Layer</div>
            <TableWrap>
              <thead><tr>{["Kandang","Strain","Ekor","Umur Mgg","HDP%","Prod/Hari","FCR","Status"].map(h=><TH key={h} color="#f59e0b">{h}</TH>)}</tr></thead>
              <tbody>
                {lyFlocks.map((f,i)=>{
                  const hdp = f.produksiHarian&&f.jumlah ? (f.produksiHarian/f.jumlah*100).toFixed(1) : 0;
                  return (
                    <TR key={f.id} i={i} color="#f59e0b">
                      <TD bold>{f.name}</TD>
                      <TD color={C.muted}>{f.breed}</TD>
                      <TD color={C.muted}>{f.jumlah}</TD>
                      <TD color={C.muted}>{f.umurMinggu||"—"}</TD>
                      <TD color={parseFloat(hdp)>=85?"#22c55e":"#f59e0b"} bold>{hdp}%</TD>
                      <TD color={C.muted}>{f.produksiHarian||0} butir</TD>
                      <TD color={C.muted}>{f.fcr||"—"}</TD>
                      <td style={S.td}><Badge text={f.status}/></td>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      {/* ══ TAB SAPI & DOMBA ══ */}
      {tab==="sapi" && (
        <div style={S.col}>
          <div style={{color:C.sapi,fontFamily:"'DM Serif Display',serif",fontSize:16}}>🐄 Analitik Sapi & Domba</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Total Sapi",cattle.length+" ekor","Modal "+rp(totalModalSapi),C.sapi)}
            {statCard("Nilai Sapi",rp(totalNilaiSapi),"Estimasi pasar",C.sapi)}
            {statCard("ROI Sapi",roiSapi+"%","Nilai vs Modal",parseFloat(roiSapi)>0?"#22c55e":"#ef4444")}
            {statCard("ADG Rata",avgADGSapi+" g/hari","Penggemukan",parseFloat(avgADGSapi)>=700?"#22c55e":"#f59e0b")}
            {statCard("Total Domba",sheep.length+" ekor","Modal "+rp(totalModalDomba),C.domba)}
            {statCard("Nilai Domba",rp(totalNilaiDomba),"Estimasi pasar",C.domba)}
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:C.sapi,fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>📋 Detail Sapi — ADG & Nilai</div>
            <TableWrap>
              <thead><tr>{["Nama","Ras","Beli","BB Beli","BB Kini","ADG g/hr","Nilai Est","Status","Keuntungan"].map(h=><TH key={h} color={C.sapi}>{h}</TH>)}</tr></thead>
              <tbody>
                {cattle.map((c,i)=>{
                  const adg = c.age>0 ? Math.round((c.weightCurrent-c.weightBuy)/c.age*1000) : 0;
                  const nilai = nilaiEst(c);
                  const untung = nilai - c.priceBuy;
                  return (
                    <TR key={c.id} i={i} color={C.sapi}>
                      <TD bold>{c.name}</TD>
                      <TD color={C.muted}>{c.breed}</TD>
                      <TD color={C.dim}>{c.buyDate}</TD>
                      <TD color={C.muted}>{c.weightBuy}kg</TD>
                      <TD color={C.muted}>{c.weightCurrent}kg</TD>
                      <TD color={adg>=700?"#22c55e":"#f59e0b"} bold>{adg}</TD>
                      <TD color={C.sapi} bold>{rp(nilai)}</TD>
                      <td style={S.td}><Badge text={c.status}/></td>
                      <TD color={untung>=0?"#22c55e":"#ef4444"} bold>{rp(untung)}</TD>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      {/* ══ TAB REKAP BULANAN ══ */}
      {tab==="bulanan" && (
        <div style={S.col}>
          <div style={{display:"flex",gap:10,alignItems:"center"}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:16}}>📅 Rekap Bulanan</div>
            <input type="month" value={bulan} onChange={e=>setBulan(e.target.value)}
              style={{background:"#13161f",border:"1px solid "+AC+"40",borderRadius:8,padding:"6px 10px",color:AC,fontSize:12}}/>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Pemasukan",rp(pemasukanBulan),salesBulan.length+" transaksi","#22c55e")}
            {statCard("Pengeluaran",rp(pengeluaranBulan),expBulan.length+" item","#ef4444")}
            {statCard("Net Bulan Ini",rp(labaBulan),labaBulan>=0?"Untung":"Rugi",labaBulan>=0?"#22c55e":"#ef4444")}
            {statCard("Transaksi",salesBulan.length+" jual","","#60a5fa")}
          </div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
              <div style={{color:"#22c55e",fontWeight:700,marginBottom:8,fontSize:13}}>📈 Penjualan Bulan {bulan}</div>
              {salesBulan.length===0 ? <Empty/> :
                <TableWrap><thead><tr>{["Hewan","Pembeli","Total","Profit"].map(h=><TH key={h} color="#22c55e">{h}</TH>)}</tr></thead>
                <tbody>{salesBulan.map((s,i)=><TR key={s.id} i={i} color="#22c55e"><TD bold>{s.animalName}</TD><TD color={C.muted}>{s.buyer}</TD><TD color="#22c55e">{rp(s.totalPrice)}</TD><TD color="#22c55e">{rp(s.profit)}</TD></TR>)}</tbody></TableWrap>}
            </div>
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:14}}>
              <div style={{color:"#ef4444",fontWeight:700,marginBottom:8,fontSize:13}}>📉 Pengeluaran Bulan {bulan}</div>
              {expBulan.length===0 ? <Empty/> :
                <TableWrap><thead><tr>{["Kategori","Keterangan","Jumlah"].map(h=><TH key={h} color="#ef4444">{h}</TH>)}</tr></thead>
                <tbody>{expBulan.map((e,i)=><TR key={e.id} i={i} color="#ef4444"><TD color={C.muted}>{e.category}</TD><TD bold>{e.description}</TD><TD color="#ef4444">{rp(e.amount)}</TD></TR>)}</tbody></TableWrap>}
            </div>
          </div>
        </div>
      )}

      {/* ══ TAB KEUANGAN ══ */}
      {tab==="keuangan" && (
        <div style={S.col}>
          <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:16}}>🏦 Laporan Keuangan</div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:10}}>
            {statCard("Total Invoice",rp(invoices.reduce((s,i)=>s+(i.totalTagihan||0),0)),invoices.length+" nota","#f59e0b")}
            {statCard("Sudah Lunas",rp(invoices.filter(i=>i.statusBayar==="Lunas").reduce((s,i)=>s+(i.totalTagihan||0),0)),"","#22c55e")}
            {statCard("Belum Lunas",rp(invoices.filter(i=>i.statusBayar!=="Lunas").reduce((s,i)=>s+(i.totalTagihan||0),0)),"","#f59e0b")}
            {statCard("Total Hutang",rp(totalHutang),"Belum dibayar","#ef4444")}
            {statCard("Total Piutang",rp(totalPiutang),"Belum diterima","#f97316")}
            {statCard("Gaji/Bulan",rp(totalGaji),(karyawan||[]).filter(k=>k.status==="Aktif").length+" aktif","#60a5fa")}
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>📋 Hutang & Piutang Aktif</div>
            <TableWrap>
              <thead><tr>{["Tipe","Pihak","Keperluan","Jumlah","Jatuh Tempo","Status"].map(h=><TH key={h} color="#f59e0b">{h}</TH>)}</tr></thead>
              <tbody>
                {(hutangPiutang||[]).filter(h=>!h.statusLunas).map((h,i)=>{
                  const overdue = h.jatuhTempo&&new Date(h.jatuhTempo)<new Date();
                  return (
                    <TR key={h.id} i={i} color="#f59e0b">
                      <td style={S.td}><Badge text={h.tipe}/></td>
                      <TD bold>{h.pihak}</TD>
                      <TD color={C.muted}>{h.keperluan?.substring(0,40)}</TD>
                      <TD color={h.tipe==="Hutang"?"#ef4444":"#f97316"} bold>{rp(h.jumlah)}</TD>
                      <TD color={overdue?"#ef4444":C.muted}>{h.jatuhTempo||"—"}{overdue?" ⚠️":""}</TD>
                      <td style={S.td}><Badge text={overdue?"JATUH TEMPO":"Aktif"}/></td>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      {/* ══ TAB PROYEKSI & BUDGET ══ */}
      {tab==="proyeksi" && (
        <div style={S.col}>
          <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:16}}>📈 Proyeksi & Anggaran vs Realisasi</div>

          {/* Proyeksi 3 bulan */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:12}}>📊 Proyeksi Pendapatan 3 Bulan ke Depan</div>
            <TableWrap>
              <thead><tr>{["Bulan","Pemasukan Proyeksi","Pengeluaran Proyeksi","Laba Proyeksi","Margin %","Catatan"].map(h=><TH key={h} color="#a855f7">{h}</TH>)}</tr></thead>
              <tbody>
                {(proyeksi||[]).map((p,i)=>{
                  const margin = p.pemasukanProyeksi > 0 ? (p.labaProyeksi/p.pemasukanProyeksi*100).toFixed(1) : 0;
                  return (
                    <TR key={p.bulan} i={i} color="#a855f7">
                      <TD bold color="#a855f7">{p.bulan}</TD>
                      <TD color="#22c55e" bold>{rp(p.pemasukanProyeksi)}</TD>
                      <TD color="#ef4444">{rp(p.pengeluaranProyeksi)}</TD>
                      <TD color={p.labaProyeksi>=0?"#22c55e":"#ef4444"} bold>{rp(p.labaProyeksi)}</TD>
                      <TD color={parseFloat(margin)>=20?"#22c55e":"#f59e0b"}>{margin}%</TD>
                      <TD color={C.muted}>{p.catatan}</TD>
                    </TR>
                  );
                })}
                <TR i={99} color="#a855f7">
                  <TD bold color="#a855f7">TOTAL 3 BULAN</TD>
                  <TD color="#22c55e" bold>{rp((proyeksi||[]).reduce((s,p)=>s+p.pemasukanProyeksi,0))}</TD>
                  <TD color="#ef4444">{rp((proyeksi||[]).reduce((s,p)=>s+p.pengeluaranProyeksi,0))}</TD>
                  <TD color="#22c55e" bold>{rp((proyeksi||[]).reduce((s,p)=>s+p.labaProyeksi,0))}</TD>
                  <td colSpan={2}/>
                </TR>
              </tbody>
            </TableWrap>
          </div>

          {/* Anggaran vs Realisasi */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:12}}>💰 Anggaran vs Realisasi Biaya</div>
            <TableWrap>
              <thead><tr>{["Bulan","Kategori","Anggaran","Realisasi","Selisih","Status","Keterangan"].map(h=><TH key={h} color="#f59e0b">{h}</TH>)}</tr></thead>
              <tbody>
                {(anggaran||[]).map((a,i)=>{
                  const selisih = a.anggaran - a.realisasi;
                  const over = selisih < 0;
                  const pct = a.anggaran>0?(a.realisasi/a.anggaran*100).toFixed(0):0;
                  return (
                    <TR key={a.id} i={i} color="#f59e0b">
                      <TD color={C.dim}>{a.bulan}</TD>
                      <td style={S.td}><Badge text={a.kategori}/></td>
                      <TD color={C.muted}>{rp(a.anggaran)}</TD>
                      <TD color={over?"#ef4444":"#22c55e"} bold>{rp(a.realisasi)}</TD>
                      <TD color={over?"#ef4444":"#22c55e"} bold>{over?"-":"+"}{ rp(Math.abs(selisih))}</TD>
                      <td style={S.td}><Badge text={over?"OVER BUDGET":pct<=80?"UNDER":"Normal"}/></td>
                      <TD color={C.muted}>{a.ket}</TD>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>

          {/* Target bulan ini */}
          {(target||[]).length > 0 && (
            <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
              <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:12}}>🎯 Target Produksi Bulan Ini</div>
              <TableWrap>
                <thead><tr>{["Bulan","Komoditi","Metric","Target","Satuan","Keterangan"].map(h=><TH key={h} color="#22c55e">{h}</TH>)}</tr></thead>
                <tbody>
                  {(target||[]).map((t,i)=>(
                    <TR key={t.id} i={i} color="#22c55e">
                      <TD color={C.dim}>{t.bulan}</TD>
                      <td style={S.td}><Badge text={t.komoditi}/></td>
                      <TD bold>{t.metric}</TD>
                      <TD color="#22c55e" bold>{t.target.toLocaleString("id-ID")}</TD>
                      <TD color={C.muted}>{t.satuan||"—"}</TD>
                      <TD color={C.muted}>{t.catatan}</TD>
                    </TR>
                  ))}
                </tbody>
              </TableWrap>
            </div>
          )}
        </div>
      )}

      </div>{/* end print area */}
    </div>
  );
};



/* ================================================================
   DATA AWAL — Layer Flocks, Broiler Flocks, Egg Production, Harvests
================================================================ */
const initialLayerFlocks = [
  {id:"LF001",name:"Kandang A Layer - Periode 8",type:"petelur",breed:"Lohmann Brown",jumlah:3000,jumlahAwal:3050,umurMinggu:42,tglMasuk:"2025-08-01",produksiHarian:2730,targetProduksi:2700,hargaDOC:9500,biayaDoc:28975000,beratRata:1.82,status:"Produksi",health:"Sehat",pakan:"EH-711 Japfa",pakanPerhari:330,kandang:"A",supplier:"PT Japfa Comfeed",vaksin:"Lengkap",mortalitas:50,fcr:2.12,notes:"HDP 91% excellent"},
  {id:"LF002",name:"Kandang B Layer - Periode 7",type:"petelur",breed:"ISA Brown",jumlah:2500,jumlahAwal:2550,umurMinggu:55,tglMasuk:"2025-05-15",produksiHarian:2100,targetProduksi:2250,hargaDOC:9200,biayaDoc:23460000,beratRata:1.78,status:"Produksi",health:"Sehat",pakan:"CP-526 Mash",pakanPerhari:275,kandang:"B",supplier:"PT Charoen Pokphand",vaksin:"Lengkap",mortalitas:50,fcr:2.20,notes:"HDP 84% mulai turun — cek Ca"},
  {id:"LF003",name:"Kandang C Layer - Afkir",type:"petelur",breed:"Lohmann Brown",jumlah:2200,jumlahAwal:2400,umurMinggu:80,tglMasuk:"2024-11-01",produksiHarian:1540,targetProduksi:1800,hargaDOC:9000,biayaDoc:21600000,beratRata:1.90,status:"Afkir",health:"Sehat",pakan:"CP-526L",pakanPerhari:242,kandang:"C",supplier:"PT Malindo",vaksin:"Lengkap",mortalitas:200,fcr:2.45,notes:"Sudah 80 mgg, siap afkir ke RPH"},
];

const initialEggProduction = [
  {id:"EP001",flockId:"LF001",flockName:"Kandang A",date:"2026-06-05",produksi:2730,reject:45,netto:2685,hargaPerBiji:1850,totalPendapatan:4967250,buyer:"Pengepul Bu Haji",notes:""},
  {id:"EP002",flockId:"LF002",flockName:"Kandang B",date:"2026-06-05",produksi:2100,reject:38,netto:2062,hargaPerBiji:1850,totalPendapatan:3814700,buyer:"Pengepul Bu Haji",notes:"HDP turun"},
  {id:"EP003",flockId:"LF001",flockName:"Kandang A",date:"2026-06-04",produksi:2755,reject:40,netto:2715,hargaPerBiji:1850,totalPendapatan:5022750,buyer:"Pengepul Bu Haji",notes:""},
  {id:"EP004",flockId:"LF002",flockName:"Kandang B",date:"2026-06-04",produksi:2150,reject:30,netto:2120,hargaPerBiji:1850,totalPendapatan:3922000,buyer:"CV Telur Nusantara",notes:""},
  {id:"EP005",flockId:"LF001",flockName:"Kandang A",date:"2026-06-03",produksi:2710,reject:55,netto:2655,hargaPerBiji:1800,totalPendapatan:4779000,buyer:"Pengepul Bu Haji",notes:"Reject tinggi — cek pakan"},
  {id:"EP006",flockId:"LF003",flockName:"Kandang C",date:"2026-06-05",produksi:1540,reject:60,netto:1480,hargaPerBiji:1800,totalPendapatan:2664000,buyer:"Pasar Cikurubuk",notes:"Afkir — HDP rendah 70%"},
];

const initialBroilerFlocks = [
  {id:"BR001",name:"Kandang D - Periode 14",type:"broiler",breed:"Cobb 500",jumlah:2000,jumlahAwal:2050,umurHari:21,tglMasuk:"2026-05-15",beratRata:1.45,targetBerat:2.0,hargaDOC:7500,biayaDoc:15375000,status:"Pembesaran",health:"Sehat",pakan:"Broiler Starter BR-1",pakanPerhari:280,kandang:"D",supplier:"PT Charoen Pokphand",vaksin:"Lengkap",fcr:1.62,mortalitas:50,tglPanen:"2026-06-18",notes:"D21 selesai. Besok ganti Finisher BR-2. FCR 1.62 sangat bagus"},
  {id:"BR002",name:"Kandang E - Periode 13",type:"broiler",breed:"Ross 308",jumlah:1850,jumlahAwal:1900,umurHari:35,tglMasuk:"2026-04-30",beratRata:1.95,targetBerat:2.0,hargaDOC:7800,biayaDoc:14820000,status:"Siap Panen",health:"Sehat",pakan:"Broiler Finisher BR-2",pakanPerhari:296,kandang:"E",supplier:"PT Malindo Feedmill",vaksin:"Lengkap",fcr:1.70,mortalitas:50,tglPanen:"2026-06-05",notes:"D35 siap panen. Hubungi jagal hari ini!"},
  {id:"BR003",name:"Kandang F - Periode 12",type:"broiler",breed:"Cobb 500",jumlah:0,jumlahAwal:2200,umurHari:42,tglMasuk:"2026-03-20",beratRata:2.35,targetBerat:2.0,hargaDOC:7200,biayaDoc:15840000,status:"Sudah Panen",health:"Sehat",pakan:"-",pakanPerhari:0,kandang:"F",supplier:"PT Wonokoyo",vaksin:"Lengkap",fcr:1.68,mortalitas:60,tglPanen:"2026-05-01",notes:"Panen D42 harga naik Rp24.000/kg. Total 2.140 ekor × 2.35kg. FCR 1.68 bagus"},
  {id:"BR004",name:"Kandang G - Persiapan",type:"broiler",breed:"Cobb 500",jumlah:0,jumlahAwal:0,umurHari:0,tglMasuk:"",beratRata:0,targetBerat:2.0,hargaDOC:7500,biayaDoc:0,status:"Kosong",health:"Sehat",pakan:"-",pakanPerhari:0,kandang:"G",supplier:"",vaksin:"Belum",fcr:0,mortalitas:0,tglPanen:"",notes:"Sedang washing & disinfeksi. Chick-in rencana 2026-06-20"},
];

const initialBroilerHarvest = [
  {id:"BH001",name:"Kandang F - Periode 12 (Panen)",flockId:"BR003",tanggalPanen:"2026-05-01",jumlahPanen:2140,beratRata:2.35,totalBerat:5029,hargaJual:24000,totalPendapatan:120696000,fcr:1.68,buyer:"CV Ayam Mas Tasikmalaya",notes:"Harga bagus Rp24.000 karena moment Idul Adha"},
  {id:"BH002",name:"Kandang E - Periode 11 (Panen)",flockId:"",tanggalPanen:"2026-04-01",jumlahPanen:1780,beratRata:2.05,totalBerat:3649,hargaJual:22500,totalPendapatan:82102500,fcr:1.72,buyer:"Jagal H. Mahmud",notes:"Panen normal, FCR 1.72 masih OK"},
];

const initialSales = [
  {id:"JL001",animalId:"S001",animalName:"Simental-01",animalType:"sapi",buyer:"H. Ahmad Bandar",buyerPhone:"0812-3456-7890",date:"2026-04-10",weight:410,pricePerKg:58000,totalPrice:23780000,buyPrice:19000000,profit:4780000,saleType:"Langsung",notes:"Bayar tunai"},
  {id:"JL002",animalId:"D001",animalName:"Garut-Jantan-01",animalType:"domba",buyer:"Jagal Pak Udin",buyerPhone:"0813-2345-6789",date:"2026-05-01",weight:52,pricePerKg:90000,totalPrice:4680000,buyPrice:3500000,profit:1180000,saleType:"Pasar Hewan",notes:"Harga bagus"},
  {id:"JL003",animalId:"",animalName:"Broiler Kandang F P12",animalType:"broiler",buyer:"CV Ayam Mas",buyerPhone:"0811-100-2345",date:"2026-05-01",weight:5029,pricePerKg:24000,totalPrice:120696000,buyPrice:85000000,profit:35696000,saleType:"Panen",notes:"Kandang F Periode 12, 2.140 ekor"},
  {id:"JL004",animalId:"",animalName:"Broiler Kandang E P11",animalType:"broiler",buyer:"Jagal H. Mahmud",buyerPhone:"0816-5678-9012",date:"2026-04-01",weight:3649,pricePerKg:22500,totalPrice:82102500,buyPrice:62000000,profit:20102500,saleType:"Panen",notes:"1.780 ekor"},
  {id:"JL005",animalId:"",animalName:"Telur Kandang A+B Mei 2026",animalType:"petelur",buyer:"Pengepul Bu Haji",buyerPhone:"0815-9876-5432",date:"2026-05-31",weight:0,pricePerKg:0,totalPrice:48500000,buyPrice:35000000,profit:13500000,saleType:"Telur",notes:"Telur Mei: 5.500 tray × Rp8.800"},
  {id:"JL006",animalId:"S002",animalName:"Limousin-02",animalType:"sapi",buyer:"RPH Kota Tasik",buyerPhone:"0265-331574",date:"2026-03-15",weight:380,pricePerKg:60000,totalPrice:22800000,buyPrice:18500000,profit:4300000,saleType:"RPH",notes:"Masuk RPH langsung"},
];

/* ================================================================
   ChickenCard — Kartu Kandang Broiler / Layer
================================================================ */
const ChickenCard = ({ flock, type, onEdit, onDelete }) => {
  const f = flock || {};
  const isBroiler = type === "broiler";
  const ac = isBroiler ? "#e879f9" : "#f59e0b";

  // Hitung metrik
  const liv = f.jumlahAwal > 0 ? (f.jumlah / f.jumlahAwal * 100) : 100;
  const deplesi = f.jumlahAwal > 0 ? ((f.mortalitas || 0) / f.jumlahAwal * 100) : 0;
  const ip = isBroiler && f.beratRata && f.fcr && f.umurHari
    ? (f.beratRata * liv / f.fcr / f.umurHari * 100) : 0;
  const hdp = !isBroiler && f.produksiHarian && f.jumlah
    ? (f.produksiHarian / f.jumlah * 100) : 0;

  const statusColor = {
    "Pembesaran": "#3b82f6", "Siap Panen": "#22c55e", "Sudah Panen": "#9097a8",
    "Kosong": "#555a6a", "Produksi": "#22c55e", "Afkir": "#f59e0b", "Persiapan": "#a855f7",
  }[f.status] || "#9097a8";

  return (
    <div style={{ background: "#0f1118", border: `1px solid ${ac}25`, borderRadius: 14, padding: 16 }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
        <div>
          <div style={{ color: ac, fontWeight: 800, fontSize: 14, marginBottom: 2 }}>{f.name || "—"}</div>
          <div style={{ color: "#9097a8", fontSize: 11 }}>{f.breed || "—"} · Kandang {f.kandang || "—"}</div>
        </div>
        <span style={{ background: statusColor + "18", color: statusColor, border: `1px solid ${statusColor}30`, borderRadius: 20, padding: "3px 10px", fontSize: 10, fontWeight: 700 }}>
          {f.status || "—"}
        </span>
      </div>

      {/* Stats grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 12 }}>
        {[
          ["Populasi", (f.jumlah || 0).toLocaleString("id-ID") + " ekor"],
          [isBroiler ? "Umur" : "Umur", isBroiler ? "D" + (f.umurHari || 0) : (f.umurMinggu || 0) + " mgg"],
          ["BB Rata", (f.beratRata || 0) + " kg"],
          isBroiler ? ["FCR", f.fcr || "—"] : ["Prod/Hari", (f.produksiHarian || 0) + " btr"],
        ].map(([k, v], i) => (
          <div key={i} style={{ background: "#ffffff05", borderRadius: 8, padding: "7px 10px" }}>
            <div style={{ fontSize: 9, color: "#555a6a", fontWeight: 700, textTransform: "uppercase" }}>{k}</div>
            <div style={{ fontSize: 13, color: "#e2e4f0", fontWeight: 700, marginTop: 1 }}>{v}</div>
          </div>
        ))}
      </div>

      {/* KPI badges */}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
        {isBroiler ? (
          <>
            <span style={{ background: (ip >= 300 ? "#22c55e" : ip >= 250 ? "#f59e0b" : "#ef4444") + "15", color: ip >= 300 ? "#22c55e" : ip >= 250 ? "#f59e0b" : "#ef4444", borderRadius: 7, padding: "3px 9px", fontSize: 10, fontWeight: 700 }}>
              IP {ip.toFixed(0)}
            </span>
            <span style={{ background: (deplesi < 5 ? "#22c55e" : "#ef4444") + "15", color: deplesi < 5 ? "#22c55e" : "#ef4444", borderRadius: 7, padding: "3px 9px", fontSize: 10, fontWeight: 700 }}>
              Deplesi {deplesi.toFixed(1)}%
            </span>
          </>
        ) : (
          <>
            <span style={{ background: (hdp >= 85 ? "#22c55e" : "#f59e0b") + "15", color: hdp >= 85 ? "#22c55e" : "#f59e0b", borderRadius: 7, padding: "3px 9px", fontSize: 10, fontWeight: 700 }}>
              HDP {hdp.toFixed(1)}%
            </span>
            <span style={{ background: "#9097a815", color: "#9097a8", borderRadius: 7, padding: "3px 9px", fontSize: 10, fontWeight: 700 }}>
              {(f.jumlahAwal || 0).toLocaleString("id-ID")} awal
            </span>
          </>
        )}
      </div>

      {/* Actions */}
      <div style={{ display: "flex", gap: 6 }}>
        <button onClick={() => onEdit && onEdit(f)} style={{ flex: 1, background: ac + "14", color: ac, border: `1px solid ${ac}30`, borderRadius: 8, padding: "6px", cursor: "pointer", fontWeight: 700, fontSize: 11 }}>
          ✏️ Edit
        </button>
        <button onClick={() => onDelete && onDelete(f.id)} style={{ background: "#ef444414", color: "#ef4444", border: "1px solid #ef444430", borderRadius: 8, padding: "6px 12px", cursor: "pointer", fontWeight: 700, fontSize: 11 }}>
          🗑️
        </button>
      </div>
    </div>
  );
};

const PagePetelur = ({ flocks=[], setFlocks, eggs=[], setEggs }) => {
  const ac = "#f59e0b";
  const blankFlock = { name: "", type: "petelur", breed: "Lohmann Brown", jumlah: "", jumlahAwal: "", umurMinggu: "", tglMasuk: "", produksiHarian: "", targetProduksi: "", hargaDOC: "", biayaDoc: "", beratRata: "", status: "Produksi", health: "Sehat", pakan: "Layer Concentrate", pakanPerhari: "", kandang: "", supplier: "", vaksin: "Belum", mortalitas: 0, notes: "" };
  const blankEgg = { flockId: "", flockName: "", date: new Date().toISOString().split("T")[0], produksi: "", reject: "", netto: "", hargaPerBiji: 1800, totalPendapatan: "", buyer: "", notes: "" };

  const [showFlock, setShowFlock] = useState(false);
  const [showEgg, setShowEgg] = useState(false);
  const [formFlock, setFormFlock] = useState(blankFlock);
  const [formEgg, setFormEgg] = useState(blankEgg);
  const [editFlockId, setEditFlockId] = useState(null);
  const [activeTab, setActiveTab] = useState("kandang");

  const totalPopulasi = flocks.reduce((s, f) => s + f.jumlah, 0);
  const totalProduksiHari = flocks.filter(f => f.status === "Produksi").reduce((s, f) => s + f.produksiHarian, 0);
  const totalPendTelur = eggs.reduce((s, e) => s + e.totalPendapatan, 0);
  const avgHenDay = flocks.filter(f => f.jumlah > 0 && f.status === "Produksi").length > 0
    ? (flocks.filter(f => f.jumlah > 0 && f.status === "Produksi").reduce((s, f) => s + (f.produksiHarian / f.jumlah) * 100, 0) / flocks.filter(f => f.jumlah > 0 && f.status === "Produksi").length).toFixed(1)
    : 0;

  const saveFlock = () => {
    const p = { ...formFlock, jumlah: +formFlock.jumlah, jumlahAwal: +formFlock.jumlahAwal || +formFlock.jumlah, umurMinggu: +formFlock.umurMinggu, produksiHarian: +formFlock.produksiHarian, targetProduksi: +formFlock.targetProduksi, hargaDOC: +formFlock.hargaDOC, biayaDoc: +formFlock.biayaDoc, beratRata: +formFlock.beratRata, pakanPerhari: +formFlock.pakanPerhari, mortalitas: +formFlock.mortalitas };
    if (editFlockId) setFlocks(flocks.map(f => f.id === editFlockId ? { ...p, id: editFlockId } : f));
    else setFlocks([...flocks, { ...p, id: "PT" + String(flocks.length + 1).padStart(3, "0") }]);
    setShowFlock(false); setEditFlockId(null); setFormFlock(blankFlock);
  };
  const saveEgg = () => {
    const flock = flocks.find(f => f.id === formEgg.flockId);
    const netto = +formEgg.produksi - +formEgg.reject;
    const total = netto * +formEgg.hargaPerBiji;
    setEggs([{ id: "TL" + String(eggs.length + 1).padStart(3, "0"), ...formEgg, netto, totalPendapatan: total, flockName: flock ? flock.name : "" }, ...eggs]);
    setShowEgg(false); setFormEgg(blankEgg);
  };
  const openEditFlock = f => { setFormFlock({ ...f }); setEditFlockId(f.id); setShowFlock(true); };
  const delFlock = id => { if (confirm("Hapus kandang?")) setFlocks(flocks.filter(f => f.id !== id)); };

  const InputF = ({ label, value, onChange, type = "text", options, span }) => (
    <div style={{ gridColumn: span ? "1/-1" : undefined }}>
      <label style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.2, fontWeight: 700, display: "block", marginBottom: 5 }}>{label}</label>
      {options ? (
        <select value={value} onChange={e => onChange(e.target.value)} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" }}>
          {options.map(o => <option key={o.v ?? o} value={o.v ?? o}>{o.l ?? o}</option>)}
        </select>
      ) : (
        <input type={type} value={value} onChange={e => onChange(e.target.value)} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" }} />
      )}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* STAT */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        {[["Total Populasi", totalPopulasi.toLocaleString("id-ID") + " ekor", ac, "🐔"],
          ["Produksi/Hari", totalProduksiHari.toLocaleString("id-ID") + " butir", "#22c55e", "🥚"],
          ["Avg Hen Day", avgHenDay + "%", avgHenDay >= 80 ? "#22c55e" : avgHenDay >= 60 ? "#f59e0b" : "#ef4444", "📊"],
          ["Total Pend. Telur", "Rp " + (totalPendTelur / 1000000).toFixed(1) + "jt", "#3b82f6", "💰"]].map(([l, v, c, e]) => (
          <div key={l} style={{ background: c + "0c", border: `1px solid ${c}25`, borderRadius: 14, padding: "16px 18px", position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", top: 10, right: 12, fontSize: 28, opacity: 0.15 }}>{e}</div>
            <div style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.5, fontWeight: 700, marginBottom: 6 }}>{l}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: c, lineHeight: 1.1 }}>{v}</div>
            <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 2, background: `linear-gradient(90deg,${c},transparent)` }} />
          </div>
        ))}
      </div>

      {/* TABS */}
      <div style={{ display: "flex", gap: 8, borderBottom: "1px solid #1c1e2b", paddingBottom: 0 }}>
        {[{ id: "kandang", l: "🏠 Data Kandang" }, { id: "telur", l: "🥚 Catatan Produksi Telur" }].map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{ background: "none", border: "none", borderBottom: activeTab === t.id ? `2px solid ${ac}` : "2px solid transparent", color: activeTab === t.id ? ac : "#555a6a", padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13, marginBottom: -1 }}>{t.l}</button>
        ))}
      </div>

      {activeTab === "kandang" && (
        <>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button onClick={() => { setEditFlockId(null); setFormFlock(blankFlock); setShowFlock(true); }} style={{ background: ac + "18", color: ac, border: `1px solid ${ac}30`, borderRadius: 9, padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13, display: "flex", alignItems: "center", gap: 6 }}>
              + Tambah Kandang
            </button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(280px,1fr))", gap: 14 }}>
            {flocks.map(f => <ChickenCard key={f.id} flock={f} type="petelur" onEdit={openEditFlock} onDelete={delFlock} />)}
          </div>
        </>
      )}

      {activeTab === "telur" && (
        <>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button onClick={() => setShowEgg(true)} style={{ background: "#22c55e18", color: "#22c55e", border: "1px solid #22c55e30", borderRadius: 9, padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13, display: "flex", alignItems: "center", gap: 6 }}>
              + Catat Produksi Telur
            </button>
          </div>
          <div style={{ overflowX: "auto", borderRadius: 12, border: "1px solid #1c1e2b" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
              <thead>
                <tr style={{ background: "#22c55e0a", borderBottom: "1px solid #22c55e25" }}>
                  {["ID", "Kandang", "Tanggal", "Produksi", "Reject", "Netto", "Harga/btr", "Total", "Pembeli", "Catatan"].map(h => (
                    <th key={h} style={{ padding: "10px 12px", color: "#22c55e", textAlign: "left", fontSize: 9, fontWeight: 800, textTransform: "uppercase", whiteSpace: "nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {eggs.length === 0 ? <tr><td colSpan={10} style={{ textAlign: "center", padding: 36, color: "#555a6a" }}>Belum ada data</td></tr> :
                  eggs.map((e, i) => (
                    <tr key={e.id} style={{ borderBottom: "1px solid #1c1e2b", background: i % 2 ? "#ffffff04" : "transparent" }}>
                      <td style={{ padding: "9px 12px", color: "#555a6a", fontFamily: "monospace", fontSize: 10 }}>{e.id}</td>
                      <td style={{ padding: "9px 12px", color: "#e2e4f0", fontWeight: 600, maxWidth: 160, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.flockName}</td>
                      <td style={{ padding: "9px 12px", color: "#555a6a" }}>{e.date}</td>
                      <td style={{ padding: "9px 12px", color: "#e2e4f0" }}>{e.produksi?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#ef4444" }}>{e.reject}</td>
                      <td style={{ padding: "9px 12px", color: "#22c55e", fontWeight: 700 }}>{e.netto?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#9097a8" }}>Rp {e.hargaPerBiji?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#3b82f6", fontWeight: 700 }}>Rp {e.totalPendapatan?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#9097a8" }}>{e.buyer}</td>
                      <td style={{ padding: "9px 12px", color: "#555a6a", fontSize: 11 }}>{e.notes || "-"}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* Modal Kandang Petelur */}
      {showFlock && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.82)", zIndex: 999, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
          <div style={{ background: "#0e1120", border: "1px solid #252535", borderRadius: 18, padding: 26, maxWidth: 660, width: "100%", maxHeight: "92vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, paddingBottom: 14, borderBottom: "1px solid #1c1e2b" }}>
              <h3 style={{ color: ac, fontFamily: "'DM Serif Display',serif", fontSize: 18, margin: 0 }}>{editFlockId ? "Edit Kandang" : "Tambah Kandang Petelur"}</h3>
              <button onClick={() => { setShowFlock(false); setEditFlockId(null); }} style={{ background: "none", border: "none", cursor: "pointer", color: "#555a6a" }}>✕</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 13 }}>
              <InputF label="Nama Kandang" value={formFlock.name} onChange={v => setFormFlock({ ...formFlock, name: v })} span />
              <InputF label="Strain / Ras" value={formFlock.breed} onChange={v => setFormFlock({ ...formFlock, breed: v })} options={["Lohmann Brown", "ISA Brown", "Hy-Line Brown", "Nick Chick", "Arab", "Kampung Super"]} />
              <InputF label="Status" value={formFlock.status} onChange={v => setFormFlock({ ...formFlock, status: v })} options={["Produksi", "Akan Afkir", "Kosong", "Persiapan"]} />
              <InputF label="Populasi Saat Ini" value={formFlock.jumlah} onChange={v => setFormFlock({ ...formFlock, jumlah: v })} type="number" />
              <InputF label="Populasi Awal (DOC)" value={formFlock.jumlahAwal} onChange={v => setFormFlock({ ...formFlock, jumlahAwal: v })} type="number" />
              <InputF label="Umur (minggu)" value={formFlock.umurMinggu} onChange={v => setFormFlock({ ...formFlock, umurMinggu: v })} type="number" />
              <InputF label="Tanggal Masuk DOC" value={formFlock.tglMasuk} onChange={v => setFormFlock({ ...formFlock, tglMasuk: v })} type="date" />
              <InputF label="Produksi/Hari (butir)" value={formFlock.produksiHarian} onChange={v => setFormFlock({ ...formFlock, produksiHarian: v })} type="number" />
              <InputF label="Target Produksi (butir)" value={formFlock.targetProduksi} onChange={v => setFormFlock({ ...formFlock, targetProduksi: v })} type="number" />
              <InputF label="Berat Rata-rata (kg)" value={formFlock.beratRata} onChange={v => setFormFlock({ ...formFlock, beratRata: v })} type="number" />
              <InputF label="Harga DOC/ekor (Rp)" value={formFlock.hargaDOC} onChange={v => setFormFlock({ ...formFlock, hargaDOC: v })} type="number" />
              <InputF label="Total Biaya DOC (Rp)" value={formFlock.biayaDoc} onChange={v => setFormFlock({ ...formFlock, biayaDoc: v })} type="number" />
              <InputF label="Pakan/Hari (kg)" value={formFlock.pakanPerhari} onChange={v => setFormFlock({ ...formFlock, pakanPerhari: v })} type="number" />
              <InputF label="Mortalitas (ekor)" value={formFlock.mortalitas} onChange={v => setFormFlock({ ...formFlock, mortalitas: v })} type="number" />
              <InputF label="No. Kandang" value={formFlock.kandang} onChange={v => setFormFlock({ ...formFlock, kandang: v })} />
              <InputF label="Vaksinasi" value={formFlock.vaksin} onChange={v => setFormFlock({ ...formFlock, vaksin: v })} options={["Lengkap", "Belum", "Sebagian"]} />
              <InputF label="Supplier DOC" value={formFlock.supplier} onChange={v => setFormFlock({ ...formFlock, supplier: v })} span />
            </div>
            <button onClick={saveFlock} style={{ marginTop: 18, background: ac, color: "#000", border: "none", borderRadius: 10, padding: "11px", cursor: "pointer", fontWeight: 800, width: "100%", fontSize: 14 }}>Simpan Kandang</button>
          </div>
        </div>
      )}

      {/* Modal Produksi Telur */}
      {showEgg && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.82)", zIndex: 999, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
          <div style={{ background: "#0e1120", border: "1px solid #252535", borderRadius: 18, padding: 26, maxWidth: 560, width: "100%", maxHeight: "90vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, paddingBottom: 14, borderBottom: "1px solid #1c1e2b" }}>
              <h3 style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 18, margin: 0 }}>Catat Produksi Telur</h3>
              <button onClick={() => setShowEgg(false)} style={{ background: "none", border: "none", cursor: "pointer", color: "#555a6a" }}>✕</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 13 }}>
              <div style={{ gridColumn: "1/-1" }}>
                <label style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.2, fontWeight: 700, display: "block", marginBottom: 5 }}>Pilih Kandang</label>
                <select value={formEgg.flockId} onChange={e => setFormEgg({ ...formEgg, flockId: e.target.value })} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, width: "100%" }}>
                  <option value="">-- Pilih Kandang --</option>
                  {flocks.filter(f => f.status === "Produksi").map(f => <option key={f.id} value={f.id}>{f.name} ({f.jumlah} ekor)</option>)}
                </select>
              </div>
              <InputF label="Tanggal" value={formEgg.date} onChange={v => setFormEgg({ ...formEgg, date: v })} type="date" />
              <InputF label="Jumlah Produksi (butir)" value={formEgg.produksi} onChange={v => setFormEgg({ ...formEgg, produksi: v })} type="number" />
              <InputF label="Reject / Pecah" value={formEgg.reject} onChange={v => setFormEgg({ ...formEgg, reject: v })} type="number" />
              <InputF label="Harga per Butir (Rp)" value={formEgg.hargaPerBiji} onChange={v => setFormEgg({ ...formEgg, hargaPerBiji: v })} type="number" />
              <InputF label="Pembeli" value={formEgg.buyer} onChange={v => setFormEgg({ ...formEgg, buyer: v })} span />
            </div>
            {formEgg.produksi && formEgg.reject && formEgg.hargaPerBiji && (
              <div style={{ marginTop: 12, background: "#22c55e0a", border: "1px solid #22c55e22", borderRadius: 9, padding: 11, display: "flex", gap: 14, flexWrap: "wrap" }}>
                <span style={{ fontSize: 12, color: "#9097a8" }}>Netto: <strong style={{ color: "#22c55e" }}>{(+formEgg.produksi - +formEgg.reject).toLocaleString("id-ID")} butir</strong></span>
                <span style={{ fontSize: 12, color: "#9097a8" }}>Pendapatan: <strong style={{ color: "#3b82f6" }}>Rp {((+formEgg.produksi - +formEgg.reject) * +formEgg.hargaPerBiji).toLocaleString("id-ID")}</strong></span>
                {formEgg.flockId && flocks.find(f => f.id === formEgg.flockId) && (
                  <span style={{ fontSize: 12, color: "#9097a8" }}>Hen Day: <strong style={{ color: "#f59e0b" }}>{((+formEgg.produksi / flocks.find(f => f.id === formEgg.flockId).jumlah) * 100).toFixed(1)}%</strong></span>
                )}
              </div>
            )}
            <button onClick={saveEgg} style={{ marginTop: 18, background: "#22c55e", color: "#000", border: "none", borderRadius: 10, padding: "11px", cursor: "pointer", fontWeight: 800, width: "100%", fontSize: 14 }}>Catat Produksi</button>
          </div>
        </div>
      )}
    </div>
  );
};

/* ===== HALAMAN: AYAM BROILER ===== */
const PageBroiler = ({ flocks=[], setFlocks, harvests=[], setHarvests }) => {
  const ac = "#e879f9";
  const blankFlock = { name: "", type: "broiler", breed: "Cobb 500", jumlah: "", jumlahAwal: "", umurHari: "", tglMasuk: "", beratRata: 0, targetBerat: 2.0, hargaDOC: "", biayaDoc: "", status: "Pembesaran", health: "Sehat", pakan: "Broiler Starter", pakanPerhari: "", kandang: "", supplier: "", vaksin: "Belum", fcr: "", mortalitas: 0, tglPanen: "", notes: "" };
  const blankHarvest = { flockId: "", flockName: "", date: new Date().toISOString().split("T")[0], jumlahPanen: "", beratRata: "", totalBerat: "", hargaPerKg: 22000, totalPendapatan: "", buyer: "", payMethod: "Transfer", fcr: "", notes: "" };

  const [showFlock, setShowFlock] = useState(false);
  const [showHarvest, setShowHarvest] = useState(false);
  const [formFlock, setFormFlock] = useState(blankFlock);
  const [formHarvest, setFormHarvest] = useState(blankHarvest);
  const [editFlockId, setEditFlockId] = useState(null);
  const [activeTab, setActiveTab] = useState("kandang");

  const aktif = flocks.filter(f => f.status !== "Sudah Panen" && f.status !== "Kosong");
  const totalPopulasi = aktif.reduce((s, f) => s + f.jumlah, 0);
  const totalPanenRev = harvests.reduce((s, h) => s + h.totalPendapatan, 0);
  const avgFCR = harvests.length > 0 ? (harvests.reduce((s, h) => s + h.fcr, 0) / harvests.length).toFixed(2) : 0;
  const siapPanen = flocks.filter(f => f.status === "Siap Panen").length;

  const saveFlock = () => {
    const p = { ...formFlock, jumlah: +formFlock.jumlah, jumlahAwal: +formFlock.jumlahAwal || +formFlock.jumlah, umurHari: +formFlock.umurHari, beratRata: +formFlock.beratRata, targetBerat: +formFlock.targetBerat, hargaDOC: +formFlock.hargaDOC, biayaDoc: +formFlock.biayaDoc, pakanPerhari: +formFlock.pakanPerhari, fcr: +formFlock.fcr, mortalitas: +formFlock.mortalitas };
    if (editFlockId) setFlocks(flocks.map(f => f.id === editFlockId ? { ...p, id: editFlockId } : f));
    else setFlocks([...flocks, { ...p, id: "BRL" + String(flocks.length + 1).padStart(3, "0") }]);
    setShowFlock(false); setEditFlockId(null); setFormFlock(blankFlock);
  };
  const saveHarvest = () => {
    const flock = flocks.find(f => f.id === formHarvest.flockId);
    const totalBerat = +formHarvest.jumlahPanen * +formHarvest.beratRata;
    const total = totalBerat * +formHarvest.hargaPerKg;
    setHarvests([{ id: "PN" + String(harvests.length + 1).padStart(3, "0"), ...formHarvest, totalBerat, totalPendapatan: total, flockName: flock ? flock.name : "", fcr: +formHarvest.fcr }, ...harvests]);
    setShowHarvest(false); setFormHarvest(blankHarvest);
  };
  const openEditFlock = f => { setFormFlock({ ...f }); setEditFlockId(f.id); setShowFlock(true); };
  const delFlock = id => { if (confirm("Hapus kandang?")) setFlocks(flocks.filter(f => f.id !== id)); };

  const InputF = ({ label, value, onChange, type = "text", options, span }) => (
    <div style={{ gridColumn: span ? "1/-1" : undefined }}>
      <label style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.2, fontWeight: 700, display: "block", marginBottom: 5 }}>{label}</label>
      {options ? (
        <select value={value} onChange={e => onChange(e.target.value)} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" }}>
          {options.map(o => <option key={o.v ?? o} value={o.v ?? o}>{o.l ?? o}</option>)}
        </select>
      ) : (
        <input type={type} value={value} onChange={e => onChange(e.target.value)} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box" }} />
      )}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* STAT */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        {[["Populasi Aktif", totalPopulasi.toLocaleString("id-ID") + " ekor", ac, "🐓"],
          ["Siap Panen", siapPanen + " kandang", "#a3e635", "✅"],
          ["Total Panen", harvests.length + " batch", "#22c55e", "🏭"],
          ["Avg FCR", avgFCR, avgFCR <= 1.7 ? "#22c55e" : avgFCR <= 1.85 ? "#f59e0b" : "#ef4444", "📊"],
          ["Total Pend. Panen", "Rp " + (totalPanenRev / 1000000).toFixed(1) + "jt", "#3b82f6", "💰"]].map(([l, v, c, e]) => (
          <div key={l} style={{ background: c + "0c", border: `1px solid ${c}25`, borderRadius: 14, padding: "16px 18px", position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", top: 10, right: 12, fontSize: 26, opacity: 0.15 }}>{e}</div>
            <div style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.5, fontWeight: 700, marginBottom: 6 }}>{l}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: c, lineHeight: 1.1 }}>{v}</div>
            <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 2, background: `linear-gradient(90deg,${c},transparent)` }} />
          </div>
        ))}
      </div>

      {/* Alert siap panen */}
      {siapPanen > 0 && (
        <div style={{ background: "#a3e63510", border: "1px solid #a3e63528", borderRadius: 11, padding: "10px 14px", color: "#a3e635", fontSize: 13, display: "flex", alignItems: "center", gap: 8 }}>
          🚨 {flocks.filter(f => f.status === "Siap Panen").map(f => f.name).join(", ")} — SIAP PANEN!
        </div>
      )}

      {/* TABS */}
      <div style={{ display: "flex", gap: 8, borderBottom: "1px solid #1c1e2b" }}>
        {[{ id: "kandang", l: "🏠 Data Kandang Broiler" }, { id: "panen", l: "🏭 Catatan Panen" }].map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{ background: "none", border: "none", borderBottom: activeTab === t.id ? `2px solid ${ac}` : "2px solid transparent", color: activeTab === t.id ? ac : "#555a6a", padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13, marginBottom: -1 }}>{t.l}</button>
        ))}
      </div>

      {activeTab === "kandang" && (
        <>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button onClick={() => { setEditFlockId(null); setFormFlock(blankFlock); setShowFlock(true); }} style={{ background: ac + "18", color: ac, border: `1px solid ${ac}30`, borderRadius: 9, padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13, display: "flex", alignItems: "center", gap: 6 }}>
              + Tambah Kandang Broiler
            </button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(280px,1fr))", gap: 14 }}>
            {flocks.map(f => <ChickenCard key={f.id} flock={f} type="broiler" onEdit={openEditFlock} onDelete={delFlock} />)}
          </div>
        </>
      )}

      {activeTab === "panen" && (
        <>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button onClick={() => setShowHarvest(true)} style={{ background: "#22c55e18", color: "#22c55e", border: "1px solid #22c55e30", borderRadius: 9, padding: "8px 16px", cursor: "pointer", fontWeight: 700, fontSize: 13 }}>
              + Catat Panen
            </button>
          </div>
          <div style={{ overflowX: "auto", borderRadius: 12, border: "1px solid #1c1e2b" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
              <thead>
                <tr style={{ background: "#22c55e0a", borderBottom: "1px solid #22c55e25" }}>
                  {["ID", "Kandang", "Tgl Panen", "Jml Panen", "Berat Rata", "Total Kg", "Harga/kg", "Total", "Buyer", "FCR", "Bayar"].map(h => (
                    <th key={h} style={{ padding: "10px 12px", color: "#22c55e", textAlign: "left", fontSize: 9, fontWeight: 800, textTransform: "uppercase", whiteSpace: "nowrap" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {harvests.length === 0 ? <tr><td colSpan={11} style={{ textAlign: "center", padding: 36, color: "#555a6a" }}>Belum ada data panen</td></tr> :
                  harvests.map((h, i) => (
                    <tr key={h.id} style={{ borderBottom: "1px solid #1c1e2b", background: i % 2 ? "#ffffff04" : "transparent" }}>
                      <td style={{ padding: "9px 12px", color: "#555a6a", fontFamily: "monospace", fontSize: 10 }}>{h.id}</td>
                      <td style={{ padding: "9px 12px", color: "#e2e4f0", fontWeight: 600, maxWidth: 150, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{h.flockName}</td>
                      <td style={{ padding: "9px 12px", color: "#555a6a" }}>{h.date}</td>
                      <td style={{ padding: "9px 12px", color: "#e2e4f0" }}>{h.jumlahPanen?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#9097a8" }}>{h.beratRata} kg</td>
                      <td style={{ padding: "9px 12px", color: "#f59e0b", fontWeight: 700 }}>{h.totalBerat?.toFixed(1)} kg</td>
                      <td style={{ padding: "9px 12px", color: "#9097a8" }}>Rp {h.hargaPerKg?.toLocaleString("id-ID")}</td>
                      <td style={{ padding: "9px 12px", color: "#3b82f6", fontWeight: 700 }}>Rp {(h.totalPendapatan / 1000000).toFixed(2)}jt</td>
                      <td style={{ padding: "9px 12px", color: "#9097a8" }}>{h.buyer}</td>
                      <td style={{ padding: "9px 12px", color: h.fcr <= 1.7 ? "#22c55e" : h.fcr <= 1.85 ? "#f59e0b" : "#ef4444", fontWeight: 700 }}>{h.fcr}</td>
                      <td style={{ padding: "9px 12px" }}><span style={{ background: "#3b82f614", color: "#3b82f6", border: "1px solid #3b82f628", borderRadius: 20, padding: "2px 8px", fontSize: 10, fontWeight: 700 }}>{h.payMethod}</span></td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* Modal Broiler */}
      {showFlock && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.82)", zIndex: 999, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
          <div style={{ background: "#0e1120", border: "1px solid #252535", borderRadius: 18, padding: 26, maxWidth: 660, width: "100%", maxHeight: "92vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, paddingBottom: 14, borderBottom: "1px solid #1c1e2b" }}>
              <h3 style={{ color: ac, fontFamily: "'DM Serif Display',serif", fontSize: 18, margin: 0 }}>{editFlockId ? "Edit Kandang" : "Tambah Kandang Broiler"}</h3>
              <button onClick={() => { setShowFlock(false); setEditFlockId(null); }} style={{ background: "none", border: "none", cursor: "pointer", color: "#555a6a" }}>✕</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 13 }}>
              <InputF label="Nama Kandang / Periode" value={formFlock.name} onChange={v => setFormFlock({ ...formFlock, name: v })} span />
              <InputF label="Strain DOC" value={formFlock.breed} onChange={v => setFormFlock({ ...formFlock, breed: v })} options={["Cobb 500", "Ross 308", "Hubbard", "Lohmann Meat", "Hybro"]} />
              <InputF label="Status" value={formFlock.status} onChange={v => setFormFlock({ ...formFlock, status: v })} options={["Pembesaran", "Siap Panen", "Sudah Panen", "Kosong"]} />
              <InputF label="Populasi Saat Ini" value={formFlock.jumlah} onChange={v => setFormFlock({ ...formFlock, jumlah: v })} type="number" />
              <InputF label="Populasi Awal (DOC)" value={formFlock.jumlahAwal} onChange={v => setFormFlock({ ...formFlock, jumlahAwal: v })} type="number" />
              <InputF label="Umur (hari)" value={formFlock.umurHari} onChange={v => setFormFlock({ ...formFlock, umurHari: v })} type="number" />
              <InputF label="Tanggal Chick-In" value={formFlock.tglMasuk} onChange={v => setFormFlock({ ...formFlock, tglMasuk: v })} type="date" />
              <InputF label="Target Panen" value={formFlock.tglPanen} onChange={v => setFormFlock({ ...formFlock, tglPanen: v })} type="date" />
              <InputF label="Berat Rata-rata (kg)" value={formFlock.beratRata} onChange={v => setFormFlock({ ...formFlock, beratRata: v })} type="number" />
              <InputF label="Target Berat Panen (kg)" value={formFlock.targetBerat} onChange={v => setFormFlock({ ...formFlock, targetBerat: v })} type="number" />
              <InputF label="FCR Saat Ini" value={formFlock.fcr} onChange={v => setFormFlock({ ...formFlock, fcr: v })} type="number" />
              <InputF label="Mortalitas (ekor)" value={formFlock.mortalitas} onChange={v => setFormFlock({ ...formFlock, mortalitas: v })} type="number" />
              <InputF label="Harga DOC/ekor (Rp)" value={formFlock.hargaDOC} onChange={v => setFormFlock({ ...formFlock, hargaDOC: v })} type="number" />
              <InputF label="Total Biaya DOC (Rp)" value={formFlock.biayaDoc} onChange={v => setFormFlock({ ...formFlock, biayaDoc: v })} type="number" />
              <InputF label="Pakan/Hari (kg)" value={formFlock.pakanPerhari} onChange={v => setFormFlock({ ...formFlock, pakanPerhari: v })} type="number" />
              <InputF label="Vaksinasi" value={formFlock.vaksin} onChange={v => setFormFlock({ ...formFlock, vaksin: v })} options={["Lengkap", "Belum", "Sebagian"]} />
              <InputF label="No. Kandang" value={formFlock.kandang} onChange={v => setFormFlock({ ...formFlock, kandang: v })} />
              <InputF label="Supplier DOC" value={formFlock.supplier} onChange={v => setFormFlock({ ...formFlock, supplier: v })} span />
            </div>
            <button onClick={saveFlock} style={{ marginTop: 18, background: ac, color: "#000", border: "none", borderRadius: 10, padding: "11px", cursor: "pointer", fontWeight: 800, width: "100%", fontSize: 14 }}>Simpan Kandang</button>
          </div>
        </div>
      )}

      {/* Modal Panen */}
      {showHarvest && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.82)", zIndex: 999, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
          <div style={{ background: "#0e1120", border: "1px solid #252535", borderRadius: 18, padding: 26, maxWidth: 560, width: "100%", maxHeight: "90vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, paddingBottom: 14, borderBottom: "1px solid #1c1e2b" }}>
              <h3 style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 18, margin: 0 }}>Catat Hasil Panen Broiler</h3>
              <button onClick={() => setShowHarvest(false)} style={{ background: "none", border: "none", cursor: "pointer", color: "#555a6a" }}>✕</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 13 }}>
              <div style={{ gridColumn: "1/-1" }}>
                <label style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.2, fontWeight: 700, display: "block", marginBottom: 5 }}>Pilih Kandang</label>
                <select value={formHarvest.flockId} onChange={e => setFormHarvest({ ...formHarvest, flockId: e.target.value })} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 9, padding: "9px 12px", color: "#e2e4f0", fontSize: 13, width: "100%" }}>
                  <option value="">-- Pilih --</option>
                  {flocks.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
                </select>
              </div>
              <InputF label="Tanggal Panen" value={formHarvest.date} onChange={v => setFormHarvest({ ...formHarvest, date: v })} type="date" />
              <InputF label="Jumlah Panen (ekor)" value={formHarvest.jumlahPanen} onChange={v => setFormHarvest({ ...formHarvest, jumlahPanen: v })} type="number" />
              <InputF label="Berat Rata-rata (kg)" value={formHarvest.beratRata} onChange={v => setFormHarvest({ ...formHarvest, beratRata: v })} type="number" />
              <InputF label="Harga per kg (Rp)" value={formHarvest.hargaPerKg} onChange={v => setFormHarvest({ ...formHarvest, hargaPerKg: v })} type="number" />
              <InputF label="FCR Akhir" value={formHarvest.fcr} onChange={v => setFormHarvest({ ...formHarvest, fcr: v })} type="number" />
              <InputF label="Pembeli" value={formHarvest.buyer} onChange={v => setFormHarvest({ ...formHarvest, buyer: v })} />
              <InputF label="Metode Bayar" value={formHarvest.payMethod} onChange={v => setFormHarvest({ ...formHarvest, payMethod: v })} options={["Transfer", "Tunai", "DP+Pelunasan"]} />
            </div>
            {formHarvest.jumlahPanen && formHarvest.beratRata && formHarvest.hargaPerKg && (
              <div style={{ marginTop: 12, background: "#22c55e0a", border: "1px solid #22c55e22", borderRadius: 9, padding: 11, display: "flex", gap: 14, flexWrap: "wrap" }}>
                <span style={{ fontSize: 12, color: "#9097a8" }}>Total Kg: <strong style={{ color: "#f59e0b" }}>{(+formHarvest.jumlahPanen * +formHarvest.beratRata).toFixed(1)} kg</strong></span>
                <span style={{ fontSize: 12, color: "#9097a8" }}>Pendapatan: <strong style={{ color: "#3b82f6" }}>Rp {((+formHarvest.jumlahPanen * +formHarvest.beratRata * +formHarvest.hargaPerKg) / 1000000).toFixed(2)}jt</strong></span>
              </div>
            )}
            <button onClick={saveHarvest} style={{ marginTop: 18, background: "#22c55e", color: "#000", border: "none", borderRadius: 10, padding: "11px", cursor: "pointer", fontWeight: 800, width: "100%", fontSize: 14 }}>Catat Panen</button>
          </div>
        </div>
      )}
    </div>
  );
};

/* ===== MAIN APP ===== */

/* ================================================================
   MODUL RPH SAPI — Rumah Potong Hewan
   Perhitungan lengkap: karkas, potongan primer, sekunder, jeroan,
   by-product, HPP, harga jual, dan profit per ekor
================================================================ */


/* ================================================================
   RPH_STANDAR — Data Harga & Persentase
================================================================ */
const RPH_STANDAR = {
  persen_karkas: {
    "Simental":{"jantan":56,"betina":52},"Limousin":{"jantan":55,"betina":51},
    "PO":{"jantan":50,"betina":47},"Bali":{"jantan":52,"betina":49},
    "Brahman":{"jantan":53,"betina":50},"FH Afkir":{"jantan":48,"betina":46},
    "default":{"jantan":52,"betina":49},
  },
  potongan_primer:[
    {kode:"has_dalam", nama:"Has Dalam (Tenderloin)",      pct:2.5,  grade:"Premium",  harga:220000, ket:"Paling empuk, steak/fillet"},
    {kode:"has_luar",  nama:"Has Luar (Sirloin)",          pct:3.5,  grade:"Premium",  harga:195000, ket:"Steak, grill, yakiniku"},
    {kode:"tanjung",   nama:"Tanjung (Rump)",               pct:4.0,  grade:"Premium",  harga:180000, ket:"Rendang, empal, steak"},
    {kode:"ekor",      nama:"Buntut/Ekor (Oxtail)",         pct:1.5,  grade:"Premium",  harga:172000, ket:"Sup buntut, semur"},
    {kode:"iga",       nama:"Iga (Short Rib)",               pct:10.0, grade:"Superior", harga:165000, ket:"Sup iga, BBQ, kaldu"},
    {kode:"paha_blkg", nama:"Paha Belakang (Topside)",      pct:7.5,  grade:"Superior", harga:160000, ket:"Rendang, semur, empal"},
    {kode:"gandik",    nama:"Gandik (Silverside/Knuckle)",  pct:5.5,  grade:"Superior", harga:158000, ket:"Rendang, empal, sate"},
    {kode:"lamusir",   nama:"Lamusir/Kisi (Chuck)",         pct:8.0,  grade:"Superior", harga:155000, ket:"Soto, semur, bakso"},
    {kode:"sengkel",   nama:"Sengkel/Betis (Shank)",        pct:5.0,  grade:"Standar",  harga:153000, ket:"Soto, semur, bakso urat"},
    {kode:"sandung",   nama:"Sandung Lamur (Brisket)",      pct:6.5,  grade:"Standar",  harga:148000, ket:"Rawon, sop betawi"},
    {kode:"paha_depan",nama:"Paha Depan (Blade)",           pct:7.0,  grade:"Standar",  harga:148000, ket:"Rendang, semur"},
    {kode:"punuk",     nama:"Punuk (Chuck Roll)",            pct:3.0,  grade:"Standar",  harga:148000, ket:"Sate, sop, khas zebu"},
    {kode:"leher",     nama:"Leher (Neck)",                  pct:3.0,  grade:"Standar",  harga:138000, ket:"Rawon, sop, asem-asem"},
  ],
  pct_tulang:18, harga_tulang:25000,
  by_products:[
    {nama:"Lidah",           pct_live:0.4, harga:155000, kat:"Fancy Meat",   latin:"Musculus glossus"},
    {nama:"Kepala (daging)", pct_live:1.5, harga:95000,  kat:"Fancy Meat",   latin:"M. masseter + M. temporalis"},
    {nama:"Kikil/Kaki (4)",  pct_live:1.5, harga:88000,  kat:"Fancy Meat",   latin:"Metacarpus/Metatarsus"},
    {nama:"Hati",            pct_live:1.4, harga:110000, kat:"Jeroan Merah", latin:"Hepar"},
    {nama:"Paru-paru",       pct_live:0.8, harga:90000,  kat:"Jeroan Merah", latin:"Pulmo"},
    {nama:"Jantung",         pct_live:0.4, harga:95000,  kat:"Jeroan Merah", latin:"Cor"},
    {nama:"Ginjal",          pct_live:0.3, harga:78000,  kat:"Jeroan Merah", latin:"Ren"},
    {nama:"Limpa",           pct_live:0.2, harga:58000,  kat:"Jeroan Merah", latin:"Lien/Spleen"},
    {nama:"Otak",            pct_live:0.2, harga:88000,  kat:"Jeroan Merah", latin:"Cerebrum"},
    {nama:"Babat (Rumen)",   pct_live:2.0, harga:68000,  kat:"Jeroan Putih", latin:"Rumen/Omasum"},
    {nama:"Usus Besar",      pct_live:1.8, harga:50000,  kat:"Jeroan Putih", latin:"Intestinum crassum"},
    {nama:"Usus Halus",      pct_live:0.8, harga:42000,  kat:"Jeroan Putih", latin:"Intestinum tenue"},
    {nama:"Tetelan (Koyor)", pct_live:1.5, harga:90000,  kat:"Jeroan Putih", latin:"Connective tissue"},
    {nama:"Kulit Sapi",      pct_live:5.5, harga:22000,  kat:"Kulit/Darah",  latin:"Corium"},
    {nama:"Darah Sapi (L)",  pct_live:4.0, harga:14000,  kat:"Kulit/Darah",  latin:"Sanguis"},
  ],
  biaya_rph:{retribusi:300000,upah:425000,listrik:90000,kemasan:70000,transport:375000,lainnya:140000},
};

/* ================================================================
   RPH_STANDAR_DOMBA — Data Harga & Persentase Domba/Kambing
   Sumber: Data RPH Garut, Aqiqah & Kurban Juni 2026
================================================================ */
const RPH_STANDAR_DOMBA = {
  persen_karkas: {
    "Domba Garut":   { jantan:50, betina:46 },
    "Domba Lokal":   { jantan:46, betina:43 },
    "Domba Merino":  { jantan:47, betina:44 },
    "Domba Ekor Gemuk":{ jantan:51, betina:47 },
    "Kambing PE":    { jantan:48, betina:44 },
    "Kambing Lokal": { jantan:46, betina:42 },
    "default":       { jantan:48, betina:44 },
  },
  potongan_primer:[
    {kode:"gigot",      nama:"Gigot/Kaki Belakang",     pct:30, grade:"Premium",  harga:130000, ket:"Bagian terlezat, sate, gule, roast"},
    {kode:"shoulder",   nama:"Bahu/Pundak (Shoulder)",  pct:20, grade:"Premium",  harga:118000, ket:"Rendang, semur, kari"},
    {kode:"rack",       nama:"Iga (Rack)",               pct:12, grade:"Premium",  harga:145000, ket:"Rack domba, BBQ, iga bakar"},
    {kode:"loin",       nama:"Loin/Punggung",            pct:10, grade:"Superior", harga:138000, ket:"Chop loin, sate, bakar"},
    {kode:"breast",     nama:"Dada/Perut (Breast)",      pct:12, grade:"Standar",  harga:95000,  ket:"Sate, gule, semur"},
    {kode:"neck",       nama:"Leher (Neck)",              pct:8,  grade:"Standar",  harga:88000,  ket:"Gulai, sop, kari"},
    {kode:"shank",      nama:"Betis/Sengkel (Shank)",    pct:8,  grade:"Standar",  harga:92000,  ket:"Sop, semur, osso buco"},
  ],
  pct_tulang: 22,
  harga_tulang: 18000,
  by_products:[
    {nama:"Kepala Domba",    pct_live:5.0,  harga:45000,  kat:"Fancy Meat",   latin:"Caput"},
    {nama:"Kaki (4)",        pct_live:2.5,  harga:30000,  kat:"Fancy Meat",   latin:"Pedis"},
    {nama:"Hati",            pct_live:2.0,  harga:90000,  kat:"Jeroan Merah", latin:"Hepar"},
    {nama:"Paru-paru",       pct_live:1.2,  harga:65000,  kat:"Jeroan Merah", latin:"Pulmo"},
    {nama:"Jantung",         pct_live:0.5,  harga:75000,  kat:"Jeroan Merah", latin:"Cor"},
    {nama:"Ginjal",          pct_live:0.4,  harga:60000,  kat:"Jeroan Merah", latin:"Ren"},
    {nama:"Limpa",           pct_live:0.3,  harga:45000,  kat:"Jeroan Merah", latin:"Lien"},
    {nama:"Otak",            pct_live:0.8,  harga:65000,  kat:"Jeroan Merah", latin:"Cerebrum"},
    {nama:"Babat/Rumen",     pct_live:2.5,  harga:55000,  kat:"Jeroan Putih", latin:"Rumen"},
    {nama:"Usus",            pct_live:1.5,  harga:38000,  kat:"Jeroan Putih", latin:"Intestinum"},
    {nama:"Tetelan",         pct_live:1.0,  harga:72000,  kat:"Jeroan Putih", latin:"Connective tissue"},
    {nama:"Kulit Domba",     pct_live:8.0,  harga:15000,  kat:"Kulit/Darah",  latin:"Pellis"},
    {nama:"Darah (L)",       pct_live:3.5,  harga:10000,  kat:"Kulit/Darah",  latin:"Sanguis"},
    {nama:"Ekor Gemuk",      pct_live:3.0,  harga:55000,  kat:"Fancy Meat",   latin:"Cauda adiposa"},
  ],
  biaya_rph:{retribusi:80000, upah:120000, listrik:30000, kemasan:25000, transport:100000, lainnya:45000},
};


/* ================================================================
   hitungRPH — kalkulasi dari record
================================================================ */
const initialRphRecords = [
  {
    id:"RPH001",
    sapiId:"S001",
    sapiNama:"BAL-01 (100kg)",
    breed:"Bali",
    gender:"Betina",
    bbHidup:100,
    hargaBeli:4800000,
    tglPotong:"2026-01-05",
    pctKarkas:47,
    status:"Selesai",
    buyer:"Warung Sate Pak Jono",
    notes:"Sapi Bali betina afkir, kecil",
    hJualHasDalam:200000,
    hJualHasLuar:180000,
    hJualTanjung:165000,
    hJualGandik:148000,
    hJualLamusir:145000,
    hJualSengkel:140000,
    hJualSandung:135000,
    hJualPahaD:138000,
    hJualPahaB:148000,
    hJualIga:150000,
    hJualPunuk:138000,
    hJualLeher:125000,
    hJualEkor:155000,
    hJualTulang:22000,
    bRetribusi:200000,
    bUpah:300000,
    bListrik:65000,
    bKemasan:45000,
    bTransport:200000,
    bLainnya:90000,
    aKarkas:47.0,
    aTulang:8.5,
    aHasDalam:1.12,
    aHasLuar:1.56,
    aTanjung:1.79,
    aGandik:2.46,
    aLamusir:3.57,
    aSengkel:2.23,
    aSandung:2.9,
    aPahaD:3.13,
    aPahaB:3.35,
    aIga:4.46,
    aPunuk:1.34,
    aLeher:1.34,
    aEkor:0.67,
    aLidah:0.38,
    aKepala:1.42,
    aKikil:1.42,
    aHati:1.33,
    aParu:0.76,
    aJantung:0.38,
    aGinjal:0.28,
    aLimpa:0.19,
    aOtak:0.19,
    aBabat:1.9,
    aUsusB:1.71,
    aUsusH:0.76,
    aTetelan:1.42,
    aKulit:5.22,
    aDarah:3.8,
    aFeses:4.0,
    aRumen:12.0,
  },
  {
    id:"RPH002",
    sapiId:"S002",
    sapiNama:"PO-02 (200kg)",
    breed:"PO",
    gender:"Jantan",
    bbHidup:200,
    hargaBeli:9500000,
    tglPotong:"2026-01-15",
    pctKarkas:50,
    status:"Selesai",
    buyer:"RPH Kota Malang",
    notes:"Sapi PO jantan muda, tulang masih besar",
    hJualHasDalam:205000,
    hJualHasLuar:185000,
    hJualTanjung:170000,
    hJualGandik:150000,
    hJualLamusir:148000,
    hJualSengkel:143000,
    hJualSandung:138000,
    hJualPahaD:140000,
    hJualPahaB:150000,
    hJualIga:152000,
    hJualPunuk:140000,
    hJualLeher:128000,
    hJualEkor:158000,
    hJualTulang:23000,
    bRetribusi:225000,
    bUpah:325000,
    bListrik:70000,
    bKemasan:50000,
    bTransport:250000,
    bLainnya:100000,
    aKarkas:100.0,
    aTulang:18.0,
    aHasDalam:2.45,
    aHasLuar:3.43,
    aTanjung:3.92,
    aGandik:5.39,
    aLamusir:7.84,
    aSengkel:4.9,
    aSandung:6.37,
    aPahaD:6.86,
    aPahaB:7.35,
    aIga:9.8,
    aPunuk:2.94,
    aLeher:2.94,
    aEkor:1.47,
    aLidah:0.78,
    aKepala:2.94,
    aKikil:2.94,
    aHati:2.74,
    aParu:1.57,
    aJantung:0.78,
    aGinjal:0.59,
    aLimpa:0.39,
    aOtak:0.39,
    aBabat:3.92,
    aUsusB:3.53,
    aUsusH:1.57,
    aTetelan:2.94,
    aKulit:10.78,
    aDarah:7.84,
    aFeses:8.0,
    aRumen:24.0,
  },
  {
    id:"RPH003",
    sapiId:"S003",
    sapiNama:"BRA-03 (300kg)",
    breed:"Brahman",
    gender:"Jantan",
    bbHidup:300,
    hargaBeli:14500000,
    tglPotong:"2026-02-03",
    pctKarkas:53,
    status:"Selesai",
    buyer:"Catering H. Ridwan",
    notes:"Brahman jantan, lemak sedang",
    hJualHasDalam:210000,
    hJualHasLuar:188000,
    hJualTanjung:172000,
    hJualGandik:152000,
    hJualLamusir:150000,
    hJualSengkel:145000,
    hJualSandung:140000,
    hJualPahaD:142000,
    hJualPahaB:153000,
    hJualIga:155000,
    hJualPunuk:142000,
    hJualLeher:130000,
    hJualEkor:162000,
    hJualTulang:23000,
    bRetribusi:250000,
    bUpah:360000,
    bListrik:75000,
    bKemasan:55000,
    bTransport:280000,
    bLainnya:110000,
    aKarkas:159.0,
    aTulang:28.6,
    aHasDalam:3.98,
    aHasLuar:5.57,
    aTanjung:6.36,
    aGandik:8.74,
    aLamusir:12.72,
    aSengkel:7.95,
    aSandung:10.34,
    aPahaD:11.13,
    aPahaB:11.93,
    aIga:15.9,
    aPunuk:4.77,
    aLeher:4.77,
    aEkor:2.38,
    aLidah:1.2,
    aKepala:4.5,
    aKikil:4.5,
    aHati:4.2,
    aParu:2.4,
    aJantung:1.2,
    aGinjal:0.9,
    aLimpa:0.6,
    aOtak:0.6,
    aBabat:6.0,
    aUsusB:5.4,
    aUsusH:2.4,
    aTetelan:4.5,
    aKulit:16.5,
    aDarah:12.0,
    aFeses:12.0,
    aRumen:36.0,
  },
  {
    id:"RPH004",
    sapiId:"S004",
    sapiNama:"SIM-04 (400kg)",
    breed:"Simental",
    gender:"Betina",
    bbHidup:400,
    hargaBeli:19200000,
    tglPotong:"2026-02-18",
    pctKarkas:52,
    status:"Selesai",
    buyer:"Supermarket Indo Daging",
    notes:"Simental betina afkir perah",
    hJualHasDalam:215000,
    hJualHasLuar:190000,
    hJualTanjung:175000,
    hJualGandik:154000,
    hJualLamusir:152000,
    hJualSengkel:147000,
    hJualSandung:142000,
    hJualPahaD:144000,
    hJualPahaB:155000,
    hJualIga:158000,
    hJualPunuk:144000,
    hJualLeher:132000,
    hJualEkor:165000,
    hJualTulang:24000,
    bRetribusi:275000,
    bUpah:390000,
    bListrik:80000,
    bKemasan:60000,
    bTransport:320000,
    bLainnya:120000,
    aKarkas:208.0,
    aTulang:37.4,
    aHasDalam:5.2,
    aHasLuar:7.28,
    aTanjung:8.32,
    aGandik:11.44,
    aLamusir:16.64,
    aSengkel:10.4,
    aSandung:13.52,
    aPahaD:14.56,
    aPahaB:15.6,
    aIga:20.8,
    aPunuk:6.24,
    aLeher:6.24,
    aEkor:3.12,
    aLidah:1.6,
    aKepala:6.0,
    aKikil:6.0,
    aHati:5.6,
    aParu:3.2,
    aJantung:1.6,
    aGinjal:1.2,
    aLimpa:0.8,
    aOtak:0.8,
    aBabat:8.0,
    aUsusB:7.2,
    aUsusH:3.2,
    aTetelan:6.0,
    aKulit:22.0,
    aDarah:16.0,
    aFeses:16.0,
    aRumen:48.0,
  },
  {
    id:"RPH005",
    sapiId:"S005",
    sapiNama:"LIM-05 (500kg)",
    breed:"Limousin",
    gender:"Jantan",
    bbHidup:500,
    hargaBeli:24500000,
    tglPotong:"2026-03-10",
    pctKarkas:55,
    status:"Selesai",
    buyer:"Jagal H. Ahmad",
    notes:"Limousin jantan unggul, sangat berisi",
    hJualHasDalam:220000,
    hJualHasLuar:195000,
    hJualTanjung:180000,
    hJualGandik:158000,
    hJualLamusir:155000,
    hJualSengkel:153000,
    hJualSandung:148000,
    hJualPahaD:148000,
    hJualPahaB:160000,
    hJualIga:165000,
    hJualPunuk:148000,
    hJualLeher:138000,
    hJualEkor:172000,
    hJualTulang:25000,
    bRetribusi:300000,
    bUpah:425000,
    bListrik:90000,
    bKemasan:70000,
    bTransport:375000,
    bLainnya:140000,
    aKarkas:275.0,
    aTulang:49.5,
    aHasDalam:7.01,
    aHasLuar:9.82,
    aTanjung:11.22,
    aGandik:15.43,
    aLamusir:22.44,
    aSengkel:14.03,
    aSandung:18.23,
    aPahaD:19.64,
    aPahaB:21.04,
    aIga:28.05,
    aPunuk:8.42,
    aLeher:8.42,
    aEkor:4.21,
    aLidah:2.04,
    aKepala:7.65,
    aKikil:7.65,
    aHati:7.14,
    aParu:4.08,
    aJantung:2.04,
    aGinjal:1.53,
    aLimpa:1.02,
    aOtak:1.02,
    aBabat:10.2,
    aUsusB:9.18,
    aUsusH:4.08,
    aTetelan:7.65,
    aKulit:28.05,
    aDarah:20.4,
    aFeses:20.0,
    aRumen:60.0,
  },
  {
    id:"RPH006",
    sapiId:"S006",
    sapiNama:"SIM-06 (600kg)",
    breed:"Simental",
    gender:"Jantan",
    bbHidup:600,
    hargaBeli:30000000,
    tglPotong:"2026-03-25",
    pctKarkas:56,
    status:"Selesai",
    buyer:"PT Karya Daging Nusantara",
    notes:"Simental jantan feedlot premium",
    hJualHasDalam:225000,
    hJualHasLuar:198000,
    hJualTanjung:183000,
    hJualGandik:160000,
    hJualLamusir:157000,
    hJualSengkel:155000,
    hJualSandung:150000,
    hJualPahaD:150000,
    hJualPahaB:163000,
    hJualIga:168000,
    hJualPunuk:150000,
    hJualLeher:140000,
    hJualEkor:175000,
    hJualTulang:25000,
    bRetribusi:320000,
    bUpah:450000,
    bListrik:95000,
    bKemasan:75000,
    bTransport:400000,
    bLainnya:150000,
    aKarkas:336.0,
    aTulang:60.5,
    aHasDalam:8.65,
    aHasLuar:12.11,
    aTanjung:13.84,
    aGandik:19.03,
    aLamusir:27.69,
    aSengkel:17.3,
    aSandung:22.5,
    aPahaD:24.23,
    aPahaB:25.96,
    aIga:34.61,
    aPunuk:10.38,
    aLeher:10.38,
    aEkor:5.19,
    aLidah:2.47,
    aKepala:9.27,
    aKikil:9.27,
    aHati:8.65,
    aParu:4.94,
    aJantung:2.47,
    aGinjal:1.85,
    aLimpa:1.24,
    aOtak:1.24,
    aBabat:12.36,
    aUsusB:11.12,
    aUsusH:4.94,
    aTetelan:9.27,
    aKulit:33.99,
    aDarah:24.72,
    aFeses:24.0,
    aRumen:72.0,
  },
  {
    id:"RPH007",
    sapiId:"S007",
    sapiNama:"BRA-07 (700kg)",
    breed:"Brahman",
    gender:"Jantan",
    bbHidup:700,
    hargaBeli:35000000,
    tglPotong:"2026-04-08",
    pctKarkas:53,
    status:"Selesai",
    buyer:"Pabrik Bakso Maju Jaya",
    notes:"Brahman jantan besar, banyak tulang",
    hJualHasDalam:222000,
    hJualHasLuar:196000,
    hJualTanjung:181000,
    hJualGandik:159000,
    hJualLamusir:156000,
    hJualSengkel:153000,
    hJualSandung:149000,
    hJualPahaD:149000,
    hJualPahaB:161000,
    hJualIga:166000,
    hJualPunuk:149000,
    hJualLeher:139000,
    hJualEkor:173000,
    hJualTulang:25000,
    bRetribusi:340000,
    bUpah:475000,
    bListrik:100000,
    bKemasan:80000,
    bTransport:425000,
    bLainnya:160000,
    aKarkas:371.0,
    aTulang:66.8,
    aHasDalam:9.18,
    aHasLuar:12.86,
    aTanjung:14.69,
    aGandik:20.2,
    aLamusir:29.38,
    aSengkel:18.36,
    aSandung:23.87,
    aPahaD:25.71,
    aPahaB:27.55,
    aIga:36.73,
    aPunuk:11.02,
    aLeher:11.02,
    aEkor:5.51,
    aLidah:2.77,
    aKepala:10.39,
    aKikil:10.39,
    aHati:9.7,
    aParu:5.54,
    aJantung:2.77,
    aGinjal:2.08,
    aLimpa:1.39,
    aOtak:1.39,
    aBabat:13.86,
    aUsusB:12.47,
    aUsusH:5.54,
    aTetelan:10.39,
    aKulit:38.12,
    aDarah:27.72,
    aFeses:28.0,
    aRumen:84.0,
  },
  {
    id:"RPH008",
    sapiId:"S008",
    sapiNama:"LIM-08 (800kg)",
    breed:"Limousin",
    gender:"Jantan",
    bbHidup:800,
    hargaBeli:40000000,
    tglPotong:"2026-04-22",
    pctKarkas:55,
    status:"Selesai",
    buyer:"Distributor Daging Jatim",
    notes:"Limousin jantan super, karkas sangat berat",
    hJualHasDalam:228000,
    hJualHasLuar:200000,
    hJualTanjung:185000,
    hJualGandik:162000,
    hJualLamusir:159000,
    hJualSengkel:157000,
    hJualSandung:152000,
    hJualPahaD:152000,
    hJualPahaB:165000,
    hJualIga:170000,
    hJualPunuk:152000,
    hJualLeher:142000,
    hJualEkor:178000,
    hJualTulang:26000,
    bRetribusi:360000,
    bUpah:500000,
    bListrik:108000,
    bKemasan:85000,
    bTransport:450000,
    bLainnya:170000,
    aKarkas:440.0,
    aTulang:79.2,
    aHasDalam:11.11,
    aHasLuar:15.55,
    aTanjung:17.78,
    aGandik:24.44,
    aLamusir:35.55,
    aSengkel:22.22,
    aSandung:28.89,
    aPahaD:31.11,
    aPahaB:33.33,
    aIga:44.44,
    aPunuk:13.33,
    aLeher:13.33,
    aEkor:6.67,
    aLidah:3.23,
    aKepala:12.12,
    aKikil:12.12,
    aHati:11.31,
    aParu:6.46,
    aJantung:3.23,
    aGinjal:2.42,
    aLimpa:1.62,
    aOtak:1.62,
    aBabat:16.16,
    aUsusB:14.54,
    aUsusH:6.46,
    aTetelan:12.12,
    aKulit:44.44,
    aDarah:32.32,
    aFeses:32.0,
    aRumen:96.0,
  },
  {
    id:"RPH009",
    sapiId:"S009",
    sapiNama:"SIM-09 (900kg)",
    breed:"Simental",
    gender:"Jantan",
    bbHidup:900,
    hargaBeli:45500000,
    tglPotong:"2026-05-10",
    pctKarkas:56,
    status:"Selesai",
    buyer:"Pasar Induk Kramat Jati",
    notes:"Simental jantan terbesar tahun ini",
    hJualHasDalam:232000,
    hJualHasLuar:203000,
    hJualTanjung:188000,
    hJualGandik:165000,
    hJualLamusir:162000,
    hJualSengkel:160000,
    hJualSandung:155000,
    hJualPahaD:155000,
    hJualPahaB:168000,
    hJualIga:173000,
    hJualPunuk:155000,
    hJualLeher:145000,
    hJualEkor:182000,
    hJualTulang:26000,
    bRetribusi:385000,
    bUpah:530000,
    bListrik:115000,
    bKemasan:90000,
    bTransport:480000,
    bLainnya:180000,
    aKarkas:504.0,
    aTulang:90.7,
    aHasDalam:12.85,
    aHasLuar:17.99,
    aTanjung:20.56,
    aGandik:28.27,
    aLamusir:41.13,
    aSengkel:25.7,
    aSandung:33.42,
    aPahaD:35.99,
    aPahaB:38.56,
    aIga:51.41,
    aPunuk:15.42,
    aLeher:15.42,
    aEkor:7.71,
    aLidah:3.67,
    aKepala:13.77,
    aKikil:13.77,
    aHati:12.85,
    aParu:7.34,
    aJantung:3.67,
    aGinjal:2.75,
    aLimpa:1.84,
    aOtak:1.84,
    aBabat:18.36,
    aUsusB:16.52,
    aUsusH:7.34,
    aTetelan:13.77,
    aKulit:50.49,
    aDarah:36.72,
    aFeses:36.0,
    aRumen:108.0,
  },
  {
    id:"RPH010",
    sapiId:"S010",
    sapiNama:"SIM-10 (1000kg)",
    breed:"Simental",
    gender:"Jantan",
    bbHidup:1000,
    hargaBeli:50000000,
    tglPotong:"2026-05-30",
    pctKarkas:56,
    status:"Selesai",
    buyer:"PT Surya Daging Indonesia",
    notes:"Sapi feedlot impor, bobot rekor 1 ton",
    hJualHasDalam:238000,
    hJualHasLuar:208000,
    hJualTanjung:193000,
    hJualGandik:168000,
    hJualLamusir:165000,
    hJualSengkel:163000,
    hJualSandung:158000,
    hJualPahaD:158000,
    hJualPahaB:172000,
    hJualIga:178000,
    hJualPunuk:158000,
    hJualLeher:148000,
    hJualEkor:188000,
    hJualTulang:27000,
    bRetribusi:420000,
    bUpah:580000,
    bListrik:125000,
    bKemasan:100000,
    bTransport:520000,
    bLainnya:200000,
    aKarkas:560.0,
    aTulang:100.8,
    aHasDalam:14.56,
    aHasLuar:20.38,
    aTanjung:23.3,
    aGandik:32.03,
    aLamusir:46.59,
    aSengkel:29.12,
    aSandung:37.86,
    aPahaD:40.77,
    aPahaB:43.68,
    aIga:58.24,
    aPunuk:17.47,
    aLeher:17.47,
    aEkor:8.74,
    aLidah:4.16,
    aKepala:15.6,
    aKikil:15.6,
    aHati:14.56,
    aParu:8.32,
    aJantung:4.16,
    aGinjal:3.12,
    aLimpa:2.08,
    aOtak:2.08,
    aBabat:20.8,
    aUsusB:18.72,
    aUsusH:8.32,
    aTetelan:15.6,
    aKulit:57.2,
    aDarah:41.6,
    aFeses:40.0,
    aRumen:120.0,
  },
];

const hitungRPH = (rec) => {
  const bb = +rec.bbHidup; if (!bb) return null;
  const hBeli = +rec.hargaBeli || 0;
  const pctK = (+rec.pctKarkas || 55) / 100;
  const karkasEst = bb * pctK;

  const hMap = {
    has_dalam: +(rec.hJualHasDalam||220000), has_luar: +(rec.hJualHasLuar||195000),
    tanjung:   +(rec.hJualTanjung||180000),  gandik:   +(rec.hJualGandik||158000),
    lamusir:   +(rec.hJualLamusir||155000),  sengkel:  +(rec.hJualSengkel||153000),
    sandung:   +(rec.hJualSandung||148000),  paha_depan:+(rec.hJualPahaD||148000),
    paha_blkg: +(rec.hJualPahaB||160000),    iga:      +(rec.hJualIga||165000),
    punuk:     +(rec.hJualPunuk||148000),    leher:    +(rec.hJualLeher||138000),
    ekor:      +(rec.hJualEkor||172000),
  };
  const aMap = {
    has_dalam:rec.aHasDalam, has_luar:rec.aHasLuar, tanjung:rec.aTanjung,
    gandik:rec.aGandik, lamusir:rec.aLamusir, sengkel:rec.aSengkel,
    sandung:rec.aSandung, paha_depan:rec.aPahaD, paha_blkg:rec.aPahaB,
    iga:rec.aIga, punuk:rec.aPunuk, leher:rec.aLeher, ekor:rec.aEkor,
  };
  const hasVal = v => v !== "" && v !== undefined && v !== null;

  const potongan = RPH_STANDAR.potongan_primer.map(p => {
    const est = +((karkasEst * p.pct) / 100).toFixed(2);
    const aktual = hasVal(aMap[p.kode]);
    const berat = aktual ? +aMap[p.kode] : est;
    const harga = hMap[p.kode] || p.harga;
    return { ...p, beratKg: berat, aktual, harga, pend: Math.round(berat * harga) };
  });

  const beratKarkas = hasVal(rec.aKarkas) ? +rec.aKarkas : +karkasEst.toFixed(2);
  const totalDaging = +potongan.reduce((s, p) => s + p.beratKg, 0).toFixed(2);
  const hTulang = +(rec.hJualTulang || 25000);
  const beratTulang = hasVal(rec.aTulang) ? +rec.aTulang : +((karkasEst * RPH_STANDAR.pct_tulang) / 100).toFixed(2);
  const beratSusut = +(beratKarkas - totalDaging - beratTulang).toFixed(2);
  const pendTulang = Math.round(beratTulang * hTulang);

  const bpAMap = {
    "Lidah":rec.aLidah,"Kepala (daging)":rec.aKepala,"Kikil/Kaki (4)":rec.aKikil,
    "Hati":rec.aHati,"Paru-paru":rec.aParu,"Jantung":rec.aJantung,
    "Ginjal":rec.aGinjal,"Limpa":rec.aLimpa,"Otak":rec.aOtak,
    "Babat (Rumen)":rec.aBabat,"Usus Besar":rec.aUsusB,"Usus Halus":rec.aUsusH,
    "Tetelan (Koyor)":rec.aTetelan,"Kulit Sapi":rec.aKulit,"Darah Sapi (L)":rec.aDarah,
  };
  const byProducts = RPH_STANDAR.by_products.map(bp => {
    const aktual = hasVal(bpAMap[bp.nama]);
    const berat = aktual ? +bpAMap[bp.nama] : +((bb * bp.pct_live) / 100).toFixed(2);
    return { ...bp, beratKg: berat, aktual, pend: Math.round(berat * bp.harga) };
  });

  const bFeses = hasVal(rec.aFeses) ? +rec.aFeses : +(bb * 4 / 100).toFixed(1);
  const bRumen = hasVal(rec.aRumen) ? +rec.aRumen : +(bb * 12 / 100).toFixed(1);

  const biayaOps = (+(rec.bRetribusi||300000))+(+(rec.bUpah||425000))+(+(rec.bListrik||90000))+(+(rec.bKemasan||70000))+(+(rec.bTransport||375000))+(+(rec.bLainnya||140000));
  const totalBiaya = hBeli + biayaOps;

  const pendDaging = potongan.reduce((s, p) => s + p.pend, 0);
  const pendByP    = byProducts.reduce((s, b) => s + b.pend, 0);
  const pendTotal  = pendDaging + pendTulang + pendByP;
  const profit     = pendTotal - totalBiaya;
  const roi        = totalBiaya > 0 ? ((profit / totalBiaya) * 100).toFixed(1) : "0";
  const hppPerKg   = totalDaging > 0 ? Math.round(totalBiaya / totalDaging) : 0;
  const mbr        = beratTulang > 0 ? (totalDaging / beratTulang).toFixed(2) : "—";
  const hasAktual  = Object.keys(rec).some(k => k.startsWith("a") && hasVal(rec[k]) && rec[k] !== 0);

  return {
    bb, beratKarkas, pctKarkas: pctK * 100, totalDaging, beratTulang, beratSusut,
    pctSusut: beratKarkas > 0 ? +((beratSusut / beratKarkas) * 100).toFixed(1) : 0,
    potongan, byProducts, bFeses, bRumen,
    biayaOps, totalBiaya, hBeli,
    pendDaging, pendTulang, pendByP, pendTotal,
    profit, roi, hppPerKg, mbr, hasAktual,
    biaya: { retribusi:+(rec.bRetribusi||300000), upah:+(rec.bUpah||425000), listrik:+(rec.bListrik||90000), kemasan:+(rec.bKemasan||70000), transport:+(rec.bTransport||375000), lainnya:+(rec.bLainnya||140000) },
  };
};

/* ================================================================
   PageRPHDomba — Halaman RPH Domba/Kambing
================================================================ */

const initialRphDombaRecords = [
  {id:"RPHD001",dombaId:"D001",dombaNama:"Garut-J-01 (20kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:20,hargaBeli:1600000,tglPotong:"2026-01-08",pctKarkas:50,status:"Selesai",buyer:"Warung Gule Pak Asep",notes:"Domba muda, daging empuk",
   hJualGigot:130000,hJualShoulder:118000,hJualRack:145000,hJualLoin:138000,hJualBreast:95000,hJualNeck:88000,hJualShank:92000,hJualTulang:18000,
   bRetribusi:60000,bUpah:90000,bListrik:22000,bKemasan:18000,bTransport:75000,bLainnya:35000,
   aKarkas:10.1,aTulang:2.2,aGigot:3.0,aShoulder:2.0,aRack:1.2,aLoin:1.0,aBreast:1.2,aNeck:0.8,aShank:0.8,
   aHati:0.4,aParu:0.25,aJantung:0.1,aGinjal:0.08,aLimpa:0.06,aOtak:0.16,
   aBabat:0.5,aUsus:0.3,aTetelan:0.2,aKepala:1.0,aKaki:0.5,aKulit:1.6,aDarah:0.7,aEkorGemuk:0,
   aFeses:0.8,aRumen:2.4},

  {id:"RPHD002",dombaId:"D004",dombaNama:"Lokal-J-04 (25kg)",breed:"Domba Lokal",gender:"Jantan",
   bbHidup:25,hargaBeli:1900000,tglPotong:"2026-01-20",pctKarkas:46,status:"Selesai",buyer:"Aqiqah Al-Barakah",notes:"Aqiqah anak laki-laki",
   hJualGigot:125000,hJualShoulder:112000,hJualRack:138000,hJualLoin:130000,hJualBreast:90000,hJualNeck:82000,hJualShank:87000,hJualTulang:16000,
   bRetribusi:65000,bUpah:95000,bListrik:24000,bKemasan:19000,bTransport:80000,bLainnya:37000,
   aKarkas:"",aTulang:"",aGigot:"",aShoulder:"",aRack:"",aLoin:"",aBreast:"",aNeck:"",aShank:"",
   aHati:"",aParu:"",aJantung:"",aGinjal:"",aLimpa:"",aOtak:"",
   aBabat:"",aUsus:"",aTetelan:"",aKepala:"",aKaki:"",aKulit:"",aDarah:"",aEkorGemuk:"",
   aFeses:"",aRumen:""},

  {id:"RPHD003",dombaId:"",dombaNama:"Garut-J (30kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:30,hargaBeli:2500000,tglPotong:"2026-02-05",pctKarkas:50,status:"Selesai",buyer:"Catering Syukuran Bu Hj. Sari",notes:"Syukuran pernikahan",
   hJualGigot:130000,hJualShoulder:118000,hJualRack:145000,hJualLoin:138000,hJualBreast:95000,hJualNeck:88000,hJualShank:92000,hJualTulang:18000,
   bRetribusi:75000,bUpah:110000,bListrik:27000,bKemasan:21000,bTransport:90000,bLainnya:40000,
   aKarkas:15.1,aTulang:3.3,aGigot:4.5,aShoulder:3.0,aRack:1.8,aLoin:1.5,aBreast:1.8,aNeck:1.2,aShank:1.2,
   aHati:0.6,aParu:0.36,aJantung:0.15,aGinjal:0.12,aLimpa:0.09,aOtak:0.24,
   aBabat:0.75,aUsus:0.45,aTetelan:0.30,aKepala:1.5,aKaki:0.75,aKulit:2.4,aDarah:1.05,aEkorGemuk:0,
   aFeses:1.2,aRumen:3.6},

  {id:"RPHD004",dombaId:"",dombaNama:"Garut Super (35kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:35,hargaBeli:3200000,tglPotong:"2026-02-20",pctKarkas:50,status:"Selesai",buyer:"RPH Pasar Cibadak",notes:"Domba garut kualitas A",
   hJualGigot:132000,hJualShoulder:120000,hJualRack:148000,hJualLoin:140000,hJualBreast:97000,hJualNeck:90000,hJualShank:94000,hJualTulang:19000,
   bRetribusi:78000,bUpah:115000,bListrik:28000,bKemasan:22000,bTransport:95000,bLainnya:42000,
   aKarkas:"",aTulang:"",aGigot:"",aShoulder:"",aRack:"",aLoin:"",aBreast:"",aNeck:"",aShank:"",
   aHati:"",aParu:"",aJantung:"",aGinjal:"",aLimpa:"",aOtak:"",
   aBabat:"",aUsus:"",aTetelan:"",aKepala:"",aKaki:"",aKulit:"",aDarah:"",aEkorGemuk:"",
   aFeses:"",aRumen:""},

  {id:"RPHD005",dombaId:"D002",dombaNama:"Garut-J-02 (40kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:40,hargaBeli:3800000,tglPotong:"2026-03-10",pctKarkas:50,status:"Selesai",buyer:"Jagal H. Udin",notes:"Domba jantan dewasa, karkas sangat baik",
   hJualGigot:135000,hJualShoulder:122000,hJualRack:150000,hJualLoin:142000,hJualBreast:98000,hJualNeck:91000,hJualShank:95000,hJualTulang:19000,
   bRetribusi:80000,bUpah:120000,bListrik:30000,bKemasan:25000,bTransport:100000,bLainnya:45000,
   aKarkas:20.2,aTulang:4.5,aGigot:6.1,aShoulder:4.0,aRack:2.4,aLoin:2.0,aBreast:2.4,aNeck:1.6,aShank:1.6,
   aHati:0.8,aParu:0.48,aJantung:0.20,aGinjal:0.16,aLimpa:0.12,aOtak:0.32,
   aBabat:1.0,aUsus:0.6,aTetelan:0.40,aKepala:2.0,aKaki:1.0,aKulit:3.2,aDarah:1.4,aEkorGemuk:0,
   aFeses:1.6,aRumen:4.8},

  {id:"RPHD006",dombaId:"",dombaNama:"Ekor Gemuk (40kg)",breed:"Domba Ekor Gemuk",gender:"Jantan",
   bbHidup:40,hargaBeli:4000000,tglPotong:"2026-03-25",pctKarkas:51,status:"Selesai",buyer:"Restoran Kambing Bakar Mas Bambang",notes:"Ekor gemuk sangat laku, lemak ekor premium",
   hJualGigot:140000,hJualShoulder:125000,hJualRack:155000,hJualLoin:148000,hJualBreast:102000,hJualNeck:93000,hJualShank:97000,hJualTulang:20000,
   bRetribusi:82000,bUpah:122000,bListrik:31000,bKemasan:26000,bTransport:102000,bLainnya:47000,
   aKarkas:20.5,aTulang:4.5,aGigot:6.2,aShoulder:4.1,aRack:2.5,aLoin:2.0,aBreast:2.5,aNeck:1.6,aShank:1.6,
   aHati:0.8,aParu:0.48,aJantung:0.20,aGinjal:0.16,aLimpa:0.12,aOtak:0.32,
   aBabat:1.0,aUsus:0.6,aTetelan:0.40,aKepala:2.0,aKaki:1.0,aKulit:3.2,aDarah:1.4,aEkorGemuk:1.2,
   aFeses:1.6,aRumen:4.8},

  {id:"RPHD007",dombaId:"",dombaNama:"Kambing PE (45kg)",breed:"Kambing PE",gender:"Jantan",
   bbHidup:45,hargaBeli:4500000,tglPotong:"2026-04-08",pctKarkas:48,status:"Selesai",buyer:"Gule & Tongseng Pak Haji",notes:"Kambing PE jantan, gemuk",
   hJualGigot:128000,hJualShoulder:115000,hJualRack:142000,hJualLoin:135000,hJualBreast:93000,hJualNeck:86000,hJualShank:90000,hJualTulang:18000,
   bRetribusi:82000,bUpah:122000,bListrik:31000,bKemasan:25000,bTransport:105000,bLainnya:45000,
   aKarkas:"",aTulang:"",aGigot:"",aShoulder:"",aRack:"",aLoin:"",aBreast:"",aNeck:"",aShank:"",
   aHati:"",aParu:"",aJantung:"",aGinjal:"",aLimpa:"",aOtak:"",
   aBabat:"",aUsus:"",aTetelan:"",aKepala:"",aKaki:"",aKulit:"",aDarah:"",aEkorGemuk:"",
   aFeses:"",aRumen:""},

  {id:"RPHD008",dombaId:"",dombaNama:"Garut Showdom (50kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:50,hargaBeli:6000000,tglPotong:"2026-04-22",pctKarkas:50,status:"Selesai",buyer:"Hotel Sari Pan Pacific",notes:"Domba showdom afkir, daging berkualitas premium",
   hJualGigot:142000,hJualShoulder:128000,hJualRack:158000,hJualLoin:150000,hJualBreast:105000,hJualNeck:95000,hJualShank:99000,hJualTulang:21000,
   bRetribusi:85000,bUpah:128000,bListrik:32000,bKemasan:27000,bTransport:110000,bLainnya:50000,
   aKarkas:25.2,aTulang:5.6,aGigot:7.6,aShoulder:5.0,aRack:3.0,aLoin:2.5,aBreast:3.0,aNeck:2.0,aShank:2.0,
   aHati:1.0,aParu:0.60,aJantung:0.25,aGinjal:0.20,aLimpa:0.15,aOtak:0.40,
   aBabat:1.25,aUsus:0.75,aTetelan:0.50,aKepala:2.5,aKaki:1.25,aKulit:4.0,aDarah:1.75,aEkorGemuk:0,
   aFeses:2.0,aRumen:6.0},

  {id:"RPHD009",dombaId:"",dombaNama:"Merino (55kg)",breed:"Domba Merino",gender:"Jantan",
   bbHidup:55,hargaBeli:7000000,tglPotong:"2026-05-10",pctKarkas:47,status:"Selesai",buyer:"PT Daging Nusantara",notes:"Merino afkir setelah 3x cukur wol",
   hJualGigot:136000,hJualShoulder:122000,hJualRack:150000,hJualLoin:143000,hJualBreast:98000,hJualNeck:90000,hJualShank:94000,hJualTulang:19000,
   bRetribusi:88000,bUpah:132000,bListrik:33000,bKemasan:28000,bTransport:115000,bLainnya:52000,
   aKarkas:"",aTulang:"",aGigot:"",aShoulder:"",aRack:"",aLoin:"",aBreast:"",aNeck:"",aShank:"",
   aHati:"",aParu:"",aJantung:"",aGinjal:"",aLimpa:"",aOtak:"",
   aBabat:"",aUsus:"",aTetelan:"",aKepala:"",aKaki:"",aKulit:"",aDarah:"",aEkorGemuk:"",
   aFeses:"",aRumen:""},

  {id:"RPHD010",dombaId:"",dombaNama:"Garut Juara (60kg)",breed:"Domba Garut",gender:"Jantan",
   bbHidup:60,hargaBeli:9000000,tglPotong:"2026-05-30",pctKarkas:50,status:"Selesai",buyer:"Catering Royal Gedung Sate",notes:"Domba Garut jantan terbesar, mantan kontes",
   hJualGigot:148000,hJualShoulder:132000,hJualRack:165000,hJualLoin:155000,hJualBreast:110000,hJualNeck:98000,hJualShank:102000,hJualTulang:22000,
   bRetribusi:90000,bUpah:138000,bListrik:35000,bKemasan:30000,bTransport:120000,bLainnya:55000,
   aKarkas:30.2,aTulang:6.7,aGigot:9.1,aShoulder:6.0,aRack:3.6,aLoin:3.0,aBreast:3.6,aNeck:2.4,aShank:2.4,
   aHati:1.2,aParu:0.72,aJantung:0.30,aGinjal:0.24,aLimpa:0.18,aOtak:0.48,
   aBabat:1.5,aUsus:0.9,aTetelan:0.60,aKepala:3.0,aKaki:1.5,aKulit:4.8,aDarah:2.1,aEkorGemuk:0,
   aFeses:2.4,aRumen:7.2},
];

/* ================================================================
   hitungRPHDomba — kalkulasi dari record domba
================================================================ */

const hitungRPHDomba = (rec) => {
  const bb = +rec.bbHidup; if (!bb) return null;
  const hBeli = +rec.hargaBeli || 0;
  const pctK  = (+rec.pctKarkas || 48) / 100;
  const karkasEst = bb * pctK;
  const S = RPH_STANDAR_DOMBA;
  const hasVal = v => v !== "" && v !== undefined && v !== null;

  const hMap = {
    gigot:+(rec.hJualGigot||130000), shoulder:+(rec.hJualShoulder||118000),
    rack:+(rec.hJualRack||145000),   loin:+(rec.hJualLoin||138000),
    breast:+(rec.hJualBreast||95000),neck:+(rec.hJualNeck||88000),
    shank:+(rec.hJualShank||92000),
  };
  const aMap = {
    gigot:rec.aGigot, shoulder:rec.aShoulder, rack:rec.aRack,
    loin:rec.aLoin, breast:rec.aBreast, neck:rec.aNeck, shank:rec.aShank,
  };
  const potongan = S.potongan_primer.map(p => {
    const est = +((karkasEst * p.pct) / 100).toFixed(2);
    const aktual = hasVal(aMap[p.kode]);
    const berat  = aktual ? +aMap[p.kode] : est;
    const harga  = hMap[p.kode] || p.harga;
    return { ...p, beratKg:berat, aktual, harga, pend:Math.round(berat*harga) };
  });

  const beratKarkas = hasVal(rec.aKarkas) ? +rec.aKarkas : +karkasEst.toFixed(2);
  const totalDaging = +potongan.reduce((s,p)=>s+p.beratKg,0).toFixed(2);
  const hTulang     = +(rec.hJualTulang||18000);
  const beratTulang = hasVal(rec.aTulang) ? +rec.aTulang : +((karkasEst * S.pct_tulang)/100).toFixed(2);
  const beratSusut  = +(beratKarkas - totalDaging - beratTulang).toFixed(2);
  const pendTulang  = Math.round(beratTulang * hTulang);

  const bpAMap = {
    "Kepala Domba":rec.aKepala,"Kaki (4)":rec.aKaki,"Hati":rec.aHati,
    "Paru-paru":rec.aParu,"Jantung":rec.aJantung,"Ginjal":rec.aGinjal,
    "Limpa":rec.aLimpa,"Otak":rec.aOtak,"Babat/Rumen":rec.aBabat,
    "Usus":rec.aUsus,"Tetelan":rec.aTetelan,"Kulit Domba":rec.aKulit,
    "Darah (L)":rec.aDarah,"Ekor Gemuk":rec.aEkorGemuk,
  };
  const byProducts = S.by_products.map(bp => {
    const aktual = hasVal(bpAMap[bp.nama]);
    const berat  = aktual ? +bpAMap[bp.nama] : +((bb * bp.pct_live)/100).toFixed(2);
    return { ...bp, beratKg:berat, aktual, pend:Math.round(berat*bp.harga) };
  });

  const bFeses = hasVal(rec.aFeses)  ? +rec.aFeses  : +(bb*4/100).toFixed(1);
  const bRumen = hasVal(rec.aRumen)  ? +rec.aRumen  : +(bb*12/100).toFixed(1);

  const biayaOps = (+(rec.bRetribusi||80000))+(+(rec.bUpah||120000))+(+(rec.bListrik||30000))+(+(rec.bKemasan||25000))+(+(rec.bTransport||100000))+(+(rec.bLainnya||45000));
  const totalBiaya  = hBeli + biayaOps;
  const pendDaging  = potongan.reduce((s,p)=>s+p.pend,0);
  const pendByP     = byProducts.reduce((s,b)=>s+b.pend,0);
  const pendTotal   = pendDaging + pendTulang + pendByP;
  const profit      = pendTotal - totalBiaya;
  const roi         = totalBiaya > 0 ? ((profit/totalBiaya)*100).toFixed(1) : "0";
  const hppPerKg    = totalDaging > 0 ? Math.round(totalBiaya/totalDaging) : 0;
  const mbr         = beratTulang > 0 ? (totalDaging/beratTulang).toFixed(2) : "—";
  const hasAktual   = Object.keys(rec).some(k => k.startsWith("a") && hasVal(rec[k]) && rec[k] !== 0);

  return {
    bb, beratKarkas, pctKarkas:pctK*100, totalDaging, beratTulang, beratSusut,
    pctSusut:beratKarkas>0?+(beratSusut/beratKarkas*100).toFixed(1):0,
    potongan, byProducts, bFeses, bRumen,
    biayaOps, totalBiaya, hBeli,
    pendDaging, pendTulang, pendByP, pendTotal,
    profit, roi, hppPerKg, mbr, hasAktual,
    biaya:{retribusi:+(rec.bRetribusi||80000),upah:+(rec.bUpah||120000),
           listrik:+(rec.bListrik||30000),kemasan:+(rec.bKemasan||25000),
           transport:+(rec.bTransport||100000),lainnya:+(rec.bLainnya||45000)},
  };
};


const PageRPHDomba = ({ records=[], setRecords, sheep=[] }) => {
  const AC = "#a3e635";
  const [tab, setTab]             = useState("kalkulator");
  const [form, setF0]             = useState(null);
  const [preview, setPreview]     = useState(null);
  const [activeId, setActiveId]   = useState(null);
  const [subTab, setSubTab]       = useState("ilmiah");

  const S = RPH_STANDAR_DOMBA;

  const blankD = {
    dombaId:"", dombaNama:"", breed:"Domba Garut", gender:"Jantan",
    bbHidup:"", hargaBeli:"", tglPotong:new Date().toISOString().split("T")[0],
    pctKarkas:50, status:"Selesai", buyer:"", notes:"",
    hJualGigot:130000, hJualShoulder:118000, hJualRack:145000,
    hJualLoin:138000, hJualBreast:95000, hJualNeck:88000, hJualShank:92000,
    hJualTulang:18000,
    bRetribusi:80000, bUpah:120000, bListrik:30000,
    bKemasan:25000, bTransport:100000, bLainnya:45000,
    aKarkas:"", aTulang:"",
    aGigot:"", aShoulder:"", aRack:"", aLoin:"", aBreast:"", aNeck:"", aShank:"",
    aHati:"", aParu:"", aJantung:"", aGinjal:"", aLimpa:"", aOtak:"",
    aBabat:"", aUsus:"", aTetelan:"",
    aKepala:"", aKaki:"", aKulit:"", aDarah:"", aEkorGemuk:"",
    aFeses:"", aRumen:"",
  };

  const f = form || blankD;
  const setF = patch => {
    const nf = { ...f, ...patch };
    setF0(nf);
    setPreview(hitungRPHDomba(nf));
  };

  const saveRecord = () => {
    if (!f.bbHidup || !f.hargaBeli) return;
    const d = sheep.find(s => s.id === f.dombaId);
    const id = "RPHD" + String(records.length + 1).padStart(3, "0");
    setRecords([{ id, ...f, bbHidup:+f.bbHidup, hargaBeli:+f.hargaBeli, pctKarkas:+f.pctKarkas, dombaNama:d?d.name:f.dombaNama }, ...records]);
    setF0(null); setPreview(null);
  };

  // Cetak laporan domba
  const cetakLaporanDomba = (rec, c) => {
    const rp = n => "Rp " + new Intl.NumberFormat("id-ID").format(Math.round(n||0));
    const rowsPot = c.potongan.map((p,i) =>
      "<tr><td>"+(i+1)+"</td><td><b>"+p.nama+"</b></td><td>"+p.grade+"</td><td><b>"+p.beratKg+" kg</b></td><td>"+(p.beratKg/c.bb*100).toFixed(2)+"%</td><td>"+rp(p.harga)+"</td><td class='green'>"+rp(p.pend)+"</td><td><span class='"+(p.aktual?"badge-a":"badge-e")+"'>"+(p.aktual?"Aktual":"Est.")+"</span></td></tr>"
    ).join("");
    const rowsByP = c.byProducts.map(b =>
      "<tr><td><b>"+b.nama+"</b></td><td>"+b.kat+"</td><td>"+b.beratKg+" kg</td><td>"+(b.beratKg/c.bb*100).toFixed(2)+"%</td><td>"+rp(b.harga)+"</td><td class='green'>"+rp(b.pend)+"</td><td><span class='"+(b.aktual?"badge-a":"badge-e")+"'>"+(b.aktual?"Aktual":"Est.")+"</span></td></tr>"
    ).join("");
    const infoCards = [["Nama",rec.dombaNama||"—"],["Ras",rec.breed],["JK",rec.gender],["BH",c.bb+" kg"],["% Karkas",rec.pctKarkas+"%"],["Karkas",c.beratKarkas+" kg"],["Tgl Potong",rec.tglPotong],["Pembeli",rec.buyer||"—"]].map(([k,v])=>"<div class='s'><div class='v'>"+v+"</div><div class='k'>"+k+"</div></div>").join("");
    const css = "*{margin:0;padding:0;box-sizing:border-box}body{font-family:'Segoe UI',Arial,sans-serif;font-size:11px;color:#111;padding:12mm}h1{font-size:16px;font-weight:800;margin-bottom:3px}h2{font-size:12px;font-weight:700;color:#2d7a00;margin:12px 0 5px;border-bottom:2px solid #2d7a00;padding-bottom:2px}.meta{color:#666;font-size:10px;margin-bottom:8px}.hbox{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:9px 13px;margin-bottom:10px;display:flex;gap:20px;flex-wrap:wrap}.hbox .s{text-align:center}.hbox .v{font-size:15px;font-weight:800;color:#2d7a00}.hbox .k{font-size:9px;color:#888;text-transform:uppercase}table{width:100%;border-collapse:collapse;margin-bottom:9px;font-size:10px}th{background:#2d7a00;color:#fff;padding:5px 7px;text-align:left;font-size:9px;text-transform:uppercase}td{padding:4px 7px;border-bottom:1px solid #eee}tr:nth-child(even)td{background:#fafafa}.tr{font-weight:700;background:#f0f0f0}.g2{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-bottom:9px}.card{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:8px 11px}.card .r{display:flex;justify-content:space-between;padding:3px 0;border-bottom:1px solid #eee;font-size:10px}.green{color:#1a7a1a;font-weight:700}.red{color:#c0392b;font-weight:700}.badge-a{background:#e8f8e8;color:#1a7a1a;border:1px solid #1a7a1a;border-radius:9px;padding:1px 5px;font-size:8px;font-weight:700}.badge-e{background:#fff8dc;color:#b8860b;border:1px solid #daa520;border-radius:9px;padding:1px 5px;font-size:8px;font-weight:700}.ind{display:grid;grid-template-columns:repeat(3,1fr);gap:7px;margin-bottom:9px}.ibox{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:7px 9px;text-align:center}.ibox .v{font-size:14px;font-weight:800;color:#2d7a00}.ibox .k{font-size:8px;color:#888;text-transform:uppercase}.footer{margin-top:14px;padding-top:7px;border-top:1px solid #ddd;color:#999;font-size:9px;text-align:center}@media print{body{padding:8mm}@page{size:A4;margin:8mm}}";
    const indCards = [["Profit",rp(c.profit)],["ROI",c.roi+"%"],["HPP/kg",rp(c.hppPerKg)+"/kg"],["Total Pend.",rp(c.pendTotal)],["DCP",c.pctKarkas+"%"],["MBR",c.mbr+":1"]].map(([k,v])=>"<div class='ibox'><div class='v'>"+v+"</div><div class='k'>"+k+"</div></div>").join("");
    const biayaRows = [["Harga Beli",rp(c.hBeli)],["Retribusi",rp(c.biaya.retribusi)],["Upah Potong",rp(c.biaya.upah)],["Listrik",rp(c.biaya.listrik)],["Kemasan",rp(c.biaya.kemasan)],["Transport",rp(c.biaya.transport)],["Lainnya",rp(c.biaya.lainnya)],["TOTAL BIAYA",rp(c.totalBiaya)]].map(([k,v])=>"<div class='r'><span>"+k+"</span><span class='red'>"+v+"</span></div>").join("");
    const pendRows = [["Daging",rp(c.pendDaging)],["Tulang",rp(c.pendTulang)],["By-Product",rp(c.pendByP)],["TOTAL PEND.",rp(c.pendTotal)],["PROFIT",rp(c.profit)],["ROI",c.roi+"%"]].map(([k,v])=>"<div class='r'><span>"+k+"</span><span class='green'>"+v+"</span></div>").join("");
    const html = ["<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'/><title>Laporan RPH Domba - "+(rec.dombaNama||rec.id)+"</title><style>"+css+"</style></head><body>",
      "<h1>🐑 Laporan Pemotongan Domba/Kambing RPH</h1>",
      "<p class='meta'>ID: "+rec.id+" | Dicetak: "+new Date().toLocaleString("id-ID")+" | Status: "+rec.status+"</p>",
      "<div class='hbox'>"+infoCards+"</div>",
      "<div class='ind'>"+indCards+"</div>",
      "<h2>I. Neraca Bobot (BH = "+c.bb+" kg)</h2>",
      "<table><thead><tr><th>Komponen</th><th>Berat (kg)</th><th>% BH</th><th>Keterangan</th></tr></thead><tbody>",
      [["Karkas",c.beratKarkas,rec.pctKarkas+"%"],["— Daging",c.totalDaging,+(c.totalDaging/c.bb*100).toFixed(1)+"%"],["— Tulang",c.beratTulang,S.pct_tulang+"% karkas"],["— Lemak/Trim",Math.max(0,c.beratSusut).toFixed(1),c.pctSusut+"% karkas"],["Jeroan & Organ",+c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0).toFixed(1),+(c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0)/c.bb*100).toFixed(1)+"%"],["Kulit+Darah",+c.byProducts.filter(b=>b.kat==="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0).toFixed(1),"~11.5% BH"],["Isi Rumen+Usus",c.bRumen,"~12% BH"],["Feses & Urin",c.bFeses,"~4% BH"]].map(([k,v,p])=>"<tr><td><b>"+k+"</b></td><td>"+v+" kg</td><td>"+p+"</td><td></td></tr>").join(""),
      "</tbody></table>",
      "<h2>II. Potongan Daging</h2>",
      "<table><thead><tr><th>No</th><th>Potongan</th><th>Grade</th><th>Berat</th><th>%BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead><tbody>",
      rowsPot,
      "<tr class='tr'><td colspan='3'>TOTAL DAGING</td><td>"+c.totalDaging+" kg</td><td>"+(c.totalDaging/c.bb*100).toFixed(2)+"%</td><td></td><td class='green'>"+rp(c.pendDaging)+"</td><td></td></tr>",
      "<tr><td colspan='3'>Tulang</td><td>"+c.beratTulang+" kg</td><td>"+(c.beratTulang/c.bb*100).toFixed(2)+"%</td><td>"+rp(rec.hJualTulang||18000)+"</td><td>"+rp(c.pendTulang)+"</td><td></td></tr>",
      "</tbody></table>",
      "<h2>III. Jeroan & By-Product</h2>",
      "<table><thead><tr><th>Produk</th><th>Kategori</th><th>Berat</th><th>%BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead><tbody>",
      rowsByP,
      "<tr class='tr'><td colspan='2'>TOTAL BY-PRODUCT</td><td>"+c.byProducts.reduce((s,b)=>+(s+b.beratKg).toFixed(2),0)+" kg</td><td></td><td></td><td class='green'>"+rp(c.pendByP)+"</td><td></td></tr>",
      "</tbody></table>",
      "<div class='g2'><div class='card'><b>Biaya Modal</b>"+biayaRows+"</div><div class='card'><b>Pendapatan</b>"+pendRows+"</div></div>",
      rec.notes?"<p style='background:#f9f9f9;padding:8px 11px;border-radius:5px;border:1px solid #ddd;font-size:11px;margin-bottom:9px'><b>Catatan:</b> "+rec.notes+"</p>":"",
      "<div class='footer'><b>TernakPro RPH Domba/Kambing</b> | "+rec.id+" | "+rec.tglPotong+"</div>",
      "<script>window.onload=function(){setTimeout(function(){window.print()},300)}</script>",
      "</body></html>"].join("");
    const blob = new Blob([html],{type:"text/html"});
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href=url; a.target="_blank"; a.click();
    setTimeout(()=>URL.revokeObjectURL(url),5000);
  };

  // ── UI Helpers ──
  const Inp = ({label,value,onChange,type="text",options,small,placeholder,hl}) => (
    <div>
      <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:3}}>{label}</label>
      {options ? (
        <select value={value||""} onChange={e=>onChange(e.target.value)} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:small?"5px 8px":"8px 11px",color:"#e2e4f0",fontSize:small?11:13,width:"100%",outline:"none"}}>
          {options.map(o=><option key={o.v??o} value={o.v??o}>{o.l??o}</option>)}
        </select>
      ) : (
        <input type={type} value={value||""} onChange={e=>onChange(e.target.value)} placeholder={placeholder||""} style={{background:"#13161f",border:"1px solid "+(hl&&value?"#a3e63540":"#252535"),borderRadius:8,padding:small?"5px 8px":"8px 11px",color:"#e2e4f0",fontSize:small?11:13,width:"100%",outline:"none",boxSizing:"border-box"}}/>
      )}
    </div>
  );

  const BarChartD = ({data,title,height=110}) => {
    const max = Math.max(...data.map(d=>d.value||0),1);
    const W=420; const bw=Math.floor((W-14)/data.length)-2;
    return (
      <div style={{background:"#0a0c16",borderRadius:10,padding:"10px 12px"}}>
        <div style={{color:"#9097a8",fontSize:10,fontWeight:700,marginBottom:6}}>{title}</div>
        <svg width="100%" viewBox={"0 0 "+W+" "+(height+38)} style={{overflow:"visible"}}>
          {data.map((d,i)=>{
            const bh=Math.max(2,(d.value/max)*height);
            const x=7+i*(bw+2); const y=height-bh+2;
            const col=d.color||AC;
            return (<g key={i}>
              <rect x={x} y={y} width={bw} height={bh} rx={2} fill={col} opacity={0.82}/>
              {d.value>0&&<text x={x+bw/2} y={y-2} textAnchor="middle" fill={col} fontSize={6} fontWeight="700">{d.label2||""}</text>}
              <text x={x+bw/2} y={height+20} textAnchor="middle" fill="#555a6a" fontSize={6.5} transform={"rotate(-38,"+(x+bw/2)+","+(height+20)+")"}>{d.label.length>9?d.label.slice(0,8)+"…":d.label}</text>
            </g>);
          })}
          <line x1={7} y1={height+2} x2={W-7} y2={height+2} stroke="#252535" strokeWidth={1}/>
        </svg>
      </div>
    );
  };

  const gradeCD = g => g==="Premium"?"#a3e635":g==="Superior"?"#3b82f6":"#9097a8";
  const thSD = {padding:"8px 10px",color:"#555a6a",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap",borderBottom:"1px solid #1c1e2b"};
  const tdSD = (col="#e2e4f0",bold=false) => ({padding:"8px 10px",color:col,fontWeight:bold?700:400,fontSize:12});
  const BadgeD = ({isA}) => (
    <span style={{background:isA?"#22c55e18":"#f5c84218",color:isA?"#22c55e":"#f5c842",border:"1px solid "+(isA?"#22c55e30":"#f5c84230"),borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>{isA?"✅":"📊"}</span>
  );

  const totalPend = records.reduce((s,r)=>{const c=hitungRPHDomba(r);return c?s+c.pendTotal:s;},0);
  const totalProf = records.reduce((s,r)=>{const c=hitungRPHDomba(r);return c?s+c.profit:s;},0);

  return (
    <div style={{display:"flex",flexDirection:"column",gap:16}}>
      {/* STAT CARDS */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))",gap:12}}>
        {[["Catatan Potong",records.length+" ekor",AC,"🐑"],
          ["Total Pendapatan","Rp "+(totalPend/1e6).toFixed(1)+"jt","#3b82f6","💰"],
          ["Total Profit","Rp "+(totalProf/1e6).toFixed(1)+"jt",totalProf>=0?"#22c55e":"#ef4444","📊"],
          ["Domba Siap Potong",sheep.filter(d=>d.status==="Siap Jual").length+" ekor","#f5c842","🐑"],
        ].map(([l,v,c,e])=>(
          <div key={l} style={{background:c+"0c",border:"1px solid "+c+"25",borderRadius:13,padding:"14px 16px",position:"relative",overflow:"hidden"}}>
            <div style={{position:"absolute",top:10,right:12,fontSize:22,opacity:0.13}}>{e}</div>
            <div style={{fontSize:10,color:"#555a6a",textTransform:"uppercase",letterSpacing:1.5,fontWeight:700,marginBottom:4}}>{l}</div>
            <div style={{fontSize:18,fontWeight:800,color:c}}>{v}</div>
            <div style={{position:"absolute",bottom:0,left:0,right:0,height:2,background:"linear-gradient(90deg,"+c+",transparent)"}}/>
          </div>
        ))}
      </div>

      {/* TABS */}
      <div style={{display:"flex",borderBottom:"1px solid #1c1e2b"}}>
        {[{id:"kalkulator",l:"🔢 Kalkulator"},{id:"riwayat",l:"📋 Riwayat Pemotongan"},{id:"standar",l:"📊 Tabel Standar"}].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)} style={{background:"none",border:"none",borderBottom:"2px solid "+(tab===t.id?AC:"transparent"),color:tab===t.id?AC:"#555a6a",padding:"8px 18px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>{t.l}</button>
        ))}
      </div>

      {/* ═══ TAB KALKULATOR ═══ */}
      {tab==="kalkulator" && (
        <div style={{display:"grid",gridTemplateColumns:"360px 1fr",gap:18,alignItems:"start"}}>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:18,display:"flex",flexDirection:"column",gap:13,maxHeight:"88vh",overflowY:"auto"}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:15,fontWeight:700}}>🐑 Data Domba/Kambing</div>
            <div>
              <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:4}}>Pilih Domba (opsional)</label>
              <select value={f.dombaId} onChange={e=>{
                const d=sheep.find(s=>s.id===e.target.value);
                const pct=d?(S.persen_karkas[d.breed]||S.persen_karkas.default)[d.gender==="Jantan"?"jantan":"betina"]:f.pctKarkas;
                setF({dombaId:e.target.value,dombaNama:d?d.name:"",breed:d?d.breed:f.breed,gender:d?d.gender:f.gender,bbHidup:d?d.weightCurrent:f.bbHidup,hargaBeli:d?d.priceBuy:f.hargaBeli,pctKarkas:pct});
              }} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:"8px 11px",color:"#e2e4f0",fontSize:13,width:"100%"}}>
                <option value="">-- Pilih atau isi manual --</option>
                {sheep.map(d=><option key={d.id} value={d.id}>{d.name} ({d.breed}) — {d.weightCurrent}kg</option>)}
              </select>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              <Inp label="Bobot Hidup (kg)" value={f.bbHidup} onChange={v=>setF({bbHidup:v})} type="number"/>
              <Inp label="% Karkas" value={f.pctKarkas} onChange={v=>setF({pctKarkas:v})} type="number"/>
              <Inp label="Ras" value={f.breed} onChange={v=>setF({breed:v})} options={["Domba Garut","Domba Lokal","Domba Merino","Domba Ekor Gemuk","Kambing PE","Kambing Lokal"]}/>
              <Inp label="Jenis Kelamin" value={f.gender} onChange={v=>setF({gender:v})} options={["Jantan","Betina"]}/>
              <Inp label="Harga Beli (Rp)" value={f.hargaBeli} onChange={v=>setF({hargaBeli:v})} type="number"/>
              <Inp label="Tanggal Potong" value={f.tglPotong} onChange={v=>setF({tglPotong:v})} type="date"/>
              <Inp label="Pembeli" value={f.buyer} onChange={v=>setF({buyer:v})}/>
              <Inp label="Status" value={f.status} onChange={v=>setF({status:v})} options={["Selesai","Proses","Antrian"]}/>
            </div>
            {/* Biaya */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>🏭 Biaya RPH</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                {[["Retribusi","bRetribusi"],["Upah Potong","bUpah"],["Listrik & Air","bListrik"],["Kemasan","bKemasan"],["Transportasi","bTransport"],["Lainnya","bLainnya"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small/>
                ))}
              </div>
            </div>
            {/* Harga Jual */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#3b82f6",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>💲 Harga Jual Daging/kg</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                {[["Gigot/Kaki Belakang","hJualGigot"],["Bahu/Shoulder","hJualShoulder"],["Iga/Rack","hJualRack"],["Loin/Punggung","hJualLoin"],["Dada/Breast","hJualBreast"],["Leher/Neck","hJualNeck"],["Betis/Shank","hJualShank"],["Tulang","hJualTulang"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small/>
                ))}
              </div>
            </div>
            {/* Berat Fisik */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:4}}>📏 Berat Fisik Nyata (Opsional)</div>
              <div style={{fontSize:10,color:"#555a6a",marginBottom:9}}>Isi hasil timbangan. Kosong = estimasi %.</div>
              <div style={{color:"#a3e635",fontSize:10,fontWeight:700,marginBottom:5}}>Karkas & Potongan (kg)</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:5,marginBottom:9}}>
                {[["Karkas","aKarkas"],["Tulang","aTulang"],["Gigot","aGigot"],["Shoulder","aShoulder"],["Iga/Rack","aRack"],["Loin","aLoin"],["Dada/Breast","aBreast"],["Leher","aNeck"],["Betis/Shank","aShank"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small placeholder="kg" hl/>
                ))}
              </div>
              <div style={{color:"#a855f7",fontSize:10,fontWeight:700,marginBottom:5}}>Jeroan & By-Product (kg)</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:5,marginBottom:9}}>
                {[["Hati","aHati"],["Paru","aParu"],["Jantung","aJantung"],["Ginjal","aGinjal"],["Limpa","aLimpa"],["Otak","aOtak"],["Babat","aBabat"],["Usus","aUsus"],["Tetelan","aTetelan"],["Kepala","aKepala"],["Kaki (4)","aKaki"],["Kulit","aKulit"],["Darah","aDarah"],["Ekor Gemuk","aEkorGemuk"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small placeholder="kg" hl/>
                ))}
              </div>
              <div style={{color:"#555a6a",fontSize:10,fontWeight:700,marginBottom:5}}>Limbah (kg)</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:5}}>
                <Inp label="Isi Rumen+Usus" value={f.aRumen} onChange={v=>setF({aRumen:v})} type="number" small placeholder="kg" hl/>
                <Inp label="Feses & Urin" value={f.aFeses} onChange={v=>setF({aFeses:v})} type="number" small placeholder="kg" hl/>
              </div>
            </div>
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:4}}>Catatan</label>
              <textarea value={f.notes||""} onChange={e=>setF({notes:e.target.value})} rows={2} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:"8px 11px",color:"#e2e4f0",fontSize:12,width:"100%",outline:"none",boxSizing:"border-box",resize:"vertical"}}/>
            </div>
            <button onClick={saveRecord} disabled={!f.bbHidup||!f.hargaBeli} style={{background:(!f.bbHidup||!f.hargaBeli)?"#333":AC,color:(!f.bbHidup||!f.hargaBeli)?"#888":"#0a0c16",border:"none",borderRadius:10,padding:12,cursor:(!f.bbHidup||!f.hargaBeli)?"not-allowed":"pointer",fontWeight:800,fontSize:14,width:"100%"}}>
              💾 Simpan ke Riwayat RPH
            </button>
          </div>

          {/* HASIL KALKULASI */}
          <div style={{display:"flex",flexDirection:"column",gap:13}}>
            {!preview ? (
              <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:48,textAlign:"center",color:"#555a6a",fontSize:13}}>← Isi data domba/kambing di kiri untuk melihat hasil kalkulasi</div>
            ) : (
              <>
                {/* Ringkasan */}
                <div style={{background:"#0f1118",border:"1px solid "+AC+"28",borderRadius:14,padding:17}}>
                  <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:15,marginBottom:12}}>📊 Ringkasan RPH Domba</div>
                  <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(120px,1fr))",gap:9}}>
                    {[["Berat Karkas",preview.beratKarkas+" kg","#a3e635",preview.pctKarkas+"% dari BH"],
                      ["Total Daging",preview.totalDaging+" kg","#22c55e",""],
                      ["Tulang",preview.beratTulang+" kg","#9097a8",""],
                      ["Lemak/Trim",Math.max(0,preview.beratSusut).toFixed(1)+" kg","#555a6a",""],
                      ["HPP/kg","Rp "+preview.hppPerKg.toLocaleString("id-ID"),"#f59e0b","BEP"],
                      ["Total Biaya","Rp "+(preview.totalBiaya/1e6).toFixed(2)+"jt","#ef4444",""],
                      ["Total Pend.","Rp "+(preview.pendTotal/1e6).toFixed(2)+"jt","#3b82f6",""],
                      ["PROFIT","Rp "+(preview.profit/1e6).toFixed(2)+"jt",preview.profit>=0?"#22c55e":"#ef4444",""],
                      ["ROI",preview.roi+"%",+preview.roi>=15?"#22c55e":"#f59e0b",""],
                      ["MBR",preview.mbr+":1","#a855f7","Meat:Bone"],
                    ].map(([l,v,c,s])=>(
                      <div key={l} style={{background:"#ffffff07",borderRadius:9,padding:"9px 11px"}}>
                        <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,marginBottom:3}}>{l}</div>
                        <div style={{color:c,fontWeight:700,fontSize:14,lineHeight:1.2}}>{v}</div>
                        {s&&<div style={{fontSize:10,color:"#555a6a",marginTop:2}}>{s}</div>}
                      </div>
                    ))}
                  </div>
                </div>
                {/* Breakdown pend */}
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:9}}>
                  {[["🥩 Daging",preview.pendDaging,"#22c55e"],["🦴 Tulang",preview.pendTulang,"#9097a8"],["🫀 By-Product",preview.pendByP,"#a855f7"]].map(([l,v,c])=>(
                    <div key={l} style={{background:c+"0c",border:"1px solid "+c+"22",borderRadius:11,padding:13,textAlign:"center"}}>
                      <div style={{color:c,fontSize:11,fontWeight:700,marginBottom:3}}>{l}</div>
                      <div style={{color:c,fontSize:14,fontWeight:800}}>{"Rp "+(v/1e6).toFixed(2)+"jt"}</div>
                      <div style={{color:"#555a6a",fontSize:10,marginTop:2}}>{preview.pendTotal>0?((v/preview.pendTotal)*100).toFixed(1)+"%":"0%"}</div>
                    </div>
                  ))}
                </div>
                {/* Tabel Potongan */}
                <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:17}}>
                  <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:11}}>🥩 Rincian Potongan Daging</div>
                  <div style={{overflowX:"auto"}}>
                    <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                      <thead><tr style={{background:"#22c55e09",borderBottom:"1px solid #22c55e22"}}>
                        {["Potongan","Grade","%Karkas","Berat (kg)","Harga/kg","Pendapatan"].map(h=><th key={h} style={{...thSD,color:"#22c55e"}}>{h}</th>)}
                      </tr></thead>
                      <tbody>
                        {preview.potongan.map((p,i)=>{
                          const gc=gradeCD(p.grade);
                          return (
                            <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:p.aktual?"#22c55e05":i%2?"#ffffff02":"transparent"}}>
                              <td style={tdSD("#e2e4f0",true)}>{p.nama}{p.aktual&&<span style={{marginLeft:5,background:"#22c55e18",color:"#22c55e",border:"1px solid #22c55e30",borderRadius:20,padding:"1px 5px",fontSize:9,fontWeight:700}}>✅</span>}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 6px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                              <td style={tdSD("#9097a8")}>{p.pct}%</td>
                              <td style={tdSD("#a3e635",true)}>{p.beratKg} kg</td>
                              <td style={tdSD("#9097a8")}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                              <td style={tdSD("#22c55e",true)}>{"Rp "+p.pend.toLocaleString("id-ID")}</td>
                            </tr>
                          );
                        })}
                        <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}>
                          <td colSpan={3} style={{padding:"8px 10px",color:"#22c55e",fontWeight:800}}>TOTAL DAGING</td>
                          <td style={tdSD("#a3e635",true)}>{preview.totalDaging} kg</td>
                          <td/><td style={tdSD("#22c55e",true)}>{"Rp "+preview.pendDaging.toLocaleString("id-ID")}</td>
                        </tr>
                        <tr style={{background:"#9097a809"}}>
                          <td colSpan={2} style={tdSD("#9097a8")}>Tulang</td>
                          <td style={tdSD("#9097a8")}>{S.pct_tulang}%</td>
                          <td style={tdSD("#9097a8",true)}>{preview.beratTulang} kg</td>
                          <td style={tdSD("#9097a8")}>{"Rp "+(f.hJualTulang||18000).toLocaleString("id-ID")}</td>
                          <td style={tdSD("#9097a8",true)}>{"Rp "+preview.pendTulang.toLocaleString("id-ID")}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
                {/* Biaya & Profit */}
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:13}}>
                  <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:15}}>
                    <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:11}}>💸 Rincian Biaya</div>
                    {[["Harga Beli Domba",f.hargaBeli,"#f5c842"],["Retribusi",f.bRetribusi,"#9097a8"],["Upah Potong",f.bUpah,"#9097a8"],["Listrik & Air",f.bListrik,"#9097a8"],["Kemasan",f.bKemasan,"#9097a8"],["Transportasi",f.bTransport,"#9097a8"],["Lainnya",f.bLainnya,"#9097a8"],["TOTAL BIAYA",preview.totalBiaya,"#ef4444"]].map(([k,v,c],i)=>(
                      <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:i<7?"1px solid #1c1e2b":"none",borderTop:i===7?"2px solid #ef444433":"none",marginTop:i===7?4:0}}>
                        <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                        <span style={{color:c,fontWeight:i===7?800:500,fontSize:i===7?13:12}}>{"Rp "+Number(v).toLocaleString("id-ID")}</span>
                      </div>
                    ))}
                  </div>
                  <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:15}}>
                    <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:11}}>💰 Rekap Keuangan</div>
                    {[["Pend. Daging",preview.pendDaging,"#22c55e"],["Pend. Tulang",preview.pendTulang,"#9097a8"],["Pend. By-Product",preview.pendByP,"#a855f7"],["TOTAL PEND.",preview.pendTotal,"#3b82f6"],["Total Biaya",preview.totalBiaya,"#ef4444"],["PROFIT BERSIH",preview.profit,preview.profit>=0?"#22c55e":"#ef4444"],["ROI",preview.roi+"%","#f5c842"],["HPP/kg","Rp "+preview.hppPerKg.toLocaleString("id-ID"),"#f59e0b"]].map(([k,v,c],i)=>(
                      <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:i<7?"1px solid #1c1e2b":"none",borderTop:[3,5].includes(i)?"2px solid #1c1e2b":"none",marginTop:[4,5].includes(i)?4:0}}>
                        <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                        <span style={{color:c,fontWeight:[3,5,6].includes(i)?800:500,fontSize:[3,5].includes(i)?13:12}}>{typeof v==="string"?v:"Rp "+v.toLocaleString("id-ID")}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* ═══ TAB RIWAYAT ═══ */}
      {tab==="riwayat" && (
        records.length===0 ? (
          <div style={{textAlign:"center",padding:60,color:"#555a6a",background:"#0f1118",borderRadius:12,border:"1px solid #1c1e2b",fontSize:13}}>Belum ada riwayat. Tambahkan di tab Kalkulator.</div>
        ) : (()=>{
          const curId = activeId || records[0]?.id;
          const rec   = records.find(r=>r.id===curId) || records[0];
          const c     = rec ? hitungRPHDomba(rec) : null;
          if (!c||!rec) return null;

          const gJ = nm => c.byProducts.find(b=>b.nama===nm)||{beratKg:0,pend:0,aktual:false,harga:0,kat:"—",latin:"—"};
          const hati=gJ("Hati"),paru=gJ("Paru-paru"),jantung=gJ("Jantung"),
                ginjal=gJ("Ginjal"),limpa=gJ("Limpa"),otak=gJ("Otak"),
                babat=gJ("Babat/Rumen"),usus=gJ("Usus"),tetelan=gJ("Tetelan"),
                kepala=gJ("Kepala Domba"),kaki=gJ("Kaki (4)"),
                kulit=gJ("Kulit Domba"),darah=gJ("Darah (L)"),ekorGemuk=gJ("Ekor Gemuk");

          const jerMerahKg  = +[hati,paru,jantung,ginjal,limpa,otak].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const jerPutihKg  = +[babat,usus,tetelan].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const fancyKg     = +[kepala,kaki,ekorGemuk].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const jerMerahPend= hati.pend+paru.pend+jantung.pend+ginjal.pend+limpa.pend+otak.pend;
          const jerPutihPend= babat.pend+usus.pend+tetelan.pend;
          const fancyPend   = kepala.pend+kaki.pend+ekorGemuk.pend;

          const chartKomp = [
            {label:"Daging",    value:c.totalDaging,              label2:c.totalDaging+"kg",   color:"#22c55e"},
            {label:"Tulang",    value:c.beratTulang,              label2:c.beratTulang+"kg",   color:"#9097a8"},
            {label:"Lemak",     value:Math.max(0,c.beratSusut),  label2:"",                   color:"#555a6a"},
            {label:"Jer.Merah", value:jerMerahKg,                 label2:"",                   color:"#ef4444"},
            {label:"Jer.Putih", value:jerPutihKg,                 label2:"",                   color:"#a855f7"},
            {label:"Fancy",     value:fancyKg,                    label2:"",                   color:"#f5c842"},
            {label:"Kulit",     value:kulit.beratKg,              label2:"",                   color:"#f59e0b"},
            {label:"Darah",     value:darah.beratKg,              label2:"",                   color:"#ef4444"},
            {label:"Rumen",     value:c.bRumen,                   label2:c.bRumen+"kg",        color:"#444"},
            {label:"Feses",     value:c.bFeses,                   label2:c.bFeses+"kg",        color:"#333"},
          ];
          const chartPot = c.potongan.map(p=>({label:p.nama.split("/")[0].trim(),value:p.beratKg,label2:p.beratKg+"kg",color:gradeCD(p.grade)})).concat([{label:"Tulang",value:c.beratTulang,label2:c.beratTulang+"kg",color:"#555a6a"}]);
          const chartPend = [
            {label:"Premium",  value:Math.round(c.potongan.filter(p=>p.grade==="Premium").reduce((s,p)=>s+p.pend,0)/1000), color:"#a3e635"},
            {label:"Superior", value:Math.round(c.potongan.filter(p=>p.grade==="Superior").reduce((s,p)=>s+p.pend,0)/1000),color:"#3b82f6"},
            {label:"Standar",  value:Math.round(c.potongan.filter(p=>p.grade==="Standar").reduce((s,p)=>s+p.pend,0)/1000), color:"#9097a8"},
            {label:"Tulang",   value:Math.round(c.pendTulang/1000),                                                          color:"#555a6a"},
            {label:"Jer.Merah",value:Math.round(jerMerahPend/1000),                                                          color:"#ef4444"},
            {label:"Fancy",    value:Math.round(fancyPend/1000),                                                              color:"#f5c842"},
            {label:"Jer.Putih",value:Math.round(jerPutihPend/1000),                                                          color:"#a855f7"},
          ];

          const stl = {
            th: {padding:"8px 10px",color:"#555a6a",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap",borderBottom:"1px solid #1c1e2b"},
            td: (col="#e2e4f0",bold=false)=>({padding:"8px 10px",color:col,fontWeight:bold?700:400,fontSize:12}),
          };

          return (
            <div style={{display:"grid",gridTemplateColumns:"240px 1fr",gap:13,alignItems:"start"}}>
              {/* Panel Kiri */}
              <div style={{background:"#0a0c16",border:"1px solid #1c1e2b",borderRadius:13,overflow:"hidden",position:"sticky",top:0}}>
                <div style={{background:AC+"12",padding:"11px 15px",borderBottom:"1px solid "+AC+"28"}}>
                  <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:13,fontWeight:700}}>📋 Daftar Pemotongan</div>
                  <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{records.length} ekor tercatat</div>
                </div>
                <div style={{maxHeight:"75vh",overflowY:"auto"}}>
                  {records.map(r=>{
                    const rc=hitungRPHDomba(r); if(!rc) return null;
                    const isActive = r.id===curId;
                    return (
                      <div key={r.id} onClick={()=>setActiveId(r.id)}
                        style={{padding:"9px 14px",borderBottom:"1px solid #1c1e2b",cursor:"pointer",
                          background:isActive?AC+"12":"transparent",
                          borderLeft:"3px solid "+(isActive?AC:"transparent"),transition:"all 0.1s"}}>
                        <div style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                          <span style={{color:isActive?AC:"#e2e4f0",fontWeight:700,fontSize:12}}>{r.dombaNama||"—"}</span>
                          <span style={{fontSize:9,fontWeight:700,padding:"2px 5px",borderRadius:9,background:rc.profit>=0?"#22c55e18":"#ef444418",color:rc.profit>=0?"#22c55e":"#ef4444"}}>
                            {rc.profit>=0?"+":"-"}{"Rp "+(Math.abs(rc.profit)/1e6).toFixed(1)+"jt"}
                          </span>
                        </div>
                        <div style={{display:"flex",gap:5,flexWrap:"wrap"}}>
                          <span style={{color:"#a3e635",fontSize:10,fontWeight:700}}>{r.bbHidup}kg</span>
                          <span style={{color:"#555a6a",fontSize:9}}>·</span>
                          <span style={{color:"#9097a8",fontSize:10}}>{r.breed}</span>
                        </div>
                        <div style={{display:"flex",gap:7,marginTop:2}}>
                          <span style={{color:"#3b82f6",fontSize:9}}>{"Rp "+(rc.pendTotal/1e6).toFixed(1)+"jt"}</span>
                          <span style={{color:"#555a6a",fontSize:9}}>ROI {rc.roi}%</span>
                          {rc.hasAktual&&<span style={{color:"#22c55e",fontSize:8,background:"#22c55e12",padding:"1px 4px",borderRadius:7}}>✅</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Panel Kanan */}
              <div style={{display:"flex",flexDirection:"column",gap:11,minWidth:0}}>
                {/* Header */}
                <div style={{background:"#0c0f1a",border:"1px solid #252535",borderRadius:13,padding:"13px 17px",display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:10}}>
                  <div>
                    <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:18,fontWeight:700,display:"flex",alignItems:"center",gap:9,flexWrap:"wrap"}}>
                      🐑 {rec.dombaNama||"—"}
                      <span style={{fontSize:11,color:"#555a6a",fontWeight:400}}>({rec.id})</span>
                      <span style={{background:c.hasAktual?"#22c55e18":"#f5c84218",color:c.hasAktual?"#22c55e":"#f5c842",border:"1px solid "+(c.hasAktual?"#22c55e30":"#f5c84230"),borderRadius:20,padding:"2px 9px",fontSize:10,fontWeight:700}}>
                        {c.hasAktual?"✅ Data Aktual":"📊 Estimasi"}
                      </span>
                    </div>
                    <div style={{color:"#9097a8",fontSize:11,marginTop:3}}>
                      {rec.breed} · {rec.gender} · BH: {c.bb}kg · Karkas: {rec.pctKarkas}% ({c.beratKarkas}kg)
                      {rec.tglPotong?" · "+rec.tglPotong:""}{rec.buyer?" · "+rec.buyer:""}
                    </div>
                  </div>
                  <button onClick={()=>cetakLaporanDomba(rec,c)} style={{background:AC+"18",color:AC,border:"1px solid "+AC+"30",borderRadius:9,padding:"8px 15px",cursor:"pointer",fontWeight:700,fontSize:12}}>
                    🖨️ Cetak
                  </button>
                </div>

                {/* KPI */}
                <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:9}}>
                  {[["💰 Pendapatan","Rp "+(c.pendTotal/1e6).toFixed(2)+"jt","#3b82f6"],
                    ["💸 Biaya","Rp "+(c.totalBiaya/1e6).toFixed(2)+"jt","#ef4444"],
                    ["📈 Profit","Rp "+(c.profit/1e6).toFixed(2)+"jt",c.profit>=0?"#22c55e":"#ef4444"],
                    ["🔄 ROI",c.roi+"%",+c.roi>=15?"#22c55e":"#f59e0b"],
                    ["🏷️ HPP/kg","Rp "+c.hppPerKg.toLocaleString("id-ID"),"#f5c842"],
                  ].map(([l,v,col])=>(
                    <div key={l} style={{background:col+"0d",border:"1px solid "+col+"25",borderRadius:10,padding:"9px 11px",textAlign:"center"}}>
                      <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:3}}>{l}</div>
                      <div style={{color:col,fontWeight:800,fontSize:13}}>{v}</div>
                    </div>
                  ))}
                </div>

                {/* Sub-Tabs */}
                <div style={{display:"flex",gap:2,background:"#0a0c16",borderRadius:"10px 10px 0 0",border:"1px solid #1c1e2b",borderBottom:"none",padding:"0 4px",paddingTop:4}}>
                  {[["ilmiah","🔬 Ilmiah"],["bisnis","💰 Bisnis"],["grafik","📊 Grafik"],["potongan","🥩 Potongan"],["jeroan","🫀 Jeroan"]].map(([id,lbl])=>(
                    <button key={id} onClick={()=>setSubTab(id)}
                      style={{flex:1,background:subTab===id?"#0f1118":"none",border:"none",
                        borderBottom:"2px solid "+(subTab===id?AC:"transparent"),
                        color:subTab===id?AC:"#555a6a",padding:"8px 4px",cursor:"pointer",
                        fontWeight:700,fontSize:11,borderRadius:"6px 6px 0 0",transition:"all 0.1s"}}>
                      {lbl}
                    </button>
                  ))}
                </div>

                <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:"0 0 13px 13px",padding:15,marginTop:-1}}>

                  {/* ILMIAH */}
                  {subTab==="ilmiah" && (
                    <div style={{display:"flex",flexDirection:"column",gap:13}}>
                      <div style={{color:"#a3e635",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:4}}>📐 Komposisi Tubuh (BH = {c.bb} kg)</div>
                      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
                        {[["Karkas",c.beratKarkas,rec.pctKarkas+"%","#a3e635",!!rec.aKarkas],
                          ["Daging",c.totalDaging,+(c.totalDaging/c.bb*100).toFixed(1)+"%","#22c55e",false],
                          ["Tulang",c.beratTulang,S.pct_tulang+"% karkas","#9097a8",!!rec.aTulang],
                          ["Lemak/Trim",+Math.max(0,c.beratSusut).toFixed(1),c.pctSusut+"% karkas","#555a6a",false],
                          ["Jer.Merah",jerMerahKg,+(jerMerahKg/c.bb*100).toFixed(1)+"%","#ef4444",false],
                          ["Jer.Putih",jerPutihKg,+(jerPutihKg/c.bb*100).toFixed(1)+"%","#a855f7",false],
                          ["Fancy Meat",fancyKg,+(fancyKg/c.bb*100).toFixed(1)+"%","#f5c842",false],
                          ["Kulit+Darah",+(kulit.beratKg+darah.beratKg).toFixed(1),+(((kulit.beratKg+darah.beratKg)/c.bb)*100).toFixed(1)+"%","#f59e0b",false],
                          ["Isi Rumen",c.bRumen,+(c.bRumen/c.bb*100).toFixed(0)+"%","#555a6a",!!rec.aRumen],
                          ["Feses & Urin",c.bFeses,"~4% BH","#444",!!rec.aFeses],
                          ["Teridentifikasi",+(c.beratKarkas+c.byProducts.reduce((s,b)=>s+b.beratKg,0)+c.bFeses+c.bRumen).toFixed(1),"dari BH","#3b82f6",false],
                          ["Selisih",+(c.bb-c.beratKarkas-c.byProducts.reduce((s,b)=>s+b.beratKg,0)-c.bFeses-c.bRumen).toFixed(1),"shrinkage","#555a6a",false],
                        ].map(([nm,brt,pct,col,isAkt])=>(
                          <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:9,padding:"8px 10px"}}>
                            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:2}}>
                              <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>{nm}</div>
                              {isAkt!==false&&<BadgeD isA={isAkt}/>}
                            </div>
                            <div style={{color:col,fontWeight:800,fontSize:15}}>{brt} <span style={{fontSize:9,fontWeight:400}}>kg</span></div>
                            <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{pct}</div>
                          </div>
                        ))}
                      </div>
                      <div style={{borderTop:"1px solid #1c1e2b",paddingTop:12}}>
                        <div style={{color:"#3b82f6",fontFamily:"'DM Serif Display',serif",fontSize:12,marginBottom:9}}>🔬 Indikator Kualitas Ilmiah</div>
                        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8}}>
                          {[["DCP (Dressing %)",c.pctKarkas+"%",c.pctKarkas>=48?"#22c55e":c.pctKarkas>=45?"#f59e0b":"#ef4444","Ideal ≥46%. Domba Garut jantan ≥48%"],
                            ["Meat-Bone Ratio",c.mbr+":1",+c.mbr>=3.0?"#22c55e":"#f59e0b","Domba: ideal ≥3.0:1 (lebih kecil dari sapi)"],
                            ["% Lean dari Karkas",+(c.totalDaging/c.beratKarkas*100).toFixed(1)+"%",c.totalDaging/c.beratKarkas>=0.72?"#22c55e":"#f59e0b","Ideal ≥72% dari karkas"],
                            ["% Lean dari BH",+(c.totalDaging/c.bb*100).toFixed(1)+"%",c.totalDaging/c.bb>=0.33?"#22c55e":"#f59e0b","Ideal ≥33% dari BH"],
                            ["% Tulang dr Karkas",+(c.beratTulang/c.beratKarkas*100).toFixed(1)+"%","#9097a8","Standar domba: 18–25% karkas"],
                            ["By-Product Revenue",+(c.pendByP/c.pendTotal*100).toFixed(1)+"%","#a855f7","% jeroan dari total omzet RPH"],
                          ].map(([k,v,col,desc])=>(
                            <div key={k} style={{background:"#ffffff05",borderRadius:8,padding:"9px 11px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:8}}>
                              <div style={{flex:1}}>
                                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                                <div style={{fontSize:10,color:"#444",lineHeight:1.3}}>{desc}</div>
                              </div>
                              <div style={{color:col,fontWeight:800,fontSize:16,whiteSpace:"nowrap"}}>{v}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* BISNIS */}
                  {subTab==="bisnis" && (
                    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:13}}>
                      <div>
                        <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>💸 Rincian Biaya Modal</div>
                        {[["Harga Beli Domba",c.hBeli,"#f5c842",true],["Retribusi",c.biaya.retribusi,"#9097a8"],["Upah Potong",c.biaya.upah,"#9097a8"],["Listrik & Air",c.biaya.listrik,"#9097a8"],["Kemasan",c.biaya.kemasan,"#9097a8"],["Transportasi",c.biaya.transport,"#9097a8"],["Lainnya",c.biaya.lainnya,"#9097a8"],["Biaya Ops RPH",c.biayaOps,"#ef4444",false,true],["TOTAL MODAL",c.totalBiaya,"#ef4444",true]].map(([k,v,col,bold,sep])=>(
                          <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #1c1e2b",borderTop:sep?"1px solid #ef444422":"none",marginTop:sep?6:0}}>
                            <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                            <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{"Rp "+Number(v).toLocaleString("id-ID")}</span>
                          </div>
                        ))}
                        <div style={{marginTop:11,background:"#ef444410",border:"1px solid #ef444428",borderRadius:9,padding:"9px 11px"}}>
                          <div style={{fontSize:10,color:"#9097a8",marginBottom:2}}>HPP (Harga Pokok Produksi)</div>
                          <div style={{fontSize:19,fontWeight:800,color:"#f5c842"}}>{"Rp "+c.hppPerKg.toLocaleString("id-ID")}<span style={{fontSize:11,fontWeight:400,color:"#555a6a"}}>/kg daging</span></div>
                        </div>
                      </div>
                      <div>
                        <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>💰 Rincian Pendapatan</div>
                        {[["Daging Premium",c.potongan.filter(p=>p.grade==="Premium").reduce((s,p)=>s+p.pend,0),"#a3e635"],["Daging Superior",c.potongan.filter(p=>p.grade==="Superior").reduce((s,p)=>s+p.pend,0),"#3b82f6"],["Daging Standar",c.potongan.filter(p=>p.grade==="Standar").reduce((s,p)=>s+p.pend,0),"#9097a8"],["Tulang",c.pendTulang,"#9097a8"],["Fancy Meat",fancyPend,"#f5c842"],["Jeroan Merah",jerMerahPend,"#ef4444"],["Jeroan Putih",jerPutihPend,"#a855f7"],["Kulit+Darah",kulit.pend+darah.pend,"#f59e0b"],["TOTAL PENDAPATAN",c.pendTotal,"#3b82f6",true],["PROFIT BERSIH",c.profit,c.profit>=0?"#22c55e":"#ef4444",true],["ROI",null,"#f5c842",true]].map(([k,v,col,bold])=>{
                          const disp = k==="ROI" ? c.roi+"%" : "Rp "+Number(v).toLocaleString("id-ID");
                          return (<div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #1c1e2b",borderTop:bold?"2px solid #1c1e2b":"none",marginTop:bold?4:0}}><span style={{fontSize:12,color:"#9097a8"}}>{k}</span><span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{disp}</span></div>);
                        })}
                      </div>
                      <div style={{gridColumn:"1/-1",borderTop:"1px solid #1c1e2b",paddingTop:12}}>
                        <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>⚖️ Neraca Bobot Lengkap</div>
                        <div style={{display:"grid",gridTemplateColumns:"repeat(6,1fr)",gap:7}}>
                          {[["BH Awal",c.bb,"100%","#f5c842"],["Karkas",c.beratKarkas,rec.pctKarkas+"%","#22c55e"],["Daging",c.totalDaging,+(c.totalDaging/c.bb*100).toFixed(1)+"%","#22c55e"],["Tulang",c.beratTulang,+(c.beratTulang/c.bb*100).toFixed(1)+"%","#9097a8"],["Lemak/Trim",+Math.max(0,c.beratSusut).toFixed(1),+(Math.max(0,c.beratSusut)/c.bb*100).toFixed(1)+"%","#555a6a"],["Jeroan Ed.",+c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0).toFixed(1),+(c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0)/c.bb*100).toFixed(1)+"%","#a855f7"],["Kulit+Darah",+(kulit.beratKg+darah.beratKg).toFixed(1),+(((kulit.beratKg+darah.beratKg)/c.bb)*100).toFixed(1)+"%","#f59e0b"],["Isi Rumen",c.bRumen,+(c.bRumen/c.bb*100).toFixed(0)+"%","#555a6a"],["Feses",c.bFeses,"~4%","#444"],["Teridentif.",+(c.beratKarkas+c.byProducts.reduce((s,b)=>s+b.beratKg,0)+c.bFeses+c.bRumen).toFixed(1),"dari BH","#3b82f6"],["Selisih",+(c.bb-c.beratKarkas-c.byProducts.reduce((s,b)=>s+b.beratKg,0)-c.bFeses-c.bRumen).toFixed(1),"shrinkage","#555a6a"]].map(([nm,brt,pct,col])=>(
                            <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:8,padding:"7px 9px",textAlign:"center"}}>
                              <div style={{fontSize:8,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{nm}</div>
                              <div style={{color:col,fontWeight:800,fontSize:13}}>{brt}<span style={{fontSize:9}}> kg</span></div>
                              <div style={{color:"#555a6a",fontSize:9}}>{pct}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* GRAFIK */}
                  {subTab==="grafik" && (
                    <div style={{display:"flex",flexDirection:"column",gap:11}}>
                      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:11}}>
                        <BarChartD data={chartKomp} title={"Komposisi Tubuh dari BH "+c.bb+"kg"} height={120}/>
                        <BarChartD data={chartPend} title="Pendapatan per Kategori (Rp ribu)" height={120}/>
                      </div>
                      <BarChartD data={chartPot} title="Berat Tiap Potongan Daging & Tulang (kg)" height={110}/>
                      <div style={{display:"flex",gap:9,flexWrap:"wrap",fontSize:10,color:"#555a6a"}}>
                        {[["#a3e635","Premium"],["#3b82f6","Superior"],["#9097a8","Standar"],["#22c55e","Daging"],["#ef4444","Jer.Merah"],["#a855f7","Jer.Putih"],["#555a6a","Tulang"]].map(([col,lbl])=>(
                          <span key={lbl} style={{display:"flex",alignItems:"center",gap:4}}>
                            <span style={{width:9,height:9,borderRadius:2,background:col,display:"inline-block"}}/>{lbl}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* POTONGAN */}
                  {subTab==="potongan" && (
                    <div style={{overflowX:"auto"}}>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#22c55e09",borderBottom:"1px solid #22c55e22"}}>
                          {["No","Potongan","Grade","%Karkas","Berat (kg)","%BH","Harga/kg","Nilai (Rp)","Data"].map(h=><th key={h} style={{...stl.th,color:"#22c55e"}}>{h}</th>)}
                        </tr></thead>
                        <tbody>
                          {c.potongan.map((p,i)=>{
                            const gc=gradeCD(p.grade);
                            return (<tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:p.aktual?"#22c55e05":i%2?"#ffffff02":"transparent"}}>
                              <td style={stl.td("#555a6a")}>{i+1}</td>
                              <td style={stl.td("#e2e4f0",true)}>{p.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                              <td style={stl.td("#9097a8")}>{p.pct}%</td>
                              <td style={stl.td("#a3e635",true)}>{p.beratKg} kg</td>
                              <td style={stl.td("#555a6a")}>{+(p.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#22c55e",true)}>{"Rp "+p.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><BadgeD isA={p.aktual}/></td>
                            </tr>);
                          })}
                          <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}><td colSpan={4} style={{padding:"9px 10px",color:"#22c55e",fontWeight:800}}>TOTAL DAGING</td><td style={stl.td("#a3e635",true)}>{c.totalDaging} kg</td><td style={stl.td("#555a6a")}>{+(c.totalDaging/c.bb*100).toFixed(2)}%</td><td/><td style={stl.td("#22c55e",true)}>{"Rp "+c.pendDaging.toLocaleString("id-ID")}</td><td/></tr>
                          <tr style={{background:"#9097a809"}}><td colSpan={2} style={stl.td("#9097a8")}>Tulang</td><td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>By-product</span></td><td style={stl.td("#9097a8")}>{S.pct_tulang}%</td><td style={stl.td("#9097a8",true)}>{c.beratTulang} kg</td><td style={stl.td("#555a6a")}>{+(c.beratTulang/c.bb*100).toFixed(2)}%</td><td style={stl.td("#9097a8")}>{"Rp "+(rec.hJualTulang||18000).toLocaleString("id-ID")}</td><td style={stl.td("#9097a8",true)}>{"Rp "+c.pendTulang.toLocaleString("id-ID")}</td><td style={{padding:"8px 10px"}}><BadgeD isA={!!rec.aTulang}/></td></tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* JEROAN */}
                  {subTab==="jeroan" && (
                    <div style={{overflowX:"auto"}}>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#a855f709",borderBottom:"1px solid #a855f722"}}>
                          {["Komponen","Kategori","Nama Latin","Berat (kg)","%BH","Harga/kg","Nilai (Rp)","Sifat","Data"].map(h=><th key={h} style={{...stl.th,color:"#a855f7"}}>{h}</th>)}
                        </tr></thead>
                        <tbody>
                          {/* FANCY MEAT */}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#f5c84212",color:"#f5c842",fontSize:10,fontWeight:700}}>🏆 FANCY & VARIETY MEAT</td></tr>
                          {[kepala,kaki,ekorGemuk].map((obj,i)=>(
                            <tr key={"fancy"+i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#f5c84205":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#f5c84215",color:"#f5c842",border:"1px solid #f5c84228",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Fancy Meat</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#a3e635",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><BadgeD isA={obj.aktual}/></td>
                            </tr>
                          ))}
                          {/* JEROAN MERAH */}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#ef444412",color:"#ef4444",fontSize:10,fontWeight:700}}>🔴 JEROAN MERAH (Organ Parenkim)</td></tr>
                          {[hati,paru,jantung,ginjal,limpa,otak].map((obj,i)=>(
                            <tr key={"jm"+i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#ef444406":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#ef444415",color:"#ef4444",border:"1px solid #ef444428",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Jeroan Merah</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#a3e635",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><BadgeD isA={obj.aktual}/></td>
                            </tr>
                          ))}
                          {/* JEROAN PUTIH */}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#9097a80a",color:"#9097a8",fontSize:10,fontWeight:700}}>⬜ JEROAN PUTIH (Saluran Cerna)</td></tr>
                          {[babat,usus,tetelan].map((obj,i)=>(
                            <tr key={"jp"+i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#9097a806":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",border:"1px solid #9097a828",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Jeroan Putih</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#a3e635",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><BadgeD isA={obj.aktual}/></td>
                            </tr>
                          ))}
                          {/* KULIT DARAH LIMBAH */}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#f59e0b0a",color:"#f59e0b",fontSize:10,fontWeight:700}}>🩸 KULIT, DARAH & LIMBAH</td></tr>
                          {[
                            [kulit,"Industri"],
                            [darah,"Edible"],
                            [{nama:"Isi Rumen+Usus",beratKg:c.bRumen,pend:0,harga:0,aktual:!!rec.aRumen,latin:"Digesta"},"Non-Edible"],
                            [{nama:"Feses & Urin",beratKg:c.bFeses,pend:0,harga:0,aktual:!!rec.aFeses,latin:"Faeces"},"Limbah"],
                          ].map(([obj,sifat],i)=>(
                            <tr key={"kdl"+i} style={{borderBottom:"1px solid #1c1e2b"}}>
                              <td style={stl.td("#e2e4f0")}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#f59e0b14",color:"#f59e0b",border:"1px solid #f59e0b28",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Ikutan</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin||"—"}</i></td>
                              <td style={stl.td("#a3e635")}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#555a6a")}>{obj.harga?"Rp "+obj.harga.toLocaleString("id-ID"):"—"}</td>
                              <td style={stl.td("#9097a8")}>{obj.pend?"Rp "+obj.pend.toLocaleString("id-ID"):"—"}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#ef444414",color:"#ef4444",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>{sifat}</span></td>
                              <td style={{padding:"8px 10px"}}><BadgeD isA={obj.aktual}/></td>
                            </tr>
                          ))}
                          <tr style={{borderTop:"2px solid #a855f733",background:"#a855f709"}}>
                            <td colSpan={3} style={{padding:"9px 10px",color:"#a855f7",fontWeight:800}}>TOTAL BY-PRODUCT (edible)</td>
                            <td style={stl.td("#a3e635",true)}>{+c.byProducts.reduce((s,b)=>s+b.beratKg,0).toFixed(2)} kg</td>
                            <td/><td/>
                            <td style={stl.td("#a855f7",true)}>{"Rp "+c.pendByP.toLocaleString("id-ID")}</td>
                            <td colSpan={2}/>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                </div>
                {rec.notes&&<div style={{background:"#ffffff05",border:"1px solid #1c1e2b",borderRadius:9,padding:"9px 13px",color:"#9097a8",fontSize:12}}>📝 <strong style={{color:"#e2e4f0"}}>Catatan:</strong> {rec.notes}</div>}
              </div>
            </div>
          );
        })()
      )}

      {/* ═══ TAB STANDAR ═══ */}
      {tab==="standar" && (
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:"#a3e635",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:11}}>📊 Standar % Karkas Domba/Kambing</div>
            <div style={{overflowX:"auto"}}>
              <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Ras","Jantan (%)","Betina (%)","Keterangan"].map(h=><th key={h} style={{...thSD,color:"#a3e635"}}>{h}</th>)}</tr></thead>
                <tbody>
                  {[["Domba Garut",50,46,"Ras unggulan Jawa Barat, DCP tinggi"],["Domba Lokal",46,43,"Ras asli Indonesia, lebih kecil"],["Domba Merino",47,44,"Penghasil wol + daging"],["Domba Ekor Gemuk",51,47,"Ekor berlemak bernilai tinggi"],["Kambing PE",48,44,"Peranakan Etawa, dwi fungsi"],["Kambing Lokal",46,42,"Kambing asli Indonesia"]].map(([ras,j,b,ket],i)=>(
                    <tr key={ras} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                      <td style={tdSD("#e2e4f0",true)}>{ras}</td>
                      <td style={tdSD("#22c55e",true)}>{j}%</td>
                      <td style={tdSD("#60a5fa",true)}>{b}%</td>
                      <td style={tdSD("#555a6a")}><span style={{fontSize:11}}>{ket}</span></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:6}}>🥩 Harga Potongan Domba (Juni 2026)</div>
            <div style={{fontSize:11,color:"#555a6a",marginBottom:11}}>Sumber: RPH Garut, Pasar Aqiqah & Kurban Jawa Barat · Juni 2026</div>
            <div style={{overflowX:"auto"}}>
              <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Potongan","Grade","%Karkas","Harga/kg","Kegunaan"].map(h=><th key={h} style={{...thSD,color:"#22c55e"}}>{h}</th>)}</tr></thead>
                <tbody>
                  {S.potongan_primer.map((p,i)=>{const gc=gradeCD(p.grade);return(
                    <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                      <td style={tdSD("#e2e4f0",true)}>{p.nama}</td>
                      <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                      <td style={tdSD("#9097a8")}>{p.pct}%</td>
                      <td style={tdSD("#a3e635",true)}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                      <td style={tdSD("#555a6a")}><span style={{fontSize:11}}>{p.ket}</span></td>
                    </tr>
                  );})}
                  <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}><td style={tdSD("#9097a8",true)}>Tulang</td><td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>By-product</span></td><td style={tdSD("#9097a8")}>{S.pct_tulang}%</td><td style={tdSD("#9097a8",true)}>{"Rp "+S.harga_tulang.toLocaleString("id-ID")}</td><td style={tdSD("#555a6a")}>Kaldu, pakan, pupuk</td></tr>
                </tbody>
              </table>
            </div>
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:6}}>🫀 Harga Jeroan Domba (Juni 2026)</div>
            <div style={{overflowX:"auto"}}>
              <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Produk","Kategori","Nama Latin","%BH","Harga/kg"].map(h=><th key={h} style={{...thSD,color:"#a855f7"}}>{h}</th>)}</tr></thead>
                <tbody>
                  {S.by_products.map((b,i)=>{const catC={"Fancy Meat":"#f5c842","Jeroan Merah":"#ef4444","Jeroan Putih":"#9097a8","Kulit/Darah":"#555a6a"};const cc=catC[b.kat]||"#666";return(
                    <tr key={b.nama} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                      <td style={tdSD("#e2e4f0",true)}>{b.nama}</td>
                      <td style={{padding:"8px 10px"}}><span style={{background:cc+"14",color:cc,border:"1px solid "+cc+"28",borderRadius:20,padding:"2px 7px",fontSize:9,fontWeight:700}}>{b.kat}</span></td>
                      <td style={tdSD("#555a6a")}><i style={{fontSize:10}}>{b.latin}</i></td>
                      <td style={tdSD("#9097a8")}>{b.pct_live}%</td>
                      <td style={tdSD("#a855f7",true)}>{"Rp "+b.harga.toLocaleString("id-ID")}</td>
                    </tr>
                  );})}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};



/* ================================================================
   RPH_STANDAR_BROILER — Standar Potongan & Harga Ayam Broiler
   Sumber: Pasar Tradisional, Supermarket, Distributor — Juni 2026
================================================================ */
const RPH_STANDAR_BROILER = {
  // % karkas dari bobot hidup (ayam broiler ~70-74%)
  persen_karkas: {
    "Cobb 500":    { jantan:73, betina:71 },
    "Ross 308":    { jantan:74, betina:72 },
    "Hubbard":     { jantan:72, betina:70 },
    "Lohmann":     { jantan:71, betina:70 },
    "Lokal/Kampung":{ jantan:68, betina:66 },
    "default":     { jantan:72, betina:70 },
  },
  // Potongan primer (% dari berat hidup)
  potongan_primer: [
    {kode:"dada",       nama:"Dada (Breast)",           pct:30, grade:"Premium",  harga:42000, ket:"Paling laku, rendah lemak, steak/goreng"},
    {kode:"paha_atas",  nama:"Paha Atas (Thigh)",       pct:18, grade:"Premium",  harga:38000, ket:"Juicy, berlemak, sate/semur/kari"},
    {kode:"paha_bawah", nama:"Paha Bawah (Drumstick)",  pct:14, grade:"Premium",  harga:36000, ket:"Favorit anak-anak, digoreng/dipanggang"},
    {kode:"sayap",      nama:"Sayap (Wing)",             pct:10, grade:"Superior", harga:32000, ket:"Sayap goreng, buffalo wings"},
    {kode:"punggung",   nama:"Punggung (Back)",          pct:14, grade:"Standar",  harga:18000, ket:"Kaldu, sup, soto ayam"},
    {kode:"leher",      nama:"Leher (Neck)",             pct:4,  grade:"Standar",  harga:15000, ket:"Kaldu, soto, gulai"},
    {kode:"karkas_utuh",nama:"Karkas Utuh (Whole)",      pct:0,  grade:"Premium",  harga:32000, ket:"Dijual utuh ke konsumen"},
  ],
  pct_tulang: 22,  // % dari berat karkas
  harga_tulang: 5000,
  // By-product / jeroan ayam
  by_products: [
    {nama:"Kepala",          pct_live:3.0,  harga:8000,  kat:"Fancy Meat",   latin:"Caput"},
    {nama:"Ceker (Kaki)",    pct_live:4.5,  harga:22000, kat:"Fancy Meat",   latin:"Pedis"},
    {nama:"Hati",            pct_live:2.0,  harga:28000, kat:"Jeroan",       latin:"Hepar"},
    {nama:"Ampela (Gizzard)",pct_live:1.8,  harga:25000, kat:"Jeroan",       latin:"Gaster"},
    {nama:"Jantung",         pct_live:0.5,  harga:30000, kat:"Jeroan",       latin:"Cor"},
    {nama:"Usus",            pct_live:1.2,  harga:12000, kat:"Jeroan",       latin:"Intestinum"},
    {nama:"Kulit Ayam",      pct_live:5.0,  harga:18000, kat:"Kulit",        latin:"Cutis"},
    {nama:"Darah (L)",       pct_live:3.5,  harga:5000,  kat:"Darah",        latin:"Sanguis"},
    {nama:"Bulu+Limbah",     pct_live:8.0,  harga:500,   kat:"Limbah",       latin:"Pluma"},
  ],
  // Produk olahan (nilai tambah)
  produk_olahan: [
    {nama:"Karkas Bersih",        harga_per_kg:32000,  ket:"Utuh tanpa bulu+jeroan"},
    {nama:"Daging Giling (MDF)",  harga_per_kg:28000,  ket:"Mechanically Deboned, bakso/nugget"},
    {nama:"Karkas Beku (IQF)",    harga_per_kg:34000,  ket:"Individual Quick Frozen"},
    {nama:"Potongan Retail",      harga_per_kg:38000,  ket:"Dada/Paha sudah dipisah"},
    {nama:"Jeroan Bersih Pack",   harga_per_kg:22000,  ket:"Hati+Ampela sudah dibersihkan"},
    {nama:"Ceker Bersih",         harga_per_kg:25000,  ket:"Kuku sudah dikupas"},
  ],
  biaya_rpa: {
    listrik_air:      150,   // per ekor
    upah_tenaga:      200,   // per ekor
    plastik_kemasan:   80,   // per ekor
    bahan_sanitasi:    30,   // per ekor
    bbm_transport:    100,   // per ekor (estimasi)
    retribusi_rph:     50,   // per ekor
    lainnya:           90,   // per ekor
  },
};

/* ================================================================
   DATA AWAL RPA BROILER — 10 contoh: 100–5000 ekor
================================================================ */
const initialRphBroilerRecords = [
  {id:"RPA001",flockId:"BR003",flockName:"Kandang F Periode 10",breed:"Cobb 500",
   tglPotong:"2026-05-15",jumlahEkor:100,beratRataHidup:2.15,hargaBeliPerEkor:48000,
   status:"Selesai",buyer:"Warung Ayam Pak Slamet",notes:"Potong kecil, uji coba",
   modePenjualan:"karkas",pctKarkas:73,
   hJualDada:42000,hJualPahaAtas:38000,hJualPahaBawah:36000,hJualSayap:32000,
   hJualPunggung:18000,hJualLeher:15000,hJualTulang:5000,
   hJualCeker:22000,hJualHati:28000,hJualAmpela:25000,hJualJantung:30000,
   hJualUsus:12000,hJualKepala:8000,hJualKulit:18000,
   bListrik:150,bUpah:200,bKemasan:80,bSanitasi:30,bTransport:100,bRetribusi:50,bLainnya:90,
   aKarkas:"",aDaging:"",aTulang:"",aDada:"",aPahaAtas:"",aPahaBawah:"",aSayap:"",aPunggung:"",aLeher:"",
   aHati:"",aAmpela:"",aJantung:"",aUsus:"",aCeker:"",aKepala:"",aKulit:"",aDarah:"",aBulu:""},

  {id:"RPA002",flockId:"BR002",flockName:"Kandang E Periode 11",breed:"Ross 308",
   tglPotong:"2026-06-05",jumlahEkor:500,beratRataHidup:1.95,hargaBeliPerEkor:44000,
   status:"Selesai",buyer:"Rumah Makan Padang Bu Minem",notes:"Dijual karkas utuh",
   modePenjualan:"karkas",pctKarkas:74,
   hJualDada:43000,hJualPahaAtas:39000,hJualPahaBawah:37000,hJualSayap:33000,
   hJualPunggung:19000,hJualLeher:16000,hJualTulang:5000,
   hJualCeker:22000,hJualHati:28000,hJualAmpela:25000,hJualJantung:30000,
   hJualUsus:12000,hJualKepala:8000,hJualKulit:18000,
   bListrik:150,bUpah:200,bKemasan:80,bSanitasi:30,bTransport:100,bRetribusi:50,bLainnya:90,
   aKarkas:720.3,aDaging:"",aTulang:"",aDada:"",aPahaAtas:"",aPahaBawah:"",aSayap:"",aPunggung:"",aLeher:"",
   aHati:19.5,aAmpela:17.6,aJantung:4.9,aUsus:11.7,aCeker:43.9,aKepala:29.3,aKulit:48.8,aDarah:34.1,aBulu:78.0},

  {id:"RPA003",flockId:"",flockName:"Kandang G Periode 8",breed:"Cobb 500",
   tglPotong:"2026-04-20",jumlahEkor:1000,beratRataHidup:2.00,hargaBeliPerEkor:45000,
   status:"Selesai",buyer:"Supermarket Segar Jaya",notes:"Dijual potongan retail",
   modePenjualan:"potongan",pctKarkas:73,
   hJualDada:45000,hJualPahaAtas:40000,hJualPahaBawah:38000,hJualSayap:34000,
   hJualPunggung:19000,hJualLeher:16000,hJualTulang:5000,
   hJualCeker:24000,hJualHati:30000,hJualAmpela:27000,hJualJantung:32000,
   hJualUsus:13000,hJualKepala:9000,hJualKulit:20000,
   bListrik:150,bUpah:220,bKemasan:100,bSanitasi:35,bTransport:110,bRetribusi:50,bLainnya:100,
   aKarkas:1460.0,aDaging:880.0,aTulang:321.0,aDada:438.0,aPahaAtas:263.0,aPahaBawah:204.0,aSayap:146.0,aPunggung:204.0,aLeher:58.0,
   aHati:40.0,aAmpela:36.0,aJantung:10.0,aUsus:24.0,aCeker:90.0,aKepala:60.0,aKulit:100.0,aDarah:70.0,aBulu:160.0},

  {id:"RPA004",flockId:"",flockName:"Kandang H Periode 7",breed:"Ross 308",
   tglPotong:"2026-04-01",jumlahEkor:1500,beratRataHidup:2.10,hargaBeliPerEkor:47000,
   status:"Selesai",buyer:"PT Charoen Pokhpand Distribution",notes:"Karkas beku IQF",
   modePenjualan:"beku",pctKarkas:74,
   hJualDada:44000,hJualPahaAtas:40000,hJualPahaBawah:38000,hJualSayap:34000,
   hJualPunggung:19000,hJualLeher:16000,hJualTulang:5000,
   hJualCeker:23000,hJualHati:29000,hJualAmpela:26000,hJualJantung:31000,
   hJualUsus:12000,hJualKepala:8500,hJualKulit:19000,
   bListrik:160,bUpah:210,bKemasan:120,bSanitasi:35,bTransport:120,bRetribusi:50,bLainnya:105,
   aKarkas:"",aDaging:"",aTulang:"",aDada:"",aPahaAtas:"",aPahaBawah:"",aSayap:"",aPunggung:"",aLeher:"",
   aHati:"",aAmpela:"",aJantung:"",aUsus:"",aCeker:"",aKepala:"",aKulit:"",aDarah:"",aBulu:""},

  {id:"RPA005",flockId:"",flockName:"Kandang I Periode 6",breed:"Cobb 500",
   tglPotong:"2026-03-15",jumlahEkor:2000,beratRataHidup:2.05,hargaBeliPerEkor:46000,
   status:"Selesai",buyer:"Pabrik Nugget PT Sierad",notes:"MDF untuk nugget ayam",
   modePenjualan:"mdf",pctKarkas:73,
   hJualDada:28000,hJualPahaAtas:26000,hJualPahaBawah:24000,hJualSayap:20000,
   hJualPunggung:16000,hJualLeher:14000,hJualTulang:5000,
   hJualCeker:22000,hJualHati:28000,hJualAmpela:25000,hJualJantung:30000,
   hJualUsus:10000,hJualKepala:7000,hJualKulit:16000,
   bListrik:145,bUpah:195,bKemasan:75,bSanitasi:28,bTransport:95,bRetribusi:50,bLainnya:87,
   aKarkas:2993.0,aDaging:1800.0,aTulang:659.0,aDada:897.0,aPahaAtas:538.0,aPahaBawah:419.0,aSayap:299.0,aPunggung:419.0,aLeher:120.0,
   aHati:82.0,aAmpela:74.0,aJantung:20.5,aUsus:49.2,aCeker:184.5,aKepala:123.0,aKulit:205.0,aDarah:143.5,aBulu:328.0},

  {id:"RPA006",flockId:"",flockName:"Kandang J Periode 5",breed:"Hubbard",
   tglPotong:"2026-03-01",jumlahEkor:2500,beratRataHidup:2.20,hargaBeliPerEkor:49000,
   status:"Selesai",buyer:"Katering Hotel Santika",notes:"Potongan dada & paha premium",
   modePenjualan:"potongan",pctKarkas:72,
   hJualDada:46000,hJualPahaAtas:41000,hJualPahaBawah:39000,hJualSayap:35000,
   hJualPunggung:20000,hJualLeher:17000,hJualTulang:5500,
   hJualCeker:25000,hJualHati:31000,hJualAmpela:28000,hJualJantung:33000,
   hJualUsus:13000,hJualKepala:9000,hJualKulit:21000,
   bListrik:155,bUpah:215,bKemasan:110,bSanitasi:32,bTransport:115,bRetribusi:55,bLainnya:98,
   aKarkas:"",aDaging:"",aTulang:"",aDada:"",aPahaAtas:"",aPahaBawah:"",aSayap:"",aPunggung:"",aLeher:"",
   aHati:"",aAmpela:"",aJantung:"",aUsus:"",aCeker:"",aKepala:"",aKulit:"",aDarah:"",aBulu:""},

  {id:"RPA007",flockId:"",flockName:"Kandang K Periode 4",breed:"Ross 308",
   tglPotong:"2026-02-15",jumlahEkor:3000,beratRataHidup:2.15,hargaBeliPerEkor:48000,
   status:"Selesai",buyer:"Distributor Jatim PT Maju Jaya",notes:"Karkas segar ke distributor",
   modePenjualan:"karkas",pctKarkas:74,
   hJualDada:43000,hJualPahaAtas:39000,hJualPahaBawah:37000,hJualSayap:33000,
   hJualPunggung:19000,hJualLeher:16000,hJualTulang:5000,
   hJualCeker:23000,hJualHati:29000,hJualAmpela:26000,hJualJantung:31000,
   hJualUsus:12000,hJualKepala:8500,hJualKulit:19000,
   bListrik:150,bUpah:200,bKemasan:85,bSanitasi:30,bTransport:100,bRetribusi:50,bLainnya:90,
   aKarkas:4772.1,aDaging:2878.5,aTulang:1049.9,aDada:863.3,aPahaAtas:518.0,aPahaBawah:403.1,aSayap:287.9,aPunggung:403.1,aLeher:115.2,
   aHati:129.0,aAmpela:116.1,aJantung:32.3,aUsus:77.4,aCeker:290.3,aKepala:193.5,aKulit:322.5,aDarah:225.8,aBulu:516.0},

  {id:"RPA008",flockId:"",flockName:"Kandang L Periode 3",breed:"Cobb 500",
   tglPotong:"2026-02-01",jumlahEkor:4000,beratRataHidup:2.00,hargaBeliPerEkor:45000,
   status:"Selesai",buyer:"Pabrik Sosis PT So Good",notes:"MDF + ceker export grade",
   modePenjualan:"mdf",pctKarkas:73,
   hJualDada:29000,hJualPahaAtas:27000,hJualPahaBawah:25000,hJualSayap:21000,
   hJualPunggung:16000,hJualLeher:14000,hJualTulang:5000,
   hJualCeker:26000,hJualHati:28000,hJualAmpela:25000,hJualJantung:30000,
   hJualUsus:10000,hJualKepala:7000,hJualKulit:16000,
   bListrik:140,bUpah:190,bKemasan:75,bSanitasi:28,bTransport:95,bRetribusi:50,bLainnya:85,
   aKarkas:5840.0,aDaging:3520.0,aTulang:1284.8,aDada:1056.0,aPahaAtas:633.6,aPahaBawah:492.8,aSayap:352.0,aPunggung:492.8,aLeher:140.8,
   aHati:160.0,aAmpela:144.0,aJantung:40.0,aUsus:96.0,aCeker:360.0,aKepala:240.0,aKulit:400.0,aDarah:280.0,aBulu:640.0},

  {id:"RPA009",flockId:"",flockName:"Kandang M Periode 2",breed:"Ross 308",
   tglPotong:"2026-01-15",jumlahEkor:4500,beratRataHidup:2.10,hargaBeliPerEkor:47000,
   status:"Selesai",buyer:"PT Bernofarm & Supermarket Chain",notes:"Split: potongan + ceker export",
   modePenjualan:"potongan",pctKarkas:74,
   hJualDada:44000,hJualPahaAtas:40000,hJualPahaBawah:38000,hJualSayap:34000,
   hJualPunggung:20000,hJualLeher:17000,hJualTulang:5500,
   hJualCeker:28000,hJualHati:30000,hJualAmpela:27000,hJualJantung:32000,
   hJualUsus:12000,hJualKepala:8500,hJualKulit:20000,
   bListrik:155,bUpah:210,bKemasan:95,bSanitasi:32,bTransport:110,bRetribusi:55,bLainnya:98,
   aKarkas:"",aDaging:"",aTulang:"",aDada:"",aPahaAtas:"",aPahaBawah:"",aSayap:"",aPunggung:"",aLeher:"",
   aHati:"",aAmpela:"",aJantung:"",aUsus:"",aCeker:"",aKepala:"",aKulit:"",aDarah:"",aBulu:""},

  {id:"RPA010",flockId:"",flockName:"Kandang N Periode 1",breed:"Cobb 500",
   tglPotong:"2025-12-20",jumlahEkor:5000,beratRataHidup:2.25,hargaBeliPerEkor:50000,
   status:"Selesai",buyer:"PT Charoen Pokhpand + Export Malaysia",notes:"Batch terbesar, IQF export grade",
   modePenjualan:"beku",pctKarkas:73,
   hJualDada:46000,hJualPahaAtas:41000,hJualPahaBawah:39000,hJualSayap:35000,
   hJualPunggung:21000,hJualLeher:17000,hJualTulang:6000,
   hJualCeker:28000,hJualHati:32000,hJualAmpela:29000,hJualJantung:35000,
   hJualUsus:14000,hJualKepala:10000,hJualKulit:22000,
   bListrik:165,bUpah:220,bKemasan:130,bSanitasi:38,bTransport:130,bRetribusi:60,bLainnya:112,
   aKarkas:8213.0,aDaging:4950.0,aTulang:1806.9,aDada:1485.0,aPahaAtas:891.0,aPahaBawah:693.0,aSayap:495.0,aPunggung:693.0,aLeher:198.0,
   aHati:225.0,aAmpela:202.5,aJantung:56.3,aUsus:135.0,aCeker:506.3,aKepala:337.5,aKulit:562.5,aDarah:393.8,aBulu:900.0},
];

/* ================================================================
   hitungRPABroiler — Kalkulasi RPA per batch
================================================================ */
const hitungRPABroiler = (rec) => {
  const S      = RPH_STANDAR_BROILER;
  const n      = +rec.jumlahEkor || 0; if (!n) return null;
  const bbRata = +rec.beratRataHidup || 0;
  const bbTotal= +(n * bbRata).toFixed(1);
  const hBeli  = +rec.hargaBeliPerEkor || 0;
  const totalBeli = n * hBeli;
  const pctK   = (+rec.pctKarkas || 72) / 100;
  const hasVal = v => v !== "" && v !== undefined && v !== null;

  // Estimasi karkas total
  const karkasEst    = +(bbTotal * pctK).toFixed(1);
  const beratKarkas  = hasVal(rec.aKarkas)  ? +rec.aKarkas  : karkasEst;

  // Harga jual map
  const hMap = {
    dada:      +(rec.hJualDada||42000),     paha_atas:  +(rec.hJualPahaAtas||38000),
    paha_bawah:+(rec.hJualPahaBawah||36000),sayap:      +(rec.hJualSayap||32000),
    punggung:  +(rec.hJualPunggung||18000), leher:      +(rec.hJualLeher||15000),
    karkas_utuh:+(rec.hJualDada||32000),
  };
  // Aktual map per potongan
  const aMap = {
    dada:rec.aDada, paha_atas:rec.aPahaAtas, paha_bawah:rec.aPahaBawah,
    sayap:rec.aSayap, punggung:rec.aPunggung, leher:rec.aLeher,
  };

  // Potongan (skip karkas_utuh dalam detail, hitung terpisah)
  const potonganDetail = S.potongan_primer.filter(p=>p.kode!=="karkas_utuh").map(p => {
    const est    = +(bbTotal * p.pct / 100).toFixed(1);
    const aktual = hasVal(aMap[p.kode]);
    const berat  = aktual ? +aMap[p.kode] : est;
    const harga  = hMap[p.kode] || p.harga;
    return { ...p, beratKg:berat, aktual, harga, pend:Math.round(berat*harga) };
  });

  const beratTulang = hasVal(rec.aTulang)
    ? +rec.aTulang
    : +(beratKarkas * S.pct_tulang / 100).toFixed(1);
  const totalDaging  = hasVal(rec.aDaging)
    ? +rec.aDaging
    : +potonganDetail.reduce((s,p)=>s+p.beratKg,0).toFixed(1);
  const hTulang = +(rec.hJualTulang||5000);
  const pendTulang = Math.round(beratTulang * hTulang);

  // By-products
  const bpAMap = {
    "Kepala":rec.aKepala,"Ceker (Kaki)":rec.aCeker,"Hati":rec.aHati,
    "Ampela (Gizzard)":rec.aAmpela,"Jantung":rec.aJantung,"Usus":rec.aUsus,
    "Kulit Ayam":rec.aKulit,"Darah (L)":rec.aDarah,"Bulu+Limbah":rec.aBulu,
  };
  const byProducts = S.by_products.map(bp => {
    const aktual = hasVal(bpAMap[bp.nama]);
    const berat  = aktual ? +bpAMap[bp.nama] : +(bbTotal*bp.pct_live/100).toFixed(1);
    return { ...bp, beratKg:berat, aktual, pend:Math.round(berat*bp.harga) };
  });

  // Biaya operasional
  const biayaPerEkor = (+(rec.bListrik||150))+(+(rec.bUpah||200))+(+(rec.bKemasan||80))+(+(rec.bSanitasi||30))+(+(rec.bTransport||100))+(+(rec.bRetribusi||50))+(+(rec.bLainnya||90));
  const totalBiayaOps = biayaPerEkor * n;
  const totalBiaya    = totalBeli + totalBiayaOps;

  // Pendapatan mode penjualan
  const pendDaging   = potonganDetail.reduce((s,p)=>s+p.pend,0);
  const pendByP      = byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.pend,0);
  const pendTotal    = pendDaging + pendTulang + pendByP;
  const profit       = pendTotal - totalBiaya;
  const roi          = totalBiaya>0 ? ((profit/totalBiaya)*100).toFixed(1) : "0";
  const hppPerKg     = totalDaging>0 ? Math.round(totalBiaya/totalDaging) : 0;
  const hppPerEkor   = n>0 ? Math.round(totalBiaya/n) : 0;
  const fcr          = bbTotal>0 ? (totalBiaya/(pendTotal||1)).toFixed(3) : "—";
  const hasAktual    = Object.keys(rec).some(k=>k.startsWith("a")&&hasVal(rec[k])&&rec[k]!==0);

  // Produktivitas
  const yieldKarkas   = bbTotal>0 ? +(beratKarkas/bbTotal*100).toFixed(1) : 0;
  const yieldDaging   = beratKarkas>0 ? +(totalDaging/beratKarkas*100).toFixed(1) : 0;
  const beratSusut    = +(beratKarkas - totalDaging - beratTulang).toFixed(1);

  return {
    n, bbRata, bbTotal, beratKarkas, pctKarkas:pctK*100,
    totalDaging, beratTulang, beratSusut,
    potongan:potonganDetail, byProducts,
    biayaPerEkor, totalBiayaOps, totalBeli, totalBiaya,
    pendDaging, pendTulang, pendByP, pendTotal,
    profit, roi, hppPerKg, hppPerEkor, hasAktual,
    yieldKarkas, yieldDaging,
    biaya:{listrik:+(rec.bListrik||150),upah:+(rec.bUpah||200),kemasan:+(rec.bKemasan||80),
           sanitasi:+(rec.bSanitasi||30),transport:+(rec.bTransport||100),
           retribusi:+(rec.bRetribusi||50),lainnya:+(rec.bLainnya||90)},
  };
};

/* ================================================================
   PageRPABroiler — Halaman RPA Ayam Broiler
================================================================ */
const PageRPABroiler = ({ records=[], setRecords, flocks=[] }) => {
  const AC = "#e879f9";
  const [tab,      setTab]      = useState("kalkulator");
  const [form,     setF0]       = useState(null);
  const [preview,  setPreview]  = useState(null);
  const [activeId, setActiveId] = useState(null);
  const [subTab,   setSubTab]   = useState("ringkasan");

  const S = RPH_STANDAR_BROILER;

  const blankB = {
    flockId:"", flockName:"", breed:"Cobb 500",
    tglPotong:new Date().toISOString().split("T")[0],
    jumlahEkor:"", beratRataHidup:"", hargaBeliPerEkor:"",
    modePenjualan:"karkas", pctKarkas:73, status:"Selesai", buyer:"", notes:"",
    hJualDada:42000, hJualPahaAtas:38000, hJualPahaBawah:36000,
    hJualSayap:32000, hJualPunggung:18000, hJualLeher:15000, hJualTulang:5000,
    hJualCeker:22000, hJualHati:28000, hJualAmpela:25000, hJualJantung:30000,
    hJualUsus:12000, hJualKepala:8000, hJualKulit:18000,
    bListrik:150, bUpah:200, bKemasan:80, bSanitasi:30, bTransport:100, bRetribusi:50, bLainnya:90,
    aKarkas:"", aDaging:"", aTulang:"",
    aDada:"", aPahaAtas:"", aPahaBawah:"", aSayap:"", aPunggung:"", aLeher:"",
    aHati:"", aAmpela:"", aJantung:"", aUsus:"", aCeker:"", aKepala:"", aKulit:"", aDarah:"", aBulu:"",
  };

  const f   = form || blankB;
  const setF = patch => { const nf={...f,...patch}; setF0(nf); setPreview(hitungRPABroiler(nf)); };

  const saveRecord = () => {
    if (!f.jumlahEkor || !f.hargaBeliPerEkor) return;
    const fk = flocks.find(x=>x.id===f.flockId);
    const id = "RPA"+String(records.length+1).padStart(3,"0");
    setRecords([{id,...f,jumlahEkor:+f.jumlahEkor,beratRataHidup:+f.beratRataHidup,
      hargaBeliPerEkor:+f.hargaBeliPerEkor,pctKarkas:+f.pctKarkas,
      flockName:fk?fk.name:f.flockName},...records]);
    setF0(null); setPreview(null);
  };

  // Cetak laporan
  const cetakLaporan = (rec, c) => {
    const rp = n => "Rp "+new Intl.NumberFormat("id-ID").format(Math.round(n||0));
    const rowsPot = c.potongan.map((p,i) =>
      "<tr><td>"+(i+1)+"</td><td><b>"+p.nama+"</b></td><td>"+p.grade+"</td>"
      +"<td><b>"+p.beratKg+" kg</b></td><td>"+(p.beratKg/c.bbTotal*100).toFixed(2)+"%</td>"
      +"<td>"+rp(p.harga)+"/kg</td><td class='green'>"+rp(p.pend)+"</td>"
      +"<td><span class='"+(p.aktual?"badge-a":"badge-e")+"'>"+(p.aktual?"Aktual":"Est.")+"</span></td></tr>"
    ).join("");
    const rowsByP = c.byProducts.map(b =>
      "<tr><td><b>"+b.nama+"</b></td><td>"+b.kat+"</td><td>"+b.beratKg+" kg</td>"
      +"<td>"+(b.beratKg/c.bbTotal*100).toFixed(2)+"%</td>"
      +"<td>"+rp(b.harga)+"/kg</td><td class='green'>"+rp(b.pend)+"</td>"
      +"<td><span class='"+(b.aktual?"badge-a":"badge-e")+"'>"+(b.aktual?"Aktual":"Est.")+"</span></td></tr>"
    ).join("");
    const css="*{margin:0;padding:0;box-sizing:border-box}body{font-family:'Segoe UI',Arial,sans-serif;font-size:11px;color:#111;padding:12mm}h1{font-size:16px;font-weight:800;margin-bottom:3px;color:#7e22ce}h2{font-size:12px;font-weight:700;color:#7e22ce;margin:12px 0 5px;border-bottom:2px solid #7e22ce;padding-bottom:2px}.meta{color:#666;font-size:10px;margin-bottom:8px}.hbox{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:9px 13px;margin-bottom:10px;display:flex;gap:18px;flex-wrap:wrap}.hbox .s{text-align:center}.hbox .v{font-size:14px;font-weight:800;color:#7e22ce}.hbox .k{font-size:9px;color:#888;text-transform:uppercase}table{width:100%;border-collapse:collapse;margin-bottom:9px;font-size:10px}th{background:#7e22ce;color:#fff;padding:5px 7px;text-align:left;font-size:9px;text-transform:uppercase}td{padding:4px 7px;border-bottom:1px solid #eee}tr:nth-child(even)td{background:#fafafa}.tr{font-weight:700;background:#f0e6ff}.g2{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-bottom:9px}.card{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:8px 11px}.card .r{display:flex;justify-content:space-between;padding:3px 0;border-bottom:1px solid #eee;font-size:10px}.green{color:#1a7a1a;font-weight:700}.red{color:#7e22ce;font-weight:700}.badge-a{background:#e8f8e8;color:#1a7a1a;border:1px solid #1a7a1a;border-radius:9px;padding:1px 5px;font-size:8px;font-weight:700}.badge-e{background:#f5e6ff;color:#7e22ce;border:1px solid #a855f7;border-radius:9px;padding:1px 5px;font-size:8px;font-weight:700}.ind-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:7px;margin-bottom:9px}.ind{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:7px 9px;text-align:center}.ind .v{font-size:14px;font-weight:800;color:#7e22ce}.ind .k{font-size:8px;color:#888;text-transform:uppercase}.footer{margin-top:14px;padding-top:7px;border-top:1px solid #ddd;color:#999;font-size:9px;text-align:center}@media print{body{padding:8mm}@page{size:A4;margin:8mm}}";
    const infoCards=[["Kandang",rec.flockName||"—"],["Strain",rec.breed],["Tgl Potong",rec.tglPotong],["Jumlah",c.n.toLocaleString("id-ID")+" ekor"],["BH Rata",c.bbRata+" kg/ekor"],["BB Total",c.bbTotal+" kg"],["Mode",rec.modePenjualan||"karkas"],["Pembeli",rec.buyer||"—"]].map(([k,v])=>"<div class='s'><div class='v'>"+v+"</div><div class='k'>"+k+"</div></div>").join("");
    const indCards=[["Profit Bersih",rp(c.profit)],["ROI",c.roi+"%"],["HPP/kg daging",rp(c.hppPerKg)+"/kg"],["HPP/ekor",rp(c.hppPerEkor)+"/ekor"],["Yield Karkas",c.yieldKarkas+"%"],["Yield Daging",c.yieldDaging+"%"]].map(([k,v])=>"<div class='ind'><div class='v'>"+v+"</div><div class='k'>"+k+"</div></div>").join("");
    const biayaRows=[["Harga Beli ("+c.n+" ekor)",rp(c.totalBeli)],["Listrik & Air",rp(c.biaya.listrik*c.n)],["Upah Tenaga",rp(c.biaya.upah*c.n)],["Kemasan",rp(c.biaya.kemasan*c.n)],["Sanitasi",rp(c.biaya.sanitasi*c.n)],["Transportasi",rp(c.biaya.transport*c.n)],["Retribusi RPA",rp(c.biaya.retribusi*c.n)],["Lainnya",rp(c.biaya.lainnya*c.n)],["Total Ops",rp(c.totalBiayaOps)],["TOTAL BIAYA",rp(c.totalBiaya)]].map(([k,v])=>"<div class='r'><span>"+k+"</span><span class='red'>"+v+"</span></div>").join("");
    const pendRows=[["Daging (potongan)",rp(c.pendDaging)],["Tulang",rp(c.pendTulang)],["Jeroan & By-Product",rp(c.pendByP)],["TOTAL PENDAPATAN",rp(c.pendTotal)],["PROFIT BERSIH",rp(c.profit)],["ROI",c.roi+"%"],["HPP/kg daging",rp(c.hppPerKg)+"/kg"]].map(([k,v])=>"<div class='r'><span>"+k+"</span><span class='green'>"+v+"</span></div>").join("");
    const html=["<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'/><title>Laporan RPA Broiler - "+(rec.flockName||rec.id)+"</title><style>"+css+"</style></head><body>",
      "<h1>🐔 Laporan Pemotongan Ayam Broiler (RPA)</h1>",
      "<p class='meta'>ID: "+rec.id+" | Dicetak: "+new Date().toLocaleString("id-ID")+" | Status: "+rec.status+"</p>",
      "<div class='hbox'>"+infoCards+"</div>",
      "<div class='ind-grid'>"+indCards+"</div>",
      "<h2>I. Neraca Bobot Batch ("+c.n.toLocaleString("id-ID")+" ekor)</h2>",
      "<table><thead><tr><th>Komponen</th><th>Berat Total (kg)</th><th>Per Ekor (kg)</th><th>% BH Total</th></tr></thead><tbody>",
      [["BH Total",c.bbTotal,c.bbRata,"100%"],["Karkas",c.beratKarkas,+(c.beratKarkas/c.n).toFixed(3),c.yieldKarkas+"%"],["— Daging",c.totalDaging,+(c.totalDaging/c.n).toFixed(3),+(c.totalDaging/c.bbTotal*100).toFixed(1)+"%"],["— Tulang",c.beratTulang,+(c.beratTulang/c.n).toFixed(3),+(c.beratTulang/c.bbTotal*100).toFixed(1)+"%"],["— Lemak/Trim",Math.max(0,c.beratSusut).toFixed(1),+(Math.max(0,c.beratSusut)/c.n).toFixed(3),+(Math.max(0,c.beratSusut)/c.bbTotal*100).toFixed(1)+"%"],["By-Product (edible)",+(c.byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.beratKg,0)).toFixed(1),"—","—"],["Bulu+Limbah",+(c.byProducts.filter(b=>b.kat==="Limbah").reduce((s,b)=>s+b.beratKg,0)).toFixed(1),"—","—"]].map(([k,v,pe,p])=>"<tr><td><b>"+k+"</b></td><td>"+v+" kg</td><td>"+pe+" kg</td><td>"+p+"</td></tr>").join(""),
      "</tbody></table>",
      "<h2>II. Rincian Potongan Daging</h2>",
      "<table><thead><tr><th>No</th><th>Potongan</th><th>Grade</th><th>Berat Total</th><th>% BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead><tbody>",
      rowsPot,
      "<tr class='tr'><td colspan='3'>TOTAL DAGING</td><td>"+c.totalDaging+" kg</td><td>"+(c.totalDaging/c.bbTotal*100).toFixed(2)+"%</td><td></td><td class='green'>"+rp(c.pendDaging)+"</td><td></td></tr>",
      "<tr><td colspan='3'>Tulang</td><td>"+c.beratTulang+" kg</td><td>"+(c.beratTulang/c.bbTotal*100).toFixed(2)+"%</td><td>"+rp(+(rec.hJualTulang||5000))+"/kg</td><td>"+rp(c.pendTulang)+"</td><td></td></tr>",
      "</tbody></table>",
      "<h2>III. By-Product & Jeroan</h2>",
      "<table><thead><tr><th>Produk</th><th>Kategori</th><th>Berat Total</th><th>% BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead><tbody>",
      rowsByP,
      "</tbody></table>",
      "<div class='g2'><div class='card'><b>Rincian Biaya</b>"+biayaRows+"</div><div class='card'><b>Rincian Pendapatan</b>"+pendRows+"</div></div>",
      rec.notes?"<p style='background:#f5f5f5;padding:8px 11px;border-radius:5px;border:1px solid #ddd;font-size:11px;margin-bottom:9px'><b>Catatan:</b> "+rec.notes+"</p>":"",
      "<div class='footer'><b>TernakPro RPA Broiler</b> | "+rec.id+" | "+rec.tglPotong+"</div>",
      "<script>window.onload=function(){setTimeout(function(){window.print()},300)}</script>",
      "</body></html>"].join("");
    const blob=new Blob([html],{type:"text/html"});
    const url=URL.createObjectURL(blob);
    const a=document.createElement("a");
    a.href=url;a.target="_blank";a.click();
    setTimeout(()=>URL.revokeObjectURL(url),5000);
  };

  // ── UI Helpers ──
  const Inp = ({label,value,onChange,type="text",options,small,placeholder,hl}) => (
    <div>
      <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:3}}>{label}</label>
      {options?(
        <select value={value||""} onChange={e=>onChange(e.target.value)} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:small?"5px 8px":"8px 11px",color:"#e2e4f0",fontSize:small?11:13,width:"100%",outline:"none"}}>
          {options.map(o=><option key={o.v??o} value={o.v??o}>{o.l??o}</option>)}
        </select>
      ):(
        <input type={type} value={value||""} onChange={e=>onChange(e.target.value)} placeholder={placeholder||""} style={{background:"#13161f",border:"1px solid "+(hl&&value?"#e879f940":"#252535"),borderRadius:8,padding:small?"5px 8px":"8px 11px",color:"#e2e4f0",fontSize:small?11:13,width:"100%",outline:"none",boxSizing:"border-box"}}/>
      )}
    </div>
  );

  const BarChartB = ({data,title,height=110}) => {
    const max=Math.max(...data.map(d=>d.value||0),1);
    const W=440;const bw=Math.floor((W-14)/data.length)-2;
    return (
      <div style={{background:"#0a0c16",borderRadius:10,padding:"10px 12px"}}>
        <div style={{color:"#9097a8",fontSize:10,fontWeight:700,marginBottom:6}}>{title}</div>
        <svg width="100%" viewBox={"0 0 "+W+" "+(height+38)} style={{overflow:"visible"}}>
          {data.map((d,i)=>{
            const bh=Math.max(2,(d.value/max)*height);
            const x=7+i*(bw+2);const y=height-bh+2;const col=d.color||AC;
            return (<g key={i}>
              <rect x={x} y={y} width={bw} height={bh} rx={2} fill={col} opacity={0.82}/>
              {d.value>0&&<text x={x+bw/2} y={y-2} textAnchor="middle" fill={col} fontSize={6} fontWeight="700">{d.label2||""}</text>}
              <text x={x+bw/2} y={height+20} textAnchor="middle" fill="#555a6a" fontSize={6.5} transform={"rotate(-38,"+(x+bw/2)+","+(height+20)+")"}>
                {d.label.length>9?d.label.slice(0,8)+"…":d.label}
              </text>
            </g>);
          })}
          <line x1={7} y1={height+2} x2={W-7} y2={height+2} stroke="#252535" strokeWidth={1}/>
        </svg>
      </div>
    );
  };

  const gradeCA = g => g==="Premium"?"#e879f9":g==="Superior"?"#3b82f6":"#9097a8";
  const thA={padding:"8px 10px",color:"#555a6a",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap",borderBottom:"1px solid #1c1e2b"};
  const tdA=(col="#e2e4f0",bold=false)=>({padding:"8px 10px",color:col,fontWeight:bold?700:400,fontSize:12});
  const BadgeB=({isA})=>(<span style={{background:isA?"#22c55e18":"#e879f918",color:isA?"#22c55e":"#e879f9",border:"1px solid "+(isA?"#22c55e30":"#e879f930"),borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>{isA?"✅":"📊"}</span>);
  const modeLabel={karkas:"🐔 Karkas Utuh",potongan:"🥩 Potongan Retail",beku:"❄️ Karkas Beku (IQF)",mdf:"🔩 MDF/Daging Giling"};

  const totalPend=records.reduce((s,r)=>{const c=hitungRPABroiler(r);return c?s+c.pendTotal:s;},0);
  const totalProf=records.reduce((s,r)=>{const c=hitungRPABroiler(r);return c?s+c.profit:s;},0);
  const totalEkor=records.reduce((s,r)=>s+(+r.jumlahEkor||0),0);

  return (
    <div style={{display:"flex",flexDirection:"column",gap:16}}>
      {/* STAT CARDS */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))",gap:12}}>
        {[["Total Batch",records.length+" batch",AC,"📋"],
          ["Total Ekor",(totalEkor/1000).toFixed(1)+"rb ekor","#f59e0b","🐔"],
          ["Total Pendapatan","Rp "+(totalPend/1e6).toFixed(1)+"jt","#3b82f6","💰"],
          ["Total Profit","Rp "+(totalProf/1e6).toFixed(1)+"jt",totalProf>=0?"#22c55e":"#ef4444","📊"],
          ["Ayam Siap Panen",flocks.filter(x=>x.status==="Siap Panen").length+" kandang","#a3e635","⚡"],
        ].map(([l,v,c,e])=>(
          <div key={l} style={{background:c+"0c",border:"1px solid "+c+"25",borderRadius:13,padding:"14px 16px",position:"relative",overflow:"hidden"}}>
            <div style={{position:"absolute",top:10,right:12,fontSize:22,opacity:0.13}}>{e}</div>
            <div style={{fontSize:10,color:"#555a6a",textTransform:"uppercase",letterSpacing:1.5,fontWeight:700,marginBottom:4}}>{l}</div>
            <div style={{fontSize:17,fontWeight:800,color:c}}>{v}</div>
            <div style={{position:"absolute",bottom:0,left:0,right:0,height:2,background:"linear-gradient(90deg,"+c+",transparent)"}}/>
          </div>
        ))}
      </div>

      {/* TABS */}
      <div style={{display:"flex",borderBottom:"1px solid #1c1e2b"}}>
        {[{id:"kalkulator",l:"🔢 Kalkulator"},{id:"riwayat",l:"📋 Riwayat Pemotongan"},{id:"standar",l:"📊 Tabel Standar"}].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)} style={{background:"none",border:"none",borderBottom:"2px solid "+(tab===t.id?AC:"transparent"),color:tab===t.id?AC:"#555a6a",padding:"8px 18px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>{t.l}</button>
        ))}
      </div>

      {/* ═══ TAB KALKULATOR ═══ */}
      {tab==="kalkulator" && (
        <div style={{display:"grid",gridTemplateColumns:"360px 1fr",gap:18,alignItems:"start"}}>
          {/* INPUT */}
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:18,display:"flex",flexDirection:"column",gap:13,maxHeight:"88vh",overflowY:"auto"}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:15,fontWeight:700}}>🐔 Data Batch Ayam</div>
            <div>
              <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:4}}>Pilih Kandang (opsional)</label>
              <select value={f.flockId} onChange={e=>{
                const fk=flocks.find(x=>x.id===e.target.value);
                const pct=fk?(S.persen_karkas[fk.breed]||S.persen_karkas.default).jantan:f.pctKarkas;
                setF({flockId:e.target.value,flockName:fk?fk.name:"",breed:fk?fk.breed:f.breed,
                  jumlahEkor:fk?fk.jumlah:f.jumlahEkor,beratRataHidup:fk?fk.beratRata:f.beratRataHidup,pctKarkas:pct});
              }} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:"8px 11px",color:"#e2e4f0",fontSize:13,width:"100%"}}>
                <option value="">-- Pilih atau isi manual --</option>
                {flocks.map(fk=><option key={fk.id} value={fk.id}>{fk.name} ({fk.breed}) — {fk.jumlah.toLocaleString("id-ID")} ekor</option>)}
              </select>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              <Inp label="Jumlah Ekor" value={f.jumlahEkor} onChange={v=>setF({jumlahEkor:v})} type="number"/>
              <Inp label="Berat Rata-rata (kg/ekor)" value={f.beratRataHidup} onChange={v=>setF({beratRataHidup:v})} type="number"/>
              <Inp label="Strain/Breed" value={f.breed} onChange={v=>setF({breed:v})} options={["Cobb 500","Ross 308","Hubbard","Lohmann","Lokal/Kampung"]}/>
              <Inp label="% Karkas" value={f.pctKarkas} onChange={v=>setF({pctKarkas:v})} type="number"/>
              <Inp label="Harga Beli/Ekor (Rp)" value={f.hargaBeliPerEkor} onChange={v=>setF({hargaBeliPerEkor:v})} type="number"/>
              <Inp label="Mode Penjualan" value={f.modePenjualan} onChange={v=>setF({modePenjualan:v})} options={[{v:"karkas",l:"Karkas Utuh"},{v:"potongan",l:"Potongan Retail"},{v:"beku",l:"Karkas Beku (IQF)"},{v:"mdf",l:"MDF/Daging Giling"}]}/>
              <Inp label="Tanggal Potong" value={f.tglPotong} onChange={v=>setF({tglPotong:v})} type="date"/>
              <Inp label="Status" value={f.status} onChange={v=>setF({status:v})} options={["Selesai","Proses","Antrian"]}/>
              <Inp label="Pembeli" value={f.buyer} onChange={v=>setF({buyer:v})}/>
            </div>

            {/* Biaya per ekor */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#f59e0b",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>🏭 Biaya Operasional (per ekor)</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                {[["Listrik & Air","bListrik"],["Upah Tenaga","bUpah"],["Kemasan","bKemasan"],["Sanitasi","bSanitasi"],["Transportasi","bTransport"],["Retribusi RPA","bRetribusi"],["Lainnya","bLainnya"]].map(([l,k])=>(
                  <Inp key={k} label={l+" (Rp/ekor)"} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small/>
                ))}
              </div>
            </div>

            {/* Harga jual */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#3b82f6",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:9}}>💲 Harga Jual (Rp/kg)</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                {[["Dada","hJualDada"],["Paha Atas","hJualPahaAtas"],["Paha Bawah","hJualPahaBawah"],["Sayap","hJualSayap"],["Punggung","hJualPunggung"],["Leher","hJualLeher"],["Tulang","hJualTulang"],["Ceker","hJualCeker"],["Hati","hJualHati"],["Ampela","hJualAmpela"],["Jantung","hJualJantung"],["Usus","hJualUsus"],["Kepala","hJualKepala"],["Kulit","hJualKulit"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small/>
                ))}
              </div>
            </div>

            {/* Berat aktual */}
            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:4}}>📏 Berat Aktual Batch (Opsional, kg total)</div>
              <div style={{fontSize:10,color:"#555a6a",marginBottom:9}}>Isi total berat seluruh batch. Kosong = estimasi %.</div>
              <div style={{color:"#e879f9",fontSize:10,fontWeight:700,marginBottom:5}}>Karkas & Potongan</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:5,marginBottom:9}}>
                {[["Karkas Total","aKarkas"],["Daging Total","aDaging"],["Tulang Total","aTulang"],["Dada","aDada"],["Paha Atas","aPahaAtas"],["Paha Bawah","aPahaBawah"],["Sayap","aSayap"],["Punggung","aPunggung"],["Leher","aLeher"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small placeholder="kg" hl/>
                ))}
              </div>
              <div style={{color:"#a855f7",fontSize:10,fontWeight:700,marginBottom:5}}>By-Product & Jeroan</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:5}}>
                {[["Hati","aHati"],["Ampela","aAmpela"],["Jantung","aJantung"],["Usus","aUsus"],["Ceker","aCeker"],["Kepala","aKepala"],["Kulit","aKulit"],["Darah","aDarah"],["Bulu+Limbah","aBulu"]].map(([l,k])=>(
                  <Inp key={k} label={l} value={f[k]} onChange={v=>setF({[k]:v})} type="number" small placeholder="kg" hl/>
                ))}
              </div>
            </div>

            <div style={{borderTop:"1px solid #1c1e2b",paddingTop:11}}>
              <label style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"block",marginBottom:4}}>Catatan</label>
              <textarea value={f.notes||""} onChange={e=>setF({notes:e.target.value})} rows={2} style={{background:"#13161f",border:"1px solid #252535",borderRadius:8,padding:"8px 11px",color:"#e2e4f0",fontSize:12,width:"100%",outline:"none",boxSizing:"border-box",resize:"vertical"}}/>
            </div>

            <button onClick={saveRecord} disabled={!f.jumlahEkor||!f.hargaBeliPerEkor} style={{background:(!f.jumlahEkor||!f.hargaBeliPerEkor)?"#333":AC,color:(!f.jumlahEkor||!f.hargaBeliPerEkor)?"#888":"#0a0c16",border:"none",borderRadius:10,padding:12,cursor:(!f.jumlahEkor||!f.hargaBeliPerEkor)?"not-allowed":"pointer",fontWeight:800,fontSize:14,width:"100%"}}>
              💾 Simpan ke Riwayat RPA
            </button>
          </div>

          {/* HASIL KALKULASI */}
          <div style={{display:"flex",flexDirection:"column",gap:13}}>
            {!preview ? (
              <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:48,textAlign:"center",color:"#555a6a",fontSize:13}}>← Isi data batch ayam di kiri</div>
            ) : (
              <>
                {/* Mode badge */}
                <div style={{background:AC+"0c",border:"1px solid "+AC+"25",borderRadius:11,padding:"10px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:8}}>
                  <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:15,fontWeight:700}}>
                    {modeLabel[f.modePenjualan]||"🐔 Karkas"} — {preview.n.toLocaleString("id-ID")} ekor @ {preview.bbRata} kg = {preview.bbTotal.toLocaleString("id-ID")} kg BH
                  </div>
                  <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
                    {[["Profit","Rp "+(preview.profit/1e6).toFixed(2)+"jt",preview.profit>=0?"#22c55e":"#ef4444"],
                      ["ROI",preview.roi+"%",+preview.roi>=15?"#22c55e":"#f59e0b"],
                      ["HPP/kg","Rp "+preview.hppPerKg.toLocaleString("id-ID"),"#f5c842"],
                      ["Yield Karkas",preview.yieldKarkas+"%","#e879f9"]].map(([k,v,col])=>(
                      <div key={k} style={{background:col+"12",border:"1px solid "+col+"28",borderRadius:9,padding:"6px 11px",textAlign:"center"}}>
                        <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                        <div style={{color:col,fontWeight:800,fontSize:13}}>{v}</div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* KPI grid */}
                <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(120px,1fr))",gap:9}}>
                  {[["BH Total",preview.bbTotal.toLocaleString("id-ID")+" kg","#e879f9",""],
                    ["Karkas Total",preview.beratKarkas.toLocaleString("id-ID")+" kg","#a3e635",preview.yieldKarkas+"% BH"],
                    ["Daging Total",preview.totalDaging.toLocaleString("id-ID")+" kg","#22c55e",preview.yieldDaging+"% karkas"],
                    ["Tulang Total",preview.beratTulang.toLocaleString("id-ID")+" kg","#9097a8",""],
                    ["Karkas/Ekor",+(preview.beratKarkas/preview.n).toFixed(3)+" kg","#e879f9","per ekor"],
                    ["Total Biaya","Rp "+(preview.totalBiaya/1e6).toFixed(2)+"jt","#ef4444",""],
                    ["Total Pend.","Rp "+(preview.pendTotal/1e6).toFixed(2)+"jt","#3b82f6",""],
                    ["HPP/ekor","Rp "+preview.hppPerEkor.toLocaleString("id-ID"),"#f59e0b",""],
                    ["Biaya Ops/ekor","Rp "+preview.biayaPerEkor.toLocaleString("id-ID"),"#9097a8",""],
                  ].map(([l,v,c,s])=>(
                    <div key={l} style={{background:"#ffffff07",borderRadius:9,padding:"9px 11px"}}>
                      <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",letterSpacing:1,marginBottom:3}}>{l}</div>
                      <div style={{color:c,fontWeight:700,fontSize:13,lineHeight:1.2}}>{v}</div>
                      {s&&<div style={{fontSize:10,color:"#555a6a",marginTop:2}}>{s}</div>}
                    </div>
                  ))}
                </div>

                {/* Breakdown pendapatan */}
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:9}}>
                  {[["🥩 Daging",preview.pendDaging,"#22c55e"],["🦴 Tulang",preview.pendTulang,"#9097a8"],["🫀 By-Product",preview.pendByP,"#a855f7"]].map(([l,v,c])=>(
                    <div key={l} style={{background:c+"0c",border:"1px solid "+c+"22",borderRadius:11,padding:13,textAlign:"center"}}>
                      <div style={{color:c,fontSize:11,fontWeight:700,marginBottom:3}}>{l}</div>
                      <div style={{color:c,fontSize:14,fontWeight:800}}>{"Rp "+(v/1e6).toFixed(2)+"jt"}</div>
                      <div style={{color:"#555a6a",fontSize:10,marginTop:2}}>{preview.pendTotal>0?((v/preview.pendTotal)*100).toFixed(1)+"%":"0%"}</div>
                    </div>
                  ))}
                </div>

                {/* Tabel Potongan */}
                <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:14,padding:17}}>
                  <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:11}}>🥩 Rincian Potongan Daging</div>
                  <div style={{overflowX:"auto"}}>
                    <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                      <thead><tr style={{background:"#22c55e09",borderBottom:"1px solid #22c55e22"}}>
                        {["Potongan","Grade","%BH","Berat Total","Per Ekor","Harga/kg","Nilai"].map(h=><th key={h} style={{...thA,color:"#22c55e"}}>{h}</th>)}
                      </tr></thead>
                      <tbody>
                        {preview.potongan.map((p,i)=>{
                          const gc=gradeCA(p.grade);
                          return (
                            <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:p.aktual?"#22c55e05":i%2?"#ffffff02":"transparent"}}>
                              <td style={tdA("#e2e4f0",true)}>{p.nama}{p.aktual&&<span style={{marginLeft:5,background:"#22c55e18",color:"#22c55e",border:"1px solid #22c55e30",borderRadius:20,padding:"1px 5px",fontSize:9,fontWeight:700}}>✅</span>}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 6px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                              <td style={tdA("#9097a8")}>{p.pct}%</td>
                              <td style={tdA("#e879f9",true)}>{p.beratKg.toLocaleString("id-ID")} kg</td>
                              <td style={tdA("#555a6a")}>{+(p.beratKg/preview.n).toFixed(3)} kg</td>
                              <td style={tdA("#9097a8")}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                              <td style={tdA("#22c55e",true)}>{"Rp "+p.pend.toLocaleString("id-ID")}</td>
                            </tr>
                          );
                        })}
                        <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}>
                          <td colSpan={3} style={{padding:"9px 10px",color:"#22c55e",fontWeight:800}}>TOTAL DAGING</td>
                          <td style={tdA("#e879f9",true)}>{preview.totalDaging.toLocaleString("id-ID")} kg</td>
                          <td style={tdA("#555a6a")}>{+(preview.totalDaging/preview.n).toFixed(3)} kg/ekor</td>
                          <td/><td style={tdA("#22c55e",true)}>{"Rp "+preview.pendDaging.toLocaleString("id-ID")}</td>
                        </tr>
                        <tr style={{background:"#9097a809"}}>
                          <td colSpan={2} style={tdA("#9097a8")}>Tulang</td>
                          <td style={tdA("#9097a8")}>{S.pct_tulang}%</td>
                          <td style={tdA("#9097a8",true)}>{preview.beratTulang.toLocaleString("id-ID")} kg</td>
                          <td style={tdA("#555a6a")}>{+(preview.beratTulang/preview.n).toFixed(3)} kg/ekor</td>
                          <td style={tdA("#9097a8")}>{"Rp "+(f.hJualTulang||5000).toLocaleString("id-ID")}</td>
                          <td style={tdA("#9097a8",true)}>{"Rp "+preview.pendTulang.toLocaleString("id-ID")}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                {/* By-product & Biaya */}
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:13}}>
                  <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:15}}>
                    <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>🫀 Jeroan & By-Product</div>
                    {preview.byProducts.map((b,i)=>{
                      const catC={"Fancy Meat":"#f5c842","Jeroan":"#ef4444","Kulit":"#f59e0b","Darah":"#ef4444","Limbah":"#555a6a"};
                      const cc=catC[b.kat]||"#666";
                      return (
                        <div key={b.nama} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"5px 0",borderBottom:"1px solid #1c1e2b"}}>
                          <div>
                            <span style={{fontSize:12,color:"#e2e4f0",fontWeight:600}}>{b.nama}</span>
                            {b.aktual&&<span style={{marginLeft:5,background:"#22c55e18",color:"#22c55e",borderRadius:20,padding:"1px 5px",fontSize:9,fontWeight:700}}>✅</span>}
                            <div style={{fontSize:10,color:"#555a6a"}}>{b.beratKg.toLocaleString("id-ID")} kg · {+(b.beratKg/preview.n).toFixed(3)} kg/ekor</div>
                          </div>
                          <span style={{color:b.kat==="Limbah"?"#555a6a":"#a855f7",fontWeight:700,fontSize:12}}>
                            {b.kat==="Limbah"?"—":"Rp "+b.pend.toLocaleString("id-ID")}
                          </span>
                        </div>
                      );
                    })}
                    <div style={{display:"flex",justifyContent:"space-between",padding:"7px 0",marginTop:4,borderTop:"2px solid #a855f733",fontWeight:800}}>
                      <span style={{color:"#a855f7",fontSize:12}}>TOTAL BY-PRODUCT</span>
                      <span style={{color:"#a855f7",fontSize:13}}>{"Rp "+preview.pendByP.toLocaleString("id-ID")}</span>
                    </div>
                  </div>
                  <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:15}}>
                    <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💸 Biaya & Keuangan</div>
                    {[["Harga Beli ("+preview.n.toLocaleString("id-ID")+" ekor)","Rp "+preview.totalBeli.toLocaleString("id-ID"),"#f5c842",true],
                      ["Total Biaya Ops","Rp "+preview.totalBiayaOps.toLocaleString("id-ID"),"#ef4444"],
                      ["Biaya/ekor","Rp "+preview.biayaPerEkor.toLocaleString("id-ID"),"#9097a8"],
                      ["TOTAL MODAL","Rp "+preview.totalBiaya.toLocaleString("id-ID"),"#ef4444",true],
                      ["Total Pendapatan","Rp "+preview.pendTotal.toLocaleString("id-ID"),"#3b82f6"],
                      ["PROFIT BERSIH","Rp "+preview.profit.toLocaleString("id-ID"),preview.profit>=0?"#22c55e":"#ef4444",true],
                      ["ROI",preview.roi+"%","#f5c842",true],
                      ["HPP Daging/kg","Rp "+preview.hppPerKg.toLocaleString("id-ID"),"#f59e0b"],
                      ["HPP/ekor","Rp "+preview.hppPerEkor.toLocaleString("id-ID"),"#f59e0b"],
                    ].map(([k,v,col,bold])=>(
                      <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #1c1e2b"}}>
                        <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                        <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{v}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* ═══ TAB RIWAYAT ═══ */}
      {tab==="riwayat" && (
        records.length===0 ? (
          <div style={{textAlign:"center",padding:60,color:"#555a6a",background:"#0f1118",borderRadius:12,border:"1px solid #1c1e2b",fontSize:13}}>Belum ada riwayat. Tambahkan di tab Kalkulator.</div>
        ) : (()=>{
          const curId=activeId||records[0]?.id;
          const rec=records.find(r=>r.id===curId)||records[0];
          const c=rec?hitungRPABroiler(rec):null;
          if(!c||!rec) return null;

          const getByP=nm=>c.byProducts.find(b=>b.nama===nm)||{beratKg:0,pend:0,aktual:false,harga:0,kat:"—"};
          const cekerB=getByP("Ceker (Kaki)"),hatiB=getByP("Hati"),ampelaB=getByP("Ampela (Gizzard)"),
                jantungB=getByP("Jantung"),ususB=getByP("Usus"),kepalaB=getByP("Kepala"),
                kulitB=getByP("Kulit Ayam"),darahB=getByP("Darah (L)"),buluB=getByP("Bulu+Limbah");

          const chartKomp=[
            {label:"Daging",  value:c.totalDaging,   label2:c.totalDaging.toLocaleString()+"kg",  color:"#22c55e"},
            {label:"Tulang",  value:c.beratTulang,   label2:c.beratTulang.toLocaleString()+"kg",  color:"#9097a8"},
            {label:"Lemak",   value:Math.max(0,c.beratSusut), label2:"",                          color:"#555a6a"},
            {label:"Ceker",   value:cekerB.beratKg,  label2:"",                                   color:"#f5c842"},
            {label:"Hati",    value:hatiB.beratKg,   label2:"",                                   color:"#ef4444"},
            {label:"Ampela",  value:ampelaB.beratKg, label2:"",                                   color:"#ef4444"},
            {label:"Kulit",   value:kulitB.beratKg,  label2:"",                                   color:"#f59e0b"},
            {label:"Darah",   value:darahB.beratKg,  label2:"",                                   color:"#ef4444"},
            {label:"Bulu",    value:buluB.beratKg,   label2:"",                                   color:"#333"},
          ];
          const chartPot=c.potongan.map(p=>({label:p.nama.split(" ")[0],value:p.beratKg,label2:p.beratKg.toLocaleString()+"kg",color:gradeCA(p.grade)}));
          const chartPend=[
            {label:"Dada",     value:Math.round((c.potongan.find(p=>p.kode==="dada")?.pend||0)/1000),    color:"#e879f9"},
            {label:"Paha Atas",value:Math.round((c.potongan.find(p=>p.kode==="paha_atas")?.pend||0)/1000),color:"#e879f9"},
            {label:"Paha Bwh", value:Math.round((c.potongan.find(p=>p.kode==="paha_bawah")?.pend||0)/1000),color:"#c084fc"},
            {label:"Sayap",    value:Math.round((c.potongan.find(p=>p.kode==="sayap")?.pend||0)/1000),   color:"#3b82f6"},
            {label:"Lainnya",  value:Math.round((c.potongan.filter(p=>["punggung","leher"].includes(p.kode)).reduce((s,p)=>s+p.pend,0))/1000),color:"#9097a8"},
            {label:"Ceker",    value:Math.round(cekerB.pend/1000),  color:"#f5c842"},
            {label:"Jeroan",   value:Math.round((hatiB.pend+ampelaB.pend+jantungB.pend)/1000),color:"#ef4444"},
            {label:"Tulang",   value:Math.round(c.pendTulang/1000), color:"#555a6a"},
          ];

          return (
            <div style={{display:"grid",gridTemplateColumns:"240px 1fr",gap:13,alignItems:"start"}}>
              {/* Panel Kiri */}
              <div style={{background:"#0a0c16",border:"1px solid #1c1e2b",borderRadius:13,overflow:"hidden",position:"sticky",top:0}}>
                <div style={{background:AC+"12",padding:"11px 14px",borderBottom:"1px solid "+AC+"28"}}>
                  <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:13,fontWeight:700}}>📋 Riwayat Pemotongan</div>
                  <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{records.length} batch tercatat · {totalEkor.toLocaleString("id-ID")} ekor total</div>
                </div>
                <div style={{maxHeight:"75vh",overflowY:"auto"}}>
                  {records.map(r=>{
                    const rc=hitungRPABroiler(r);if(!rc) return null;
                    const isActive=r.id===curId;
                    return (
                      <div key={r.id} onClick={()=>setActiveId(r.id)}
                        style={{padding:"9px 13px",borderBottom:"1px solid #1c1e2b",cursor:"pointer",
                          background:isActive?AC+"12":"transparent",borderLeft:"3px solid "+(isActive?AC:"transparent"),transition:"all 0.1s"}}>
                        <div style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
                          <span style={{color:isActive?AC:"#e2e4f0",fontWeight:700,fontSize:11}}>{r.flockName||r.id}</span>
                          <span style={{fontSize:9,fontWeight:700,padding:"2px 5px",borderRadius:9,background:rc.profit>=0?"#22c55e18":"#ef444418",color:rc.profit>=0?"#22c55e":"#ef4444"}}>
                            {rc.profit>=0?"+":"-"}{"Rp "+(Math.abs(rc.profit)/1e6).toFixed(1)+"jt"}
                          </span>
                        </div>
                        <div style={{display:"flex",gap:5,flexWrap:"wrap"}}>
                          <span style={{color:AC,fontSize:10,fontWeight:700}}>{(+r.jumlahEkor).toLocaleString("id-ID")} ekor</span>
                          <span style={{color:"#555a6a",fontSize:9}}>·</span>
                          <span style={{color:"#9097a8",fontSize:10}}>{r.breed}</span>
                        </div>
                        <div style={{display:"flex",gap:6,marginTop:2}}>
                          <span style={{color:"#3b82f6",fontSize:9}}>{"Rp "+(rc.pendTotal/1e6).toFixed(1)+"jt"}</span>
                          <span style={{color:"#555a6a",fontSize:9}}>ROI {rc.roi}%</span>
                          {rc.hasAktual&&<span style={{color:"#22c55e",fontSize:8,background:"#22c55e12",padding:"1px 4px",borderRadius:7}}>✅</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Panel Kanan */}
              <div style={{display:"flex",flexDirection:"column",gap:11,minWidth:0}}>
                {/* Header */}
                <div style={{background:"#0c0f1a",border:"1px solid #252535",borderRadius:13,padding:"13px 17px",display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:10}}>
                  <div>
                    <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:17,fontWeight:700,display:"flex",alignItems:"center",gap:9,flexWrap:"wrap"}}>
                      🐔 {rec.flockName||"—"}
                      <span style={{fontSize:11,color:"#555a6a",fontWeight:400}}>({rec.id})</span>
                      <span style={{background:c.hasAktual?"#22c55e18":"#e879f918",color:c.hasAktual?"#22c55e":"#e879f9",border:"1px solid "+(c.hasAktual?"#22c55e30":"#e879f930"),borderRadius:20,padding:"2px 9px",fontSize:10,fontWeight:700}}>
                        {c.hasAktual?"✅ Data Aktual":"📊 Estimasi"}
                      </span>
                      <span style={{background:"#3b82f615",color:"#3b82f6",border:"1px solid #3b82f628",borderRadius:20,padding:"2px 9px",fontSize:10,fontWeight:700}}>
                        {modeLabel[rec.modePenjualan]||"Karkas"}
                      </span>
                    </div>
                    <div style={{color:"#9097a8",fontSize:11,marginTop:3}}>
                      {rec.breed} · {c.n.toLocaleString("id-ID")} ekor · BH rata {c.bbRata}kg · Total {c.bbTotal.toLocaleString("id-ID")}kg · {rec.tglPotong}{rec.buyer?" · "+rec.buyer:""}
                    </div>
                  </div>
                  <button onClick={()=>cetakLaporan(rec,c)} style={{background:AC+"18",color:AC,border:"1px solid "+AC+"30",borderRadius:9,padding:"8px 15px",cursor:"pointer",fontWeight:700,fontSize:12}}>
                    🖨️ Cetak
                  </button>
                </div>

                {/* KPI */}
                <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:9}}>
                  {[["💰 Pendapatan","Rp "+(c.pendTotal/1e6).toFixed(2)+"jt","#3b82f6"],
                    ["💸 Biaya","Rp "+(c.totalBiaya/1e6).toFixed(2)+"jt","#ef4444"],
                    ["📈 Profit","Rp "+(c.profit/1e6).toFixed(2)+"jt",c.profit>=0?"#22c55e":"#ef4444"],
                    ["🔄 ROI",c.roi+"%",+c.roi>=15?"#22c55e":"#f59e0b"],
                    ["🏷️ HPP/kg","Rp "+c.hppPerKg.toLocaleString("id-ID"),"#f5c842"],
                  ].map(([l,v,col])=>(
                    <div key={l} style={{background:col+"0d",border:"1px solid "+col+"25",borderRadius:10,padding:"9px 11px",textAlign:"center"}}>
                      <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:3}}>{l}</div>
                      <div style={{color:col,fontWeight:800,fontSize:13}}>{v}</div>
                    </div>
                  ))}
                </div>

                {/* Sub-Tabs */}
                <div style={{display:"flex",gap:2,background:"#0a0c16",borderRadius:"10px 10px 0 0",border:"1px solid #1c1e2b",borderBottom:"none",padding:"0 4px",paddingTop:4}}>
                  {[["ringkasan","📊 Ringkasan"],["neraca","⚖️ Neraca Bobot"],["potongan","🥩 Potongan"],["byproduct","🫀 By-Product"],["keuangan","💰 Keuangan"]].map(([id,lbl])=>(
                    <button key={id} onClick={()=>setSubTab(id)}
                      style={{flex:1,background:subTab===id?"#0f1118":"none",border:"none",
                        borderBottom:"2px solid "+(subTab===id?AC:"transparent"),
                        color:subTab===id?AC:"#555a6a",padding:"8px 4px",cursor:"pointer",
                        fontWeight:700,fontSize:11,borderRadius:"6px 6px 0 0",transition:"all 0.1s"}}>
                      {lbl}
                    </button>
                  ))}
                </div>

                <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:"0 0 13px 13px",padding:15,marginTop:-1}}>

                  {/* RINGKASAN */}
                  {subTab==="ringkasan" && (
                    <div style={{display:"flex",flexDirection:"column",gap:13}}>
                      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
                        {[["Jumlah Ekor",c.n.toLocaleString("id-ID")+" ekor","#e879f9",""],
                          ["BH Total",c.bbTotal.toLocaleString("id-ID")+" kg","#f5c842",""],
                          ["Karkas Total",c.beratKarkas.toLocaleString("id-ID")+" kg","#a3e635",c.yieldKarkas+"% BH"],
                          ["Daging Total",c.totalDaging.toLocaleString("id-ID")+" kg","#22c55e",c.yieldDaging+"% karkas"],
                          ["Tulang Total",c.beratTulang.toLocaleString("id-ID")+" kg","#9097a8",""],
                          ["Karkas/Ekor",+(c.beratKarkas/c.n).toFixed(3)+" kg","#e879f9","rata-rata"],
                          ["Daging/Ekor",+(c.totalDaging/c.n).toFixed(3)+" kg","#22c55e","rata-rata"],
                          ["Biaya/Ekor","Rp "+c.hppPerEkor.toLocaleString("id-ID"),"#f59e0b","HPP"],
                        ].map(([nm,v,col,sub])=>(
                          <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:9,padding:"9px 11px"}}>
                            <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{nm}</div>
                            <div style={{color:col,fontWeight:800,fontSize:15}}>{v}</div>
                            {sub&&<div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{sub}</div>}
                          </div>
                        ))}
                      </div>
                      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
                        <BarChartB data={chartKomp} title={"Distribusi Komponen BH "+c.bbTotal.toLocaleString()+" kg"} height={120}/>
                        <BarChartB data={chartPend} title="Kontribusi Pendapatan per Produk (Rp ribu)" height={120}/>
                      </div>
                      <BarChartB data={chartPot} title="Berat per Jenis Potongan (kg total batch)" height={110}/>
                      <div style={{display:"flex",gap:9,flexWrap:"wrap",fontSize:10,color:"#555a6a"}}>
                        {[["#e879f9","Premium"],["#3b82f6","Superior"],["#9097a8","Standar"],["#22c55e","Daging"],["#ef4444","Jeroan"],["#555a6a","Tulang/Lainnya"]].map(([col,lbl])=>(
                          <span key={lbl} style={{display:"flex",alignItems:"center",gap:4}}>
                            <span style={{width:9,height:9,borderRadius:2,background:col,display:"inline-block"}}/>{lbl}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* NERACA BOBOT */}
                  {subTab==="neraca" && (
                    <div style={{display:"flex",flexDirection:"column",gap:12}}>
                      <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:4}}>⚖️ Neraca Bobot Batch ({c.n.toLocaleString("id-ID")} ekor)</div>
                      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
                        {[
                          ["BH Total",c.bbTotal,"100%","#f5c842",false],
                          ["Karkas",c.beratKarkas,c.yieldKarkas+"%","#a3e635",!!rec.aKarkas],
                          ["— Daging",c.totalDaging,+(c.totalDaging/c.bbTotal*100).toFixed(1)+"%","#22c55e",!!rec.aDaging],
                          ["— Tulang",c.beratTulang,+(c.beratTulang/c.bbTotal*100).toFixed(1)+"%","#9097a8",!!rec.aTulang],
                          ["— Lemak/Trim",+Math.max(0,c.beratSusut).toFixed(1),+(Math.max(0,c.beratSusut)/c.bbTotal*100).toFixed(1)+"%","#555a6a",false],
                          ["Jeroan Edible",+(c.byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.beratKg,0)).toFixed(1),+(c.byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.beratKg,0)/c.bbTotal*100).toFixed(1)+"%","#a855f7",false],
                          ["Bulu+Limbah",buluB.beratKg,+(buluB.beratKg/c.bbTotal*100).toFixed(1)+"%","#555a6a",!!rec.aBulu],
                          ["Per Ekor (karkas)",+(c.beratKarkas/c.n).toFixed(3)+" kg","rata-rata","#e879f9",false],
                        ].map(([nm,brt,pct,col,isAkt])=>(
                          <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:9,padding:"9px 11px"}}>
                            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:2}}>
                              <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>{nm}</div>
                              {isAkt!==false&&<BadgeB isA={isAkt}/>}
                            </div>
                            <div style={{color:col,fontWeight:800,fontSize:14}}>{typeof brt==="number"?brt.toLocaleString("id-ID"):brt}<span style={{fontSize:9,fontWeight:400}}> {typeof brt==="number"?"kg":""}</span></div>
                            <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{pct}</div>
                          </div>
                        ))}
                      </div>
                      <div style={{borderTop:"1px solid #1c1e2b",paddingTop:12}}>
                        <div style={{color:"#3b82f6",fontFamily:"'DM Serif Display',serif",fontSize:12,marginBottom:9}}>🔬 Indikator Produktivitas</div>
                        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8}}>
                          {[
                            ["Yield Karkas",c.yieldKarkas+"%",c.yieldKarkas>=72?"#22c55e":"#f59e0b","Ideal ≥72% BH. Pengukur efisiensi pemotongan"],
                            ["Yield Daging",c.yieldDaging+"%",c.yieldDaging>=72?"#22c55e":"#f59e0b","% daging dari karkas. Ideal ≥72%"],
                            ["Karkas/Ekor",+(c.beratKarkas/c.n).toFixed(3)+" kg","#e879f9","Rata-rata berat karkas per ekor"],
                            ["Daging/Ekor",+(c.totalDaging/c.n).toFixed(3)+" kg","#22c55e","Rata-rata daging bersih per ekor"],
                            ["By-Prod Revenue",+(c.pendByP/c.pendTotal*100).toFixed(1)+"%","#a855f7","% pendapatan dari jeroan & by-product"],
                            ["HPP/kg daging","Rp "+c.hppPerKg.toLocaleString("id-ID"),"#f59e0b","Harga pokok produksi per kg daging"],
                          ].map(([k,v,col,desc])=>(
                            <div key={k} style={{background:"#ffffff05",borderRadius:8,padding:"9px 11px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:8}}>
                              <div style={{flex:1}}>
                                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                                <div style={{fontSize:10,color:"#444",lineHeight:1.3}}>{desc}</div>
                              </div>
                              <div style={{color:col,fontWeight:800,fontSize:15,whiteSpace:"nowrap"}}>{v}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* POTONGAN */}
                  {subTab==="potongan" && (
                    <div style={{overflowX:"auto"}}>
                      <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>🥩 Rincian Potongan Daging — Batch {c.n.toLocaleString("id-ID")} Ekor</div>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#22c55e09",borderBottom:"1px solid #22c55e22"}}>
                          {["No","Potongan","Grade","%BH","Total (kg)","Per Ekor","Harga/kg","Nilai (Rp)","Data"].map(h=><th key={h} style={{...thA,color:"#22c55e"}}>{h}</th>)}
                        </tr></thead>
                        <tbody>
                          {c.potongan.map((p,i)=>{
                            const gc=gradeCA(p.grade);
                            return (
                              <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:p.aktual?"#22c55e05":i%2?"#ffffff02":"transparent"}}>
                                <td style={tdA("#555a6a")}>{i+1}</td>
                                <td style={tdA("#e2e4f0",true)}>{p.nama}</td>
                                <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                                <td style={tdA("#9097a8")}>{p.pct}%</td>
                                <td style={tdA("#e879f9",true)}>{p.beratKg.toLocaleString("id-ID")} kg</td>
                                <td style={tdA("#555a6a")}>{+(p.beratKg/c.n).toFixed(3)} kg</td>
                                <td style={tdA("#9097a8")}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                                <td style={tdA("#22c55e",true)}>{"Rp "+p.pend.toLocaleString("id-ID")}</td>
                                <td style={{padding:"8px 10px"}}><BadgeB isA={p.aktual}/></td>
                              </tr>
                            );
                          })}
                          <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}>
                            <td colSpan={4} style={{padding:"9px 10px",color:"#22c55e",fontWeight:800}}>TOTAL DAGING</td>
                            <td style={tdA("#e879f9",true)}>{c.totalDaging.toLocaleString("id-ID")} kg</td>
                            <td style={tdA("#555a6a")}>{+(c.totalDaging/c.n).toFixed(3)} kg/ekor</td>
                            <td/><td style={tdA("#22c55e",true)}>{"Rp "+c.pendDaging.toLocaleString("id-ID")}</td><td/>
                          </tr>
                          <tr style={{background:"#9097a809"}}>
                            <td colSpan={2} style={tdA("#9097a8")}>Tulang</td>
                            <td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>By-product</span></td>
                            <td style={tdA("#9097a8")}>{S.pct_tulang}%</td>
                            <td style={tdA("#9097a8",true)}>{c.beratTulang.toLocaleString("id-ID")} kg</td>
                            <td style={tdA("#555a6a")}>{+(c.beratTulang/c.n).toFixed(3)} kg/ekor</td>
                            <td style={tdA("#9097a8")}>{"Rp "+(rec.hJualTulang||5000).toLocaleString("id-ID")}</td>
                            <td style={tdA("#9097a8",true)}>{"Rp "+c.pendTulang.toLocaleString("id-ID")}</td>
                            <td style={{padding:"8px 10px"}}><BadgeB isA={!!rec.aTulang}/></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* BY-PRODUCT */}
                  {subTab==="byproduct" && (
                    <div style={{overflowX:"auto"}}>
                      <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>🫀 By-Product, Jeroan & Limbah — {c.n.toLocaleString("id-ID")} Ekor</div>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#a855f709",borderBottom:"1px solid #a855f722"}}>
                          {["Produk","Kategori","Total (kg)","Per Ekor","%BH","Harga/kg","Nilai (Rp)","Data"].map(h=><th key={h} style={{...thA,color:"#a855f7"}}>{h}</th>)}
                        </tr></thead>
                        <tbody>
                          {c.byProducts.map((b,i)=>{
                            const catC={"Fancy Meat":"#f5c842","Jeroan":"#ef4444","Kulit":"#f59e0b","Darah":"#ef4444","Limbah":"#555a6a"};
                            const cc=catC[b.kat]||"#666";
                            return (
                              <tr key={b.nama} style={{borderBottom:"1px solid #1c1e2b",background:b.aktual?"#a855f706":i%2?"#ffffff02":"transparent"}}>
                                <td style={tdA("#e2e4f0",true)}>{b.nama}</td>
                                <td style={{padding:"8px 10px"}}><span style={{background:cc+"14",color:cc,border:"1px solid "+cc+"28",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>{b.kat}</span></td>
                                <td style={tdA("#e879f9",true)}>{b.beratKg.toLocaleString("id-ID")} kg</td>
                                <td style={tdA("#555a6a")}>{+(b.beratKg/c.n).toFixed(3)} kg</td>
                                <td style={tdA("#9097a8")}>{+(b.beratKg/c.bbTotal*100).toFixed(2)}%</td>
                                <td style={tdA("#9097a8")}>{"Rp "+b.harga.toLocaleString("id-ID")}</td>
                                <td style={tdA(b.kat==="Limbah"?"#555a6a":"#a855f7",true)}>{b.kat==="Limbah"?"—":"Rp "+b.pend.toLocaleString("id-ID")}</td>
                                <td style={{padding:"8px 10px"}}><BadgeB isA={b.aktual}/></td>
                              </tr>
                            );
                          })}
                          <tr style={{borderTop:"2px solid #a855f733",background:"#a855f709"}}>
                            <td colSpan={2} style={{padding:"9px 10px",color:"#a855f7",fontWeight:800}}>TOTAL BY-PRODUCT (edible)</td>
                            <td style={tdA("#e879f9",true)}>{+(c.byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.beratKg,0)).toFixed(1).toLocaleString?+(c.byProducts.filter(b=>b.kat!=="Limbah").reduce((s,b)=>s+b.beratKg,0)).toFixed(1)+" kg":""} kg</td>
                            <td colSpan={3}/><td style={tdA("#a855f7",true)}>{"Rp "+c.pendByP.toLocaleString("id-ID")}</td><td/>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* KEUANGAN */}
                  {subTab==="keuangan" && (
                    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:13}}>
                      <div>
                        <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💸 Rincian Biaya Modal</div>
                        {[["Harga Beli ("+c.n.toLocaleString("id-ID")+" ekor)","Rp "+c.totalBeli.toLocaleString("id-ID"),"#f5c842",true],
                          ["Listrik & Air","Rp "+(c.biaya.listrik*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Upah Tenaga","Rp "+(c.biaya.upah*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Kemasan","Rp "+(c.biaya.kemasan*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Sanitasi","Rp "+(c.biaya.sanitasi*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Transportasi","Rp "+(c.biaya.transport*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Retribusi RPA","Rp "+(c.biaya.retribusi*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Lainnya","Rp "+(c.biaya.lainnya*c.n).toLocaleString("id-ID"),"#9097a8"],
                          ["Total Ops","Rp "+c.totalBiayaOps.toLocaleString("id-ID"),"#ef4444",false,true],
                          ["TOTAL MODAL","Rp "+c.totalBiaya.toLocaleString("id-ID"),"#ef4444",true],
                        ].map(([k,v,col,bold,sep])=>(
                          <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #1c1e2b",borderTop:sep?"1px solid #ef444422":"none",marginTop:sep?6:0}}>
                            <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                            <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{v}</span>
                          </div>
                        ))}
                        <div style={{marginTop:11,background:"#ef444410",border:"1px solid #ef444428",borderRadius:9,padding:"9px 11px"}}>
                          <div style={{fontSize:10,color:"#9097a8",marginBottom:2}}>Biaya per Ekor (HPP)</div>
                          <div style={{fontSize:18,fontWeight:800,color:"#f5c842"}}>{"Rp "+c.hppPerEkor.toLocaleString("id-ID")}<span style={{fontSize:11,fontWeight:400,color:"#555a6a"}}>/ekor</span></div>
                          <div style={{fontSize:11,fontWeight:700,color:"#f59e0b",marginTop:2}}>{"Rp "+c.hppPerKg.toLocaleString("id-ID")}<span style={{fontSize:10,fontWeight:400,color:"#555a6a"}}>/kg daging</span></div>
                        </div>
                      </div>
                      <div>
                        <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💰 Rincian Pendapatan</div>
                        {[["Daging Premium","Rp "+c.potongan.filter(p=>p.grade==="Premium").reduce((s,p)=>s+p.pend,0).toLocaleString("id-ID"),"#e879f9"],
                          ["Daging Superior","Rp "+c.potongan.filter(p=>p.grade==="Superior").reduce((s,p)=>s+p.pend,0).toLocaleString("id-ID"),"#3b82f6"],
                          ["Daging Standar","Rp "+c.potongan.filter(p=>p.grade==="Standar").reduce((s,p)=>s+p.pend,0).toLocaleString("id-ID"),"#9097a8"],
                          ["Tulang","Rp "+c.pendTulang.toLocaleString("id-ID"),"#9097a8"],
                          ["Ceker","Rp "+cekerB.pend.toLocaleString("id-ID"),"#f5c842"],
                          ["Hati+Ampela+Jantung","Rp "+(hatiB.pend+ampelaB.pend+jantungB.pend).toLocaleString("id-ID"),"#ef4444"],
                          ["Lainnya (jeroan+kulit)","Rp "+(c.pendByP-cekerB.pend-hatiB.pend-ampelaB.pend-jantungB.pend).toLocaleString("id-ID"),"#a855f7"],
                          ["TOTAL PENDAPATAN","Rp "+c.pendTotal.toLocaleString("id-ID"),"#3b82f6",true],
                          ["PROFIT BERSIH","Rp "+c.profit.toLocaleString("id-ID"),c.profit>=0?"#22c55e":"#ef4444",true],
                          ["ROI",c.roi+"%","#f5c842",true],
                        ].map(([k,v,col,bold])=>(
                          <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",borderBottom:"1px solid #1c1e2b",borderTop:bold?"2px solid #1c1e2b":"none",marginTop:bold?4:0}}>
                            <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                            <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{v}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                </div>
                {rec.notes&&<div style={{background:"#ffffff05",border:"1px solid #1c1e2b",borderRadius:9,padding:"9px 13px",color:"#9097a8",fontSize:12}}>📝 <strong style={{color:"#e2e4f0"}}>Catatan:</strong> {rec.notes}</div>}
              </div>
            </div>
          );
        })()
      )}

      {/* ═══ TAB STANDAR ═══ */}
      {tab==="standar" && (
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:11}}>📊 Standar % Karkas Ayam Broiler</div>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
              <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Strain","Jantan (%)","Betina (%)","Keterangan"].map(h=><th key={h} style={{...thA,color:AC}}>{h}</th>)}</tr></thead>
              <tbody>{[["Cobb 500",73,71,"Paling populer Indonesia, konversi pakan baik"],["Ross 308",74,72,"Yield karkas tertinggi, pertumbuhan cepat"],["Hubbard",72,70,"Daging dada sangat besar, premium"],["Lohmann",71,70,"Dwi tujuan, bisa untuk layer afkir"],["Lokal/Kampung",68,66,"Tekstur lebih padat, harga lebih tinggi"]].map(([ras,j,b,ket],i)=>(
                <tr key={ras} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                  <td style={tdA("#e2e4f0",true)}>{ras}</td>
                  <td style={tdA("#22c55e",true)}>{j}%</td>
                  <td style={tdA("#60a5fa",true)}>{b}%</td>
                  <td style={tdA("#555a6a")}><span style={{fontSize:11}}>{ket}</span></td>
                </tr>
              ))}</tbody>
            </table>
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:6}}>🥩 Standar Potongan & Harga Ayam (Juni 2026)</div>
            <div style={{fontSize:11,color:"#555a6a",marginBottom:11}}>Sumber: Pasar Tradisional, Supermarket, Distributor Jatim/Jabar · Juni 2026</div>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
              <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Potongan","Grade","%BH","Harga/kg","Kegunaan"].map(h=><th key={h} style={{...thA,color:"#22c55e"}}>{h}</th>)}</tr></thead>
              <tbody>{S.potongan_primer.filter(p=>p.kode!=="karkas_utuh").map((p,i)=>{
                const gc=gradeCA(p.grade);
                return (
                  <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                    <td style={tdA("#e2e4f0",true)}>{p.nama}</td>
                    <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                    <td style={tdA("#9097a8")}>{p.pct}%</td>
                    <td style={tdA(AC,true)}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                    <td style={tdA("#555a6a")}><span style={{fontSize:11}}>{p.ket}</span></td>
                  </tr>
                );
              })}</tbody>
            </table>
            <div style={{marginTop:12,background:AC+"0a",border:"1px solid "+AC+"22",borderRadius:10,padding:13}}>
              <div style={{color:AC,fontWeight:700,fontSize:12,marginBottom:9}}>📌 Produk Olahan & Mode Penjualan</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))",gap:8}}>
                {S.produk_olahan.map(p=>(
                  <div key={p.nama} style={{background:"#ffffff06",borderRadius:8,padding:"7px 11px"}}>
                    <div style={{fontSize:11,color:"#e2e4f0",fontWeight:700}}>{p.nama}</div>
                    <div style={{fontSize:12,color:AC,fontWeight:800,marginTop:2}}>{"Rp "+p.harga_per_kg.toLocaleString("id-ID")}/kg</div>
                    <div style={{fontSize:10,color:"#555a6a",marginTop:1}}>{p.ket}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:17}}>
            <div style={{color:"#a855f7",fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:11}}>🫀 By-Product & Jeroan Ayam (Juni 2026)</div>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
              <thead><tr style={{borderBottom:"1px solid #1c1e2b"}}>{["Produk","Kategori","%BH","Harga/kg","Nilai per 1000 ekor @ 2kg"].map(h=><th key={h} style={{...thA,color:"#a855f7"}}>{h}</th>)}</tr></thead>
              <tbody>{S.by_products.map((b,i)=>{
                const catC={"Fancy Meat":"#f5c842","Jeroan":"#ef4444","Kulit":"#f59e0b","Darah":"#ef4444","Limbah":"#555a6a"};
                const cc=catC[b.kat]||"#666";
                const nilaiPer1000=Math.round(1000*2*b.pct_live/100*b.harga);
                return (
                  <tr key={b.nama} style={{borderBottom:"1px solid #1c1e2b",background:i%2?"#ffffff03":"transparent"}}>
                    <td style={tdA("#e2e4f0",true)}>{b.nama}</td>
                    <td style={{padding:"8px 10px"}}><span style={{background:cc+"14",color:cc,border:"1px solid "+cc+"28",borderRadius:20,padding:"2px 7px",fontSize:9,fontWeight:700}}>{b.kat}</span></td>
                    <td style={tdA("#9097a8")}>{b.pct_live}%</td>
                    <td style={tdA("#a855f7",true)}>{"Rp "+b.harga.toLocaleString("id-ID")}</td>
                    <td style={tdA("#3b82f6",true)}>{"Rp "+nilaiPer1000.toLocaleString("id-ID")}</td>
                  </tr>
                );
              })}</tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};


/* ================================================================
   DATA KONTAK — Mantri, Dokter, Dinas, Penjual
================================================================ */
const INIT_KONTAK = [
  // ── MANTRI HEWAN ──
  {id:"KT001",kategori:"Mantri Hewan",nama:"Mantri Agus Santoso",hp:"081234567890",hp2:"",alamat:"Jl. Peternakan No.12, Kec. Ciawi",wilayah:"Kec. Ciawi & Cisarua",spesialisasi:"Sapi, Domba, Vaksinasi",jam:"06.00–18.00",tarif:"Rp 50.000–150.000/kunjungan",catatan:"Tersedia panggilan darurat",aktif:true},
  {id:"KT002",kategori:"Mantri Hewan",nama:"Mantri Dede Kurniawan",hp:"082198765432",hp2:"",alamat:"Desa Sukamaju, RT 03/05",wilayah:"Kec. Sukabumi Utara",spesialisasi:"Domba Garut, Obat Cacing, Scabies",jam:"07.00–17.00",tarif:"Rp 40.000–100.000/kunjungan",catatan:"Bisa celup domba massal",aktif:true},
  {id:"KT003",kategori:"Mantri Hewan",nama:"Mantri Hendra Gunawan",hp:"085344556677",hp2:"",alamat:"Pasar Hewan Cibadak",wilayah:"Kec. Cibadak & Cicurug",spesialisasi:"Sapi Potong, Vaksin ND & AI",jam:"06.00–16.00",tarif:"Rp 50.000–200.000/kunjungan",catatan:"Pengalaman 15 tahun",aktif:true},
  // ── DOKTER HEWAN ──
  {id:"KT004",kategori:"Dokter Hewan",nama:"drh. Hasan Basri M.Si",hp:"087722334455",hp2:"022-7788990",alamat:"Klinik Hewan Mandiri, Jl. Raya Sukabumi 45",wilayah:"Kota Sukabumi & sekitar",spesialisasi:"Ruminansia Besar, Bedah, Reproduksi, Ultrasonografi",jam:"08.00–17.00 (Senin–Sabtu)",tarif:"Konsultasi Rp 100.000 + tindakan",catatan:"Melayani panggilan farm besar",aktif:true},
  {id:"KT005",kategori:"Dokter Hewan",nama:"drh. Sinta Permatasari",hp:"081355443322",hp2:"",alamat:"Puskeswan Kec. Tarogong",wilayah:"Kab. Garut & Tasikmalaya",spesialisasi:"Unggas, Broiler, Layer, AI H5N1",jam:"07.30–15.30 (Senin–Jumat)",tarif:"Gratis (Puskeswan Pemerintah)",catatan:"Khusus unggas komersial",aktif:true},
  {id:"KT006",kategori:"Dokter Hewan",nama:"drh. Ahmad Fauzi Sp.MP",hp:"089988776655",hp2:"",alamat:"Klinik Ternak Sejahtera, Jl. Pasundan No.8",wilayah:"Kab. Tasikmalaya",spesialisasi:"Domba Garut, IB, ET, Reproduksi",jam:"09.00–18.00",tarif:"Konsultasi Rp 150.000 + IB Rp 200.000",catatan:"Spesialis breeding domba Garut",aktif:true},
  // ── DINAS PETERNAKAN ──
  {id:"KT007",kategori:"Dinas Peternakan",nama:"Dinas Peternakan Kab. Sukabumi",hp:"0266-222-333",hp2:"0266-222-334",alamat:"Jl. Ahmad Yani No.1, Sukabumi 43132",wilayah:"Kab. Sukabumi",spesialisasi:"Laporan PMK, AI, Anthrax, Brucellosis — Penyakit Strategis",jam:"07.30–16.00 (Senin–Jumat)",tarif:"Gratis",catatan:"Hotline darurat PMK: 0800-1234-567",aktif:true},
  {id:"KT008",kategori:"Dinas Peternakan",nama:"Dinas Peternakan Kab. Garut",hp:"0262-232-100",hp2:"0262-232-101",alamat:"Jl. Pembangunan No.95, Garut 44151",wilayah:"Kab. Garut",spesialisasi:"Domba Garut, Vaksinasi Massal, Inseminasi Buatan",jam:"07.30–15.30 (Senin–Jumat)",tarif:"Gratis — beberapa vaksin bersubsidi",catatan:"Unit IB aktif setiap hari kerja",aktif:true},
  {id:"KT009",kategori:"Dinas Peternakan",nama:"BBVET Wates (Balai Besar Vet)",hp:"0274-773-222",hp2:"0274-773-223",alamat:"Jl. Raya Wates Km.27, Yogyakarta",wilayah:"Jawa — Laboratorium Diagnosa Penyakit",spesialisasi:"Diagnosa Lab: PMK, AI, Brucella, Babesia, Anaplasma",jam:"08.00–16.00 (Senin–Jumat)",tarif:"Tarif laboratorium sesuai Permentan",catatan:"Kirim sampel darah/organ untuk diagnosa definitif",aktif:true},
  // ── PENJUAL SAPI ──
  {id:"KT010",kategori:"Penjual Sapi",nama:"Bandar H. Rahman (Sapi Potong)",hp:"081320001234",hp2:"081320001235",alamat:"Pasar Hewan Ciawi, Los B No.12",wilayah:"Ciawi, Bogor & sekitar",spesialisasi:"Sapi Simental, Limousin, Brahman — Penggemukan",jam:"Senin, Rabu, Sabtu (hari pasar)",tarif:"Harga pasar + nego",catatan:"Stock 20–50 ekor, bisa kirim",aktif:true},
  {id:"KT011",kategori:"Penjual Sapi",nama:"CV Maju Jaya Ternak",hp:"082134567890",hp2:"021-5566778",alamat:"Jl. Industri Peternakan Km.5, Bogor",wilayah:"Jawa Barat & Jakarta",spesialisasi:"Sapi PO, Bali, Brahman — Bakalan Import",jam:"Senin–Sabtu 08.00–17.00",tarif:"Sesuai BB + ongkir",catatan:"Bisa indent, sertifikat kesehatan tersedia",aktif:true},
  {id:"KT012",kategori:"Penjual Sapi",nama:"Pak Asep (Jagal & Bakalan)",hp:"085311112233",hp2:"",alamat:"Pasar Sukamaju, Kios No.5",wilayah:"Sukabumi & Cianjur",spesialisasi:"Sapi Betina Afkir, Sapi FH, Bakalan Lokal",jam:"Setiap hari 05.00–10.00",tarif:"Rp 42.000–62.000/kg BB",catatan:"Harga bersaing, bisa timbang ditempat",aktif:true},
  // ── PENJUAL DOMBA ──
  {id:"KT013",kategori:"Penjual Domba",nama:"Pasar Hewan Wanaraja (Domba Garut)",hp:"0262-555-6789",hp2:"",alamat:"Pasar Hewan Wanaraja, Garut",wilayah:"Garut & Tasikmalaya",spesialisasi:"Domba Garut Grade A, Domba Kurban, Domba Lokal",jam:"Rabu & Minggu (hari pasar)",tarif:"Rp 1.500.000–15.000.000/ekor",catatan:"Pasar terbesar domba Garut, cek FAMACHA dulu",aktif:true},
  {id:"KT014",kategori:"Penjual Domba",nama:"Peternak Pak Bambang Rancakalong",hp:"081333445566",hp2:"",alamat:"Kp. Rancakalong, Sumedang",wilayah:"Sumedang & Majalengka",spesialisasi:"Domba Garut Breeding, Bibit Unggul, Jantan Show",jam:"Setiap hari (call dulu)",tarif:"Harga premium — bibit grade A",catatan:"Tersedia sertifikat silsilah domba",aktif:true},
  // ── PENJUAL DOC/AYAM ──
  {id:"KT015",kategori:"Penjual DOC/Ayam",nama:"PT Japfa Comfeed — Dist. Jabar",hp:"021-4567-8901",hp2:"0800-123-4567",alamat:"Jl. Raya Bogor Km.32, Jakarta",wilayah:"Jawa Barat & Banten",spesialisasi:"DOC Broiler Cobb 500, Pakan CP-511/512, Obat Veteriner",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga kontrak + spot",catatan:"Minimal order DOC 500 ekor, pakan 1 ton",aktif:true},
  {id:"KT016",kategori:"Penjual DOC/Ayam",nama:"PT Malindo Feedmill — Sales Garut",hp:"081244556677",hp2:"",alamat:"Agen Malindo Jl. Patriot No.33, Garut",wilayah:"Garut, Tasik, Ciamis",spesialisasi:"DOC Ross 308, DOC Layer ISA Brown, Pakan Layer Mash",jam:"Senin–Sabtu 08.00–16.00",tarif:"Harga agen — bisa kredit",catatan:"Bisa DO (Delivery Order) ke kandang",aktif:true},
  // ── PENJUAL PAKAN ──
  {id:"KT017",kategori:"Penjual Pakan",nama:"Toko Pertanian & Pakan Pak Udin",hp:"085377889900",hp2:"",alamat:"Jl. Ciawi-Tasik Km.12, Bogor",wilayah:"Bogor Selatan & Sukabumi Utara",spesialisasi:"Konsentrat Sapi/Domba, Dedak, Molases, Mineral Block",jam:"Setiap hari 06.00–18.00",tarif:"Harga grosir, diskon >500kg",catatan:"Stok lengkap, bisa antar",aktif:true},
  {id:"KT018",kategori:"Penjual Pakan",nama:"CV Nutrisi Ternak Sejahtera",hp:"022-6677889",hp2:"081256789012",alamat:"Jl. Soekarno Hatta No.156, Bandung",wilayah:"Bandung & Jawa Barat",spesialisasi:"Pakan Broiler Starter/Grower/Finisher, Layer Mash, Premix",jam:"Senin–Sabtu 08.00–17.00",tarif:"Harga distributor resmi Charoen CP",catatan:"Min order 1 ton, tersedia DO",aktif:true},
  {id:"KT019",kategori:"Penjual Pakan",nama:"Apotek Hewan & Poultry Supply Pak Haji",hp:"081388990011",hp2:"",alamat:"Pasar Sukabumi Timur Kios 44",wilayah:"Sukabumi & Cianjur",spesialisasi:"Obat Cacing, Vaksin, Vitamin, Premix, Antibiotik Veteriner",jam:"Setiap hari 06.00–17.00",tarif:"Eceran & grosir",catatan:"Stok vaksin ND, Gumboro, AI, PMK",aktif:true},
  // ── DARURAT ──
  {id:"KT020",kategori:"Darurat & Hotline",nama:"Hotline PMK Nasional",hp:"0800-1234-567",hp2:"",alamat:"Kementerian Pertanian RI",wilayah:"Seluruh Indonesia",spesialisasi:"Laporan PMK, AI H5N1, Anthrax, Brucellosis — Penyakit Strategis",jam:"24 jam / 7 hari",tarif:"Gratis (bebas pulsa)",catatan:"WAJIB hubungi dalam 1×24 jam jika ada kasus penyakit strategis",aktif:true},
  {id:"KT021",kategori:"Darurat & Hotline",nama:"PDHI (Perhimpunan Dokter Hewan Indonesia)",hp:"021-7257-231",hp2:"",alamat:"Jl. Petta Ponggawa No.2, Jakarta Selatan",wilayah:"Seluruh Indonesia — Rujukan Nasional",spesialisasi:"Referral dokter hewan, konsultasi kasus sulit",jam:"Senin–Jumat 09.00–16.00",tarif:"—",catatan:"Bisa minta referral drh spesialis di daerah",aktif:true},

  // ── PERUSAHAAN PAKAN & DOC NASIONAL ──
  {id:"KT022",kategori:"Penjual DOC/Ayam",nama:"PT Charoen Pokphand Indonesia Tbk (Pusat)",hp:"021-6919999",hp2:"021-6907324",alamat:"Jl. Ancol VIII/1, Ancol Barat, Jakarta Utara 14430",wilayah:"Seluruh Indonesia — Kantor Pusat",spesialisasi:"DOC Broiler & Layer, Pakan CP-511/512, Vaksin Medivac, Olahan Ayam",jam:"Senin–Jumat 08.00–17.00",tarif:"Hubungi sales representative daerah",catatan:"Website: cp.co.id | Email: investor.relations@cp.co.id | Produk: Comfeed, DOC, Prima Freshmart",aktif:true},
  {id:"KT023",kategori:"Penjual DOC/Ayam",nama:"PT Charoen Pokphand — Cabang Surabaya",hp:"031-8972992",hp2:"031-8972258",alamat:"Jl. Raya Surabaya-Mojokerto (Sepanjang) Km 19, Surabaya",wilayah:"Jawa Timur & Indonesia Timur",spesialisasi:"DOC Broiler, Pakan Ternak, RPA Ayam",jam:"Senin–Sabtu 07.00–17.00",tarif:"Harga kontrak & spot",catatan:"Fax: 031-8972258",aktif:true},
  {id:"KT024",kategori:"Penjual DOC/Ayam",nama:"PT Charoen Pokphand — Cabang Semarang",hp:"024-6580235",hp2:"024-6581362",alamat:"Jl. Raya Semarang-Demak Km 8 Genuk, Semarang 50118",wilayah:"Jawa Tengah & DIY",spesialisasi:"DOC, Pakan Agro-Feedmill, Distribusi Jateng",jam:"Senin–Sabtu 07.00–16.00",tarif:"Harga distributor",catatan:"Fax: 024-6581362",aktif:true},
  {id:"KT025",kategori:"Penjual Pakan",nama:"PT Japfa Comfeed Indonesia Tbk (Pusat)",hp:"021-2854-5680",hp2:"",alamat:"Wisma Millenia Lt. 7, Jl. MT. Haryono Kav. 16, Jakarta 12810",wilayah:"Seluruh Indonesia — Kantor Pusat",spesialisasi:"DOC Cobb 500, Pakan Comfeed & Benefeed, Vaksin Vaksindo, Daging So Good",jam:"Senin–Jumat 08.00–17.00",tarif:"Hubungi agen/distributor daerah",catatan:"Website: japfacomfeed.co.id | Anak perusahaan: So Good Food, Santori Sapi, Vaksindo",aktif:true},
  {id:"KT026",kategori:"Penjual Pakan",nama:"PT Japfa Comfeed — Cabang Cirebon/Jabar",hp:"0231-202014",hp2:"0231-208858",alamat:"Jl. Jend. A. Yani No. 31, Pegambiran, Cirebon 45113",wilayah:"Jawa Barat & Banten",spesialisasi:"Pakan Ternak (Comfeed), DOC, Distribusi Jabar",jam:"Senin–Sabtu 07.00–16.00",tarif:"Harga distributor",catatan:"Fax: 0231-208858",aktif:true},
  {id:"KT027",kategori:"Penjual Pakan",nama:"PT Malindo Feedmill Tbk (Pusat)",hp:"021-7661727",hp2:"021-7661728",alamat:"Jl. RS Fatmawati No.15, Komplek Golden Plaza Blok G 17-22, Jakarta Selatan 12420",wilayah:"Seluruh Indonesia — Kantor Pusat",spesialisasi:"DOC Layer ISA Brown & Ross 308, Pakan Layer Mash, Broiler Starter/Finisher",jam:"Senin–Jumat 08.00–16.00 · Sabtu 08.00–13.00",tarif:"Hubungi sales daerah",catatan:"Website: malindofeedmill.com | Email: bibitindo@malindofeedmill.co.id",aktif:true},
  {id:"KT028",kategori:"Penjual Pakan",nama:"PT Malindo Feedmill — Cabang Gresik (Jatim)",hp:"031-8972385",hp2:"031-8971378",alamat:"Jl. Pertamina, Desa Sumberame, Kec. Wringin Anom, Gresik, Jawa Timur",wilayah:"Jawa Timur & Indonesia Timur",spesialisasi:"Pakan Ternak, DOC Layer, Distribusi Jatim",jam:"Senin–Sabtu 07.00–16.00",tarif:"Harga pabrik",catatan:"Fax: 031-8971378",aktif:true},

  // ── OBAT & VAKSIN HEWAN ──
  {id:"KT029",kategori:"Penjual Pakan",nama:"PT Medion Farma Jaya (Pusat Bandung)",hp:"022-6866090",hp2:"",alamat:"Jl. Raya Batujajar No. 29, Cimareme, Bandung Barat, Jawa Barat",wilayah:"Seluruh Indonesia — Kantor Pusat & Pabrik",spesialisasi:"Vaksin Unggas (Medivac ND/AI/IB/Gumboro), Obat Hewan, Premix, Desinfektan",jam:"Senin–Jumat 08.00–16.00",tarif:"Eceran & Distributor",catatan:"Website: medionfarma.co.id | Produk unggulan: Medivac AI, Coccivac, Wormectin",aktif:true},
  {id:"KT030",kategori:"Penjual Pakan",nama:"PT Sierad Produce Tbk (Pusat)",hp:"021-29819999",hp2:"021-29819997",alamat:"TCC Batavia Tower One Lt.7, Jl. KH. Mas Mansyur Kav.126, Jakarta Pusat",wilayah:"Seluruh Indonesia",spesialisasi:"DOC Layer, Pakan Ternak, Ayam Potong, Produk Olahan Daging",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga pabrik — hubungi sales",catatan:"Fax: 021-29819997 | Cabang Tangerang: 021-5953888",aktif:true},

  // ── PEMERINTAH & LEMBAGA RESMI ──
  {id:"KT031",kategori:"Dinas Peternakan",nama:"Direktorat Jenderal PKH — Kementan RI",hp:"021-7815380",hp2:"021-7801513",alamat:"Jl. Harsono RM No.3, Gedung C Lt.7, Ragunan, Jakarta Selatan 12550",wilayah:"Seluruh Indonesia — Pusat",spesialisasi:"Kebijakan Peternakan, Vaksinasi Nasional, Laporan Penyakit Strategis (PMK/AI/Anthrax)",jam:"Senin–Kamis 08.00–15.30 · Jumat 08.00–16.00",tarif:"Gratis",catatan:"Email: ditjenpkh@pertanian.go.id | Website: ditjenpkh.pertanian.go.id",aktif:true},
  {id:"KT032",kategori:"Darurat & Hotline",nama:"Kementan RI — Pertanian.go.id",hp:"021-7815380",hp2:"",alamat:"Jl. Harsono RM No.3, Ragunan, Jakarta Selatan 12550",wilayah:"Seluruh Indonesia",spesialisasi:"Informasi Pertanian & Peternakan Nasional, Kebijakan, Subsidi",jam:"Senin–Jumat 08.00–16.00",tarif:"Gratis",catatan:"Website: pertanian.go.id | WA Ditjen PSP: 0812-9090-0043",aktif:true},
  {id:"KT033",kategori:"Penjual DOC/Ayam",nama:"PT So Good Food (Japfa Group)",hp:"0812-9179-278",hp2:"",alamat:"Website: sogood.id",wilayah:"Seluruh Indonesia — distribusi luas",spesialisasi:"Ayam Potong & Kampung Fresh/Frozen, Distribusi ke Supermarket & HoReCa",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga grosir & distribusi",catatan:"Anak perusahaan PT Japfa Comfeed | WA: 628129179278",aktif:true},

  // ══════════════════════════════════════════════
  //  TASIKMALAYA & CIAMIS — Dokter, Mantri, Dinas
  // ══════════════════════════════════════════════

  // ── DOKTER HEWAN TASIKMALAYA ──
  {id:"KT034",kategori:"Dokter Hewan",nama:"drh. Dini Dinarwati (Praktek Tasikmalaya)",hp:"0813-1241-2225",hp2:"",alamat:"Jl. BKR No.11, Kahuripan, Kec. Tawang, Kab. Tasikmalaya 46124",wilayah:"Kota & Kab. Tasikmalaya",spesialisasi:"Hewan ternak & peliharaan — Vaksin, Pemeriksaan Umum, Edukasi Kesehatan",jam:"Senin–Kamis & Sabtu 09.00–12.00 + 16.00–20.00 | Jumat 09.00–11.00 + 16.00–20.00",tarif:"Konsultasi terjangkau",catatan:"Dikenal sabar & suka edukasi pemilik hewan | Cocok untuk konsultasi ternak",aktif:true},
  {id:"KT035",kategori:"Dokter Hewan",nama:"drh. Mokhamad Ridwan Rustandi MM (DnR Pet Clinic)",hp:"0813-1241-2225",hp2:"",alamat:"Jl. BKR No.11A, Tasikmalaya (depan Mahaka)",wilayah:"Kota Tasikmalaya",spesialisasi:"Kucing, Anjing, Hewan Ternak, Burung, Ayam, Bebek — Anggota PDHI",jam:"Senin–Jumat 08.00–17.00",tarif:"Konsultasi Rp 75.000+",catatan:"Lulusan FKH IPB 2007, pengalaman 11 tahun | WA: 081312412225 | Instagram: @dnr_pet_clinic",aktif:true},
  {id:"KT036",kategori:"Dokter Hewan",nama:"drh. Yudha (Crown Pet Care — Singaparna)",hp:"0812-3363-9924",hp2:"",alamat:"Jl. Raya Timur Cintaraja Singaparna, Cintaraja, Kec. Singaparna, Kab. Tasikmalaya 46417",wilayah:"Singaparna, Kab. Tasikmalaya & sekitar Garut",spesialisasi:"Hewan peliharaan & ternak — Pet Shop, Vaksin, Pemeriksaan Umum",jam:"Senin–Jumat 16.00–19.00 | Sabtu 12.00–14.00",tarif:"Konsultasi terjangkau",catatan:"Lokasi strategis di Singaparna — mudah dijangkau peternak Tasikmalaya Selatan",aktif:true},
  {id:"KT037",kategori:"Dokter Hewan",nama:"drh. Zainal Muttaqin (KANZEN VET CLINIC)",hp:"085214147778",hp2:"",alamat:"Tasikmalaya, Jawa Barat",wilayah:"Kota Tasikmalaya",spesialisasi:"Hewan peliharaan & ternak umum — Vaksin, Bedah Kecil",jam:"10.00 – selesai (setiap hari)",tarif:"Hubungi untuk info tarif",catatan:"Instagram: @klinik.kanzenvet | Dokter aktif & responsif",aktif:true},
  {id:"KT038",kategori:"Dokter Hewan",nama:"drh. Dini Dinarwati (Praktek Cihideung)",hp:"0812-2433-6020",hp2:"",alamat:"Jl. Letnan Kolonel Re Jaelani, Argasari, Kec. Cihideung, Kab. Tasikmalaya 46122",wilayah:"Kab. Tasikmalaya — area Cihideung",spesialisasi:"Hewan ternak & peliharaan — Sterilisasi, Vaksinasi, Pemeriksaan",jam:"Senin–Sabtu 09.00–17.00",tarif:"Terjangkau",catatan:"Pengalaman panjang di Tasikmalaya — telaten & sabar",aktif:true},

  // ── DOKTER HEWAN / KLINIK CIAMIS ──
  {id:"KT039",kategori:"Dokter Hewan",nama:"Klinik Hewan Ciamis (Jl. Ahmad Yani)",hp:"085214147778",hp2:"",alamat:"Jl. Ahmad Yani, Ruko Pancasila Plaza No.53/15, Ciamis 46131",wilayah:"Kab. Ciamis",spesialisasi:"Hewan peliharaan & ternak — Pemeriksaan, Vaksin, Pengobatan Umum",jam:"Senin–Sabtu 08.00–17.00",tarif:"Terjangkau",catatan:"Rating tinggi di Google Maps area Ciamis — hubungi via Google Maps untuk nomor terbaru",aktif:true},
  {id:"KT040",kategori:"Dokter Hewan",nama:"Klinik Hewan Sindangkasih (Ruko Buana TH)",hp:"0812-2269-9699",hp2:"",alamat:"Ruko 2, Jl. Buana Town House, Sindangkasih, Kec. Sindangkasih, Kab. Ciamis 46268",wilayah:"Kab. Ciamis — area Sindangkasih",spesialisasi:"Hewan peliharaan & ternak",jam:"Senin–Sabtu 08.00–17.00",tarif:"Hubungi langsung",catatan:"Salah satu rekomendasi teratas di Ciamis — cari nomor via Google Maps 'Klinik Hewan Sindangkasih'",aktif:true},

  // ── PUSKESWAN & DINAS PETERNAKAN TASIKMALAYA ──
  {id:"KT041",kategori:"Dinas Peternakan",nama:"Puskeswan Kota Tasikmalaya",hp:"0265-335669",hp2:"",alamat:"Jl. Raya Leuwidahu, Parakannyasag — di lingkungan Kantor Dinas Pertanian Kota Tasikmalaya",wilayah:"Kota Tasikmalaya & sekitar",spesialisasi:"Pemeriksaan & pengobatan hewan ternak + peliharaan — GRATIS (bayar seikhlasnya)",jam:"Senin–Jumat 07.30–15.30",tarif:"Gratis / seikhlasnya",catatan:"Berdiri sejak 2019 — aktif melayani. Dinas Pertanian Kota Tasik: 0265-335669",aktif:true},
  {id:"KT042",kategori:"Dinas Peternakan",nama:"Dinas Pertanian Kab. Tasikmalaya (DPKPP)",hp:"0265-330163",hp2:"",alamat:"Komplek Perkantoran Kab. Tasikmalaya, Jl. Bojongkoneng, Sukaasih, Singaparna 46415",wilayah:"Kab. Tasikmalaya",spesialisasi:"Peternakan, Kesehatan Hewan, IB Sapi & Domba, Vaksinasi Massal, Laporan Penyakit",jam:"Senin–Jumat 07.30–15.30",tarif:"Gratis",catatan:"Website: dpkpp.tasikmalayakab.go.id | Hubungi untuk program IB gratis & vaksin bersubsidi",aktif:true},
  {id:"KT043",kategori:"Dinas Peternakan",nama:"Dinas Peternakan Perikanan & Kelautan Kab. Tasikmalaya",hp:"0265-331606",hp2:"",alamat:"Jl. Achmad Yani No.128, Tasikmalaya",wilayah:"Kab. Tasikmalaya",spesialisasi:"Peternakan, Kesehatan Hewan Ternak, Obat Hewan Bersubsidi",jam:"Senin–Jumat 08.00–15.30",tarif:"Gratis — pelayanan pemerintah",catatan:"Hubungi untuk bantuan teknis penyakit ternak, vaksinasi PMK & AI bersubsidi",aktif:true},

  // ── PUSKESWAN & DINAS PETERNAKAN CIAMIS ──
  {id:"KT044",kategori:"Dinas Peternakan",nama:"Dinas Peternakan & Perikanan Kab. Ciamis",hp:"0265-771024",hp2:"0265-771511",hp2:"",alamat:"Jl. Lebursitu No.44, Ciamis 46213",wilayah:"Kab. Ciamis",spesialisasi:"Peternakan, Kesehatan Hewan, IB Sapi, Vaksinasi, Laporan Penyakit Strategis",jam:"Senin–Jumat 08.00–15.00 | Sabtu–Minggu Tutup",tarif:"Gratis",catatan:"Website: disnakan.ciamiskab.go.id | Instagram: @disnakkan.ciamis | Email: distankpkabciamis@gmail.com",aktif:true},

  // ── MANTRI HEWAN TASIKMALAYA–CIAMIS ──
  {id:"KT045",kategori:"Mantri Hewan",nama:"Mantri Hewan — Puskeswan Singaparna",hp:"0265-330163",hp2:"",alamat:"Kec. Singaparna, Kab. Tasikmalaya",wilayah:"Singaparna & kecamatan sekitar",spesialisasi:"Vaksinasi Sapi & Domba, Obat Cacing, PMK, IB, Pengobatan Dasar Ternak",jam:"Senin–Jumat 07.30–15.00 (panggilan fleksibel)",tarif:"Gratis (Puskeswan Pemerintah) + ongkos transport",catatan:"Hubungi melalui Dinas Pertanian Kab. Tasikmalaya 0265-330163 untuk dirujuk ke mantri wilayah",aktif:true},
  {id:"KT046",kategori:"Mantri Hewan",nama:"Mantri Hewan — Puskeswan Ciamis Kota",hp:"0265-771024",hp2:"",alamat:"Jl. Lebursitu No.44, Ciamis — Kantor Dinas Peternakan Kab. Ciamis",wilayah:"Ciamis Kota & kecamatan sekitar",spesialisasi:"Vaksinasi, Obat Cacing, Pengobatan Sapi/Domba/Unggas, IB, Laporan PMK",jam:"Senin–Jumat 08.00–15.00 (panggilan fleksibel)",tarif:"Gratis (program pemerintah)",catatan:"Hubungi Disnakan Ciamis 0265-771024 untuk diarahkan ke mantri wilayah terdekat",aktif:true},
  {id:"KT047",kategori:"Mantri Hewan",nama:"Mantri Hewan — Puskeswan Manonjaya (Kab. Tasik)",hp:"0265-330163",hp2:"",alamat:"Kec. Manonjaya, Kab. Tasikmalaya",wilayah:"Manonjaya, Salawu, Cigalontang & sekitar",spesialisasi:"Sapi Potong, Domba Garut, Vaksinasi ND/AI Unggas, PMK",jam:"Senin–Jumat (panggilan farm tersedia)",tarif:"Gratis + transport",catatan:"Hubungi Dinas Kab. Tasik 0265-330163 untuk kontak mantri kecamatan ini",aktif:true},

  // ══════════════════════════════════════════════════
  //  PERBANKAN & PEMBIAYAAN — KUR & Modal Usaha Ternak
  // ══════════════════════════════════════════════════
  {id:"KT048",kategori:"Perbankan & KUR",nama:"Bank BRI — Call Center KUR & Kredit Usaha",hp:"1500017",hp2:"14017",alamat:"Kantor BRI terdekat — atau via call center 24 jam",wilayah:"Seluruh Indonesia",spesialisasi:"KUR Mikro (max Rp 100 jt), KUR Kecil (max Rp 500 jt), KUR TKI, Simpedes, Tabungan Ternak",jam:"Call Center 24 jam / Kantor Cabang Senin–Jumat 08.00–15.30",tarif:"Bunga KUR 6%/tahun (subsidi pemerintah)",catatan:"BRI paling banyak menyalurkan KUR pertanian & peternakan. WA: 081212-14017 | Tanyakan KUR Klaster Sapi/Domba",aktif:true},
  {id:"KT049",kategori:"Perbankan & KUR",nama:"Bank BNI — Call Center 24 Jam",hp:"1500046",hp2:"68888",alamat:"Kantor BNI terdekat — atau via call center",wilayah:"Seluruh Indonesia",spesialisasi:"KUR BNI (max Rp 500 jt), Kredit Investasi, BNI Agri Loan untuk Peternakan Komersial",jam:"Call Center 24 jam / Kantor Senin–Jumat 08.00–15.30",tarif:"Bunga KUR 6%/tahun",catatan:"WA resmi BNI: 08115881946 | BNI memiliki program khusus kredit agribisnis dan peternakan",aktif:true},
  {id:"KT050",kategori:"Perbankan & KUR",nama:"Bank Mandiri — Mandiri Call 24 Jam",hp:"14000",hp2:"021-5299-7777",alamat:"Kantor Bank Mandiri terdekat",wilayah:"Seluruh Indonesia",spesialisasi:"KUR Mandiri, Kredit Investasi Agri, Deposito, Cash Management, Payroll",jam:"Call Center 24 jam / Kantor Senin–Jumat 08.00–15.30",tarif:"Bunga KUR 6%/tahun",catatan:"Mandiri kuat di kredit investasi kandang & alat mesin peternakan skala menengah",aktif:true},
  {id:"KT051",kategori:"Perbankan & KUR",nama:"Bank BPD Jabar (BJB) — KUR & Agri",hp:"14049",hp2:"022-4230 333",alamat:"Kantor BJB Cabang Tasikmalaya / Ciamis terdekat",wilayah:"Jawa Barat & Banten",spesialisasi:"KUR BJB (agri, ternak, UMKM), Kredit UMKM Jabar, Kartu Kredit Petani Ternak",jam:"Call Center jam kerja / Kantor Senin–Jumat 08.00–15.00",tarif:"Bunga KUR 6%/tahun — khusus Jabar ada program subsidi tambahan",catatan:"BJB paling dekat untuk peternak Tasik-Ciamis — ada cabang di Singaparna & Ciamis Kota",aktif:true},

  // ══════════════════════════════════════════════════
  //  ASURANSI TERNAK — AUTS & AUTK Pemerintah
  // ══════════════════════════════════════════════════
  {id:"KT052",kategori:"Asuransi & BPJS",nama:"Jasindo Asuransi — AUTS/AUTK (Asuransi Ternak)",hp:"021-5080-5555",hp2:"1500-337",alamat:"PT Asuransi Jasa Indonesia (Jasindo), Jakarta",wilayah:"Seluruh Indonesia",spesialisasi:"AUTS (Asuransi Usaha Ternak Sapi) Rp 10 jt/ekor subsidi pemerintah, AUTK (Ayam/Ternak Kecil)",jam:"Senin–Jumat 08.00–17.00",tarif:"Premi AUTS: Rp 200.000/ekor/tahun (subsidi 80% dari APBN)",catatan:"Daftar AUTS lewat Dinas Peternakan atau mantri setempat — WAJIB diikuti peternak penerima bantuan pemerintah",aktif:true},
  {id:"KT053",kategori:"Asuransi & BPJS",nama:"BPJS Ketenagakerjaan — Perlindungan Pekerja Farm",hp:"175",hp2:"1500-910",alamat:"Kantor BPJS TK terdekat / bpjsketenagakerjaan.go.id",wilayah:"Seluruh Indonesia",spesialisasi:"JHT, JKK, JKM, JP untuk karyawan kandang & pekerja farm",jam:"Call Center 24 jam / Kantor Senin–Jumat 08.00–15.30",tarif:"Iuran minimal Rp 16.800/bulan/orang (JKK+JKM+JHT)",catatan:"Wajib mendaftar BPJS TK jika punya karyawan tetap — sanksi hukum jika tidak mendaftar",aktif:true},

  // ══════════════════════════════════════════════════
  //  LOGISTIK & TRANSPORTASI TERNAK
  // ══════════════════════════════════════════════════
  {id:"KT054",kategori:"Logistik & Transportasi",nama:"Perumda Dharma Jaya (RPH & Distribusi Daging Jakarta)",hp:"021-4892-1555",hp2:"",alamat:"Jl. Raya Penggilingan No.25, Cakung, Jakarta Timur 13940",wilayah:"DKI Jakarta & sekitar — distribusi daging sapi/domba",spesialisasi:"RPH Sapi & Domba bersertifikat Halal, Cold Storage, Distribusi Daging Jakarta",jam:"Senin–Jumat 07.00–16.00",tarif:"Tarif RPH sesuai Perda DKI",catatan:"Mitra potong untuk sapi/domba yang ingin dijual ke pasar Jakarta — RPH terbesar Jabodetabek",aktif:true},
  {id:"KT055",kategori:"Logistik & Transportasi",nama:"Ekspedisi Ternak — PT Ciomas Adisatwa (Japfa RPA)",hp:"0251-8611392",hp2:"",alamat:"Jl. Raya Parung Bogor KM.24 Gg. Sawo No.25, Kemang, Bogor 16310",wilayah:"Jawa Barat & Jabodetabek",spesialisasi:"RPA (Rumah Potong Ayam) Broiler bersertifikat, Cold Chain, Distribusi Produk Olahan",jam:"Senin–Sabtu 07.00–17.00",tarif:"Tarif per batch — hubungi sales",catatan:"Anak perusahaan Japfa — solusi pemotongan + distribusi broiler skala komersial",aktif:true},
  {id:"KT056",kategori:"Logistik & Transportasi",nama:"JNE Ekspres — Pengiriman DOC & Bibit",hp:"021-2927-8888",hp2:"",alamat:"Kantor JNE terdekat — atau jneonline.com",wilayah:"Seluruh Indonesia",spesialisasi:"Pengiriman DOC (Day Old Chick), Telur Tetas, Bibit Ternak Kecil via Kargo Udara/Darat",jam:"Call Center 24 jam / Agen terdekat Senin–Sabtu",tarif:"Tarif kargo sesuai berat & tujuan — tanyakan tarif DOC live animal",catatan:"Pastikan kemasan DOC sesuai standar biosekuriti | JNE ada layanan khusus live animal",aktif:true},

  // ══════════════════════════════════════════════════
  //  PEMASARAN & PLATFORM DIGITAL
  // ══════════════════════════════════════════════════
  {id:"KT057",kategori:"Pemasaran Digital",nama:"Jualternak.com — Marketplace Ternak Online",hp:"081215778768",hp2:"",alamat:"aplikasi digital — cari di PlayStore / AppStore",wilayah:"Seluruh Indonesia",spesialisasi:"Platform jual beli ternak online, marketplace sapi/domba/ayam langsung ke pembeli",jam:"24 jam",tarif:"Komisi jual beli sesuai platform",catatan:"Alternatif jual ternak via digital — cek juga: Ternakita.id, Sapiqu.com, iGrow, Tokopedia/Shopee kategori ternak",aktif:true},
  {id:"KT058",kategori:"Pemasaran Digital",nama:"BAZNAS — Program Hewan Kurban & Aqiqah",hp:"021-3904555",hp2:"0811-100-1344",alamat:"Jl. Kebon Sirih Raya No.57, Jakarta Pusat 10340",wilayah:"Seluruh Indonesia",spesialisasi:"Pembelian sapi/domba kurban massal, aqiqah, program ternak zakat produktif",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga pasar — volume besar lebih kompetitif",catatan:"Channel penjualan kurban terpercaya — buka jalur BAZNAS jauh sebelum Idul Adha (minimal 3 bulan)",aktif:true},

  // ══════════════════════════════════════════════════
  //  PAKAN TAMBAHAN & BAHAN BAKU
  // ══════════════════════════════════════════════════
  {id:"KT059",kategori:"Penjual Pakan",nama:"PT Petrokimia Gresik — Pupuk & Molases",hp:"031-3981811",hp2:"0800-1-PETRO (738760)",alamat:"Jl. Jend. Ahmad Yani, Gresik, Jawa Timur 61119",wilayah:"Seluruh Indonesia — via kios resmi / distributor",spesialisasi:"Molases (tetes tebu) untuk pakan fermentasi, ZA, pupuk kandang olahan, Petroganik",jam:"Senin–Jumat 07.00–16.00",tarif:"Harga distributor — hubungi kios resmi Petrokimia daerah",catatan:"Molases Petrokimia tersedia di kios pertanian — bahan utama silase & pakan fermentasi sapi",aktif:true},
  {id:"KT060",kategori:"Penjual Pakan",nama:"PT Wilmar International — Dedak & Bungkil Sawit",hp:"021-2996-9999",hp2:"",alamat:"Jl. MH Thamrin No.31, Jakarta Pusat 10230",wilayah:"Seluruh Indonesia — via distributor regional",spesialisasi:"Bungkil Sawit (Palm Kernel Meal), Dedak, Minyak Sawit (CPO) untuk campuran pakan ternak",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga bulk — ton-an via distributor",catatan:"Bungkil sawit = bahan pakan murah & bergizi — bagus untuk sapi & broiler. Minta kontak distributor daerah",aktif:true},

  // ══════════════════════════════════════════════════
  //  LEMBAGA & ASOSIASI TERNAK NASIONAL
  // ══════════════════════════════════════════════════
  {id:"KT061",kategori:"Lainnya",nama:"GPPU (Gabungan Perusahaan Pembibitan Unggas)",hp:"021-4787-7890",hp2:"",alamat:"Jl. MT Haryono Kav.62, Jakarta Selatan",wilayah:"Seluruh Indonesia — Asosiasi DOC & Bibit Unggas",spesialisasi:"Informasi harga DOC nasional, standar kualitas bibit, isu industri unggas",jam:"Senin–Jumat 09.00–16.00",tarif:"—",catatan:"Bergabung untuk informasi harga DOC patokan nasional — penting untuk negosiasi harga beli DOC",aktif:true},
  {id:"KT062",kategori:"Lainnya",nama:"HPDKI (Himpunan Peternak Domba Kambing Indonesia)",hp:"022-2030-8588",hp2:"",alamat:"Jl. Taman Sari No.1, Bandung — Jawa Barat",wilayah:"Seluruh Indonesia, kuat di Jabar & Jateng",spesialisasi:"Pasar domba, standar harga pasar, program sertifikasi bibit domba Garut, networking peternak",jam:"Senin–Jumat 08.00–16.00",tarif:"Iuran anggota",catatan:"Bergabung HPDKI untuk akses data harga domba Garut nasional & jaringan pembeli besar",aktif:true},
  {id:"KT063",kategori:"Lainnya",nama:"GAPUSPINDO (Gabungan Pengusaha Sapi Potong Indonesia)",hp:"021-5200-456",hp2:"",alamat:"Jakarta — asosiasi nasional feedlot & sapi potong",wilayah:"Seluruh Indonesia",spesialisasi:"Harga sapi nasional, kebijakan impor sapi, standar feedlot, info lelang sapi",jam:"Senin–Jumat 09.00–16.00",tarif:"Iuran anggota",catatan:"Penting untuk peternak sapi yang ingin masuk pasar retail besar & informasi harga sapi nasional",aktif:true},
  {id:"KT064",kategori:"Lainnya",nama:"BAPANAS (Badan Pangan Nasional) — Info Harga Pangan",hp:"021-7807-7678",hp2:"",alamat:"Jl. Harsono RM No.3, Ragunan, Jakarta Selatan",wilayah:"Seluruh Indonesia",spesialisasi:"Harga referensi daging sapi, ayam, telur, stabilisasi harga pangan nasional",jam:"Senin–Jumat 08.00–16.00",tarif:"Gratis",catatan:"Pantau harga referensi pemerintah di badanpangan.go.id — acuan harga jual/beli ternak & produknya",aktif:true},

  // ══════════════════════════════════════════════════
  //  🧬 BREEDING & GENETIKA — SAPI & DOMBA
  // ══════════════════════════════════════════════════
  {id:"KT065",kategori:"Breeding & Genetika",nama:"BIB Lembang — Semen Beku Sapi & Kambing",hp:"022-2786222",hp2:"022-2787271",alamat:"Jl. Kayu Ambon No.78, Lembang, Kab. Bandung Barat 40391",wilayah:"Jawa Barat & Nasional — IB Sapi Perah & Potong",spesialisasi:"Semen beku sapi (FH, Simental, Limousin, Bali, Wagyu), kambing PE/Boer/Saanen, pelatihan IB",jam:"Senin–Jumat 07.30–15.30",tarif:"Sesuai tarif PMK — semen beku Rp 15.000–75.000/straw",catatan:"Email: biblembang@pertanian.go.id | Website: biblembang.ditjenpkh.pertanian.go.id | Konsultasi bebas untuk peternak",aktif:true},
  {id:"KT066",kategori:"Breeding & Genetika",nama:"BBIB Singosari — Semen Beku & Pelatihan IB",hp:"0341-458359",hp2:"0341-458474",alamat:"Jl. BBIB No.1, Ds. Toyomarto, Kec. Singosari, Malang 65153",wilayah:"Seluruh Indonesia — Produsen semen beku terbesar",spesialisasi:"Semen beku 10 ras sapi (Limousin/Simental/Angus/Brangus/Brahman/Ongole/Bali/FH/Madura/Wagyu) + kambing",jam:"Senin–Jumat 07.00–15.30",tarif:"Tarif PMK 39/2019 — hubungi untuk katalog harga",catatan:"HP WA: 085895679267 | Email: bbib.singosari@pertanian.go.id | SNI Award 2023 — kualitas terverifikasi",aktif:true},
  {id:"KT067",kategori:"Breeding & Genetika",nama:"BPTUHPT Baturraden — Bibit Sapi HMT",hp:"0281-681182",hp2:"",alamat:"Jl. Raya Baturraden KM.20, Purwokerto, Jawa Tengah 53151",wilayah:"Jawa Tengah & sekitar",spesialisasi:"Bibit sapi FH unggul, semen beku, hijauan makanan ternak (HMT) unggul, pelatihan breeding",jam:"Senin–Jumat 07.30–15.30",tarif:"Tarif BLU pemerintah",catatan:"Pusat pembibitan sapi perah FH pemerintah — sumber bibit FH untuk peternak Jabar & Jateng",aktif:true},
  {id:"KT068",kategori:"Breeding & Genetika",nama:"PT Santosa Agrindo (Santori Beef — Japfa)",hp:"021-2854-5680",hp2:"",alamat:"Wisma Millenia Lt.7, Jl. MT Haryono Kav.16, Jakarta — Feedlot Lampung & Jatim",wilayah:"Seluruh Indonesia — Feedlot + RPH + Distribusi Daging Sapi Premium",spesialisasi:"Feedlot 150.000 ekor/th, Wagyu breeding 10.000 ekor, RPH standar ekspor, daging premium Tokusen Wagyu",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga wholesale — HORECA & supermarket",catatan:"Anak perusahaan Japfa Comfeed — kontak via Japfa pusat 021-2854-5680. Website: japfacomfeed.co.id/peternakan-sapi",aktif:true},

  // ══════════════════════════════════════════════════
  //  🌿 NUTRISI, RISET & TEKNOLOGI PAKAN
  // ══════════════════════════════════════════════════
  {id:"KT069",kategori:"Riset & Nutrisi",nama:"BPTP Jawa Barat — Teknologi Pertanian Lokal",hp:"022-2786238",hp2:"022-2789846",alamat:"Jl. Kayuambon No.80, Lembang, Bandung Barat 40391",wilayah:"Jawa Barat",spesialisasi:"Teknologi pakan fermentasi, silase, UMMB, budidaya HMT unggul, inovasi peternakan spesifik lokasi",jam:"Senin–Jumat 08.00–15.30",tarif:"Gratis — konsultasi penelitian",catatan:"Email: bptp-jabar@litbang.pertanian.go.id | Sumber rekomendasi teknologi pakan lokal Jabar berbasis riset",aktif:true},
  {id:"KT070",kategori:"Riset & Nutrisi",nama:"Balitnak Bogor — Balai Penelitian Ternak",hp:"0251-8240752",hp2:"0251-8240754",alamat:"Jl. Veteran III No.1, Ciawi, Bogor, Jawa Barat 16002",wilayah:"Seluruh Indonesia — Lembaga Riset Ternak Nasional",spesialisasi:"Riset nutrisi pakan, formula ransum, breed unggulan, probiotik, teknologi reproduksi",jam:"Senin–Jumat 08.00–16.00",tarif:"Gratis konsultasi / tarif uji laboratorium",catatan:"Email: balitnak@litbang.pertanian.go.id | Sumber referensi nutrisi pakan ternak tertinggi di Indonesia",aktif:true},
  {id:"KT071",kategori:"Riset & Nutrisi",nama:"Fakultas Peternakan IPB University Bogor",hp:"0251-8628304",hp2:"",alamat:"Jl. Agatis, Kampus IPB Dramaga, Bogor 16680",wilayah:"Nasional — Perguruan Tinggi Peternakan Terbaik",spesialisasi:"Konsultasi nutrisi, breeding, riset kolaborasi, magang mahasiswa, uji laboratorium pakan & produk",jam:"Senin–Jumat 08.00–16.00",tarif:"Tarif konsultasi profesional",catatan:"Hubungi untuk kerja sama penelitian, pengujian nutrisi pakan, konsultasi teknis peternakan komersial",aktif:true},
  {id:"KT072",kategori:"Riset & Nutrisi",nama:"PT Eka Farma (Suplemen & Premix Ternak)",hp:"0274-868148",hp2:"",alamat:"Jl. Industri No.12, Yogyakarta",wilayah:"Jawa & Nasional",spesialisasi:"Premix vitamin-mineral sapi/domba/unggas, probiotik, mineral block, suplemen reproduksi (Ovusync, Estrumate)",jam:"Senin–Sabtu 08.00–16.00",tarif:"Harga distributor",catatan:"Produk unggulan: EM4 Peternakan, mineral blok sapi, booster reproduksi — tersedia di toko pertanian",aktif:true},
  {id:"KT073",kategori:"Riset & Nutrisi",nama:"PT Sinta Prima Feedmill — Premix & Additive",hp:"021-8896-0550",hp2:"",alamat:"Jl. Raya Bekasi Km.25, Jakarta Timur",wilayah:"Jawa & Nasional",spesialisasi:"Premix layer/broiler/sapi, toxin binder, asam amino sintetis (Met/Lys), enzim phytase, beta-glucan",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga distributor bulk",catatan:"Supplier premix untuk formula pakan mandiri — produk terverifikasi Ditjen PKH",aktif:true},

  // ══════════════════════════════════════════════════
  //  🏭 PRODUKSI & PENGOLAHAN HASIL TERNAK
  // ══════════════════════════════════════════════════
  {id:"KT074",kategori:"Produksi & Pengolahan",nama:"PT Greenfields Indonesia — Susu Sapi Segar",hp:"0341-551989",hp2:"",alamat:"Jl. Ngadas, Poncokusumo, Malang, Jawa Timur 65157",wilayah:"Jawa & Nasional",spesialisasi:"Pengolahan susu segar, kerjasama penyetoran susu peternak lokal, harga susu premium",jam:"Senin–Sabtu 07.00–16.00",tarif:"Harga beli susu: Rp 5.500–7.500/liter (tergantung kualitas)",catatan:"Salah satu perusahaan susu terbesar — bisa menjadi offtaker susu untuk peternak sapi perah",aktif:true},
  {id:"KT075",kategori:"Produksi & Pengolahan",nama:"PT Indolakto / Indomilk (AISF Group)",hp:"0251-8312191",hp2:"",alamat:"Jl. Raya Siliwangi No.31, Cicurug, Sukabumi, Jawa Barat",wilayah:"Jawa Barat & Nasional",spesialisasi:"Pengolahan susu, offtaker susu sapi perah, koperasi susu mitra",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga beli susu berdasarkan kualitas dan volume",catatan:"Pabrik terdekat dari Tasikmalaya — potensial sebagai offtaker susu sapi perah Jabar Selatan",aktif:true},
  {id:"KT076",kategori:"Produksi & Pengolahan",nama:"KPBS Pangalengan (Koperasi Peternak Sapi)",hp:"022-5977-141",hp2:"",alamat:"Jl. Raya Pangalengan No.340, Bandung 40378",wilayah:"Jawa Barat — Model koperasi susu terbesar Jabar",spesialisasi:"Koperasi susu sapi perah, IB subsidi anggota, pengolahan susu, kredit sapronak",jam:"Senin–Sabtu 07.00–15.00",tarif:"Harga koperasi — kompetitif",catatan:"Bergabung KPBS untuk akses IB bersubsidi, kredit pakan, dan saluran jual susu — model bisnis terbaik",aktif:true},
  {id:"KT077",kategori:"Produksi & Pengolahan",nama:"PT Wonosari Jaya (Telur & Layer Nasional)",hp:"0274-496200",hp2:"",alamat:"Jl. Wonosari Km.14, Bantul, Yogyakarta 55762",wilayah:"Jawa & Nasional",spesialisasi:"Produksi telur konsumsi skala besar, distribusi telur nasional, kemitraan peternak layer",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga telur: ikuti harga acuan BAPANAS",catatan:"Model kemitraan layer skala besar — bisa jadi referensi atau offtaker telur untuk peternak layer",aktif:true},

  // ══════════════════════════════════════════════════
  //  🛒 PEMASARAN HILIR — RETAIL & HORECA
  // ══════════════════════════════════════════════════
  {id:"KT078",kategori:"Pemasaran Hilir",nama:"Transmart / Carrefour — Supplier Daging & Telur",hp:"1500-110",hp2:"",alamat:"Kantor pusat: Jl. Lebak Bulus No.8, Jakarta Selatan",wilayah:"Seluruh Indonesia — jaringan hypermarket terbesar",spesialisasi:"Supplier sapi/domba/broiler/telur ke jaringan retail modern — volume besar konsisten",jam:"Call center 24 jam / Procurement Senin–Jumat",tarif:"Harga kontrak bulk — lebih rendah tapi volume terjamin",catatan:"Hubungi divisi procurement untuk menjadi supplier tetap — butuh SIUP, NKV, sertifikat halal MUI",aktif:true},
  {id:"KT079",kategori:"Pemasaran Hilir",nama:"GrabFood/GoFood — Mitra UMKM Ternak Olahan",hp:"021-2985-0000",hp2:"",alamat:"grab.com/id/merchant | gofood.co.id/merchant",wilayah:"Seluruh Indonesia — platform delivery terbesar",spesialisasi:"Jual produk olahan ternak (dendeng, bakso, sate, susu, telur) via aplikasi digital",jam:"24 jam",tarif:"Komisi 15–30% per transaksi",catatan:"Daftar sebagai merchant untuk menjual produk olahan ternak langsung ke konsumen via digital — modal kecil",aktif:true},
  {id:"KT080",kategori:"Pemasaran Hilir",nama:"PT Great Giant Livestock (GGL) — Beef Premium",hp:"0725-47001",hp2:"",alamat:"Terbanggi Besar, Lampung Tengah, Lampung 34163",wilayah:"Seluruh Indonesia — feedlot + distribusi",spesialisasi:"Penggemukan sapi impor 100.000 ekor/th, distribusi daging premium, kemitraan sapi potong",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga wholesale",catatan:"Feedlot terbesar Indonesia — kontak untuk informasi harga sapi bakalan + referensi standar feedlot nasional",aktif:true},

  // ══════════════════════════════════════════════════
  //  📊 SOSIAL EKONOMI & KEMITRAAN
  // ══════════════════════════════════════════════════
  {id:"KT081",kategori:"Sosial & Kemitraan",nama:"Koperasi Unit Desa (KUD) Setempat",hp:"021-7815380",hp2:"",alamat:"Kantor KUD Kecamatan setempat",wilayah:"Kecamatan — akses paling dekat",spesialisasi:"Kredit sapronak, pembelian kolektif pakan, penjualan kolektif ternak, asuransi ternak AUTS",jam:"Senin–Jumat 08.00–15.00",tarif:"Biaya keanggotaan minimal",catatan:"BERGABUNG KUD = akses harga pakan lebih murah, IB bersubsidi, dan pinjaman modal usaha tanpa agunan besar",aktif:true},
  {id:"KT082",kategori:"Sosial & Kemitraan",nama:"PPL / Penyuluh Pertanian Lapangan (BPP)",hp:"0265-330163",hp2:"",alamat:"Balai Penyuluhan Pertanian (BPP) Kecamatan setempat",wilayah:"Kecamatan masing-masing",spesialisasi:"Bimbingan teknis peternakan, akses program bantuan pemerintah, pendampingan SIUP & perizinan",jam:"Senin–Jumat 07.30–15.30",tarif:"Gratis",catatan:"PPL adalah jembatan antara peternak dan program pemerintah — WAJIB kenal PPL kecamatan anda",aktif:true},
  {id:"KT083",kategori:"Sosial & Kemitraan",nama:"Dinas Koperasi & UMKM Kab. Tasikmalaya",hp:"0265-330566",hp2:"",alamat:"Komplek Perkantoran Singaparna, Kab. Tasikmalaya",wilayah:"Kab. Tasikmalaya",spesialisasi:"Pendaftaran koperasi ternak, izin usaha UMKM, akses KUR, pelatihan manajemen usaha",jam:"Senin–Jumat 08.00–15.30",tarif:"Gratis",catatan:"Urus legalitas usaha peternakan & akses program UMKM Jabar — syarat utama untuk akses KUR bank",aktif:true},
  {id:"KT084",kategori:"Sosial & Kemitraan",nama:"Dinas Koperasi & UMKM Kab. Ciamis",hp:"0265-771297",hp2:"",alamat:"Jl. Jend. Ahmad Yani No.171, Kertasari, Ciamis 46213",wilayah:"Kab. Ciamis",spesialisasi:"Legalitas UMKM, koperasi, KUR, pelatihan wirausaha ternak",jam:"Senin–Jumat 08.00–15.30",tarif:"Gratis",catatan:"Hubungi untuk pendampingan legalisasi usaha peternakan dan akses dana bergulir UMKM",aktif:true},

  // ══════════════════════════════════════════════════
  //  🏥 KESEHATAN HEWAN TERNAK (THT)
  // ══════════════════════════════════════════════════
  {id:"KT085",kategori:"Laboratorium & THT",nama:"BBVET Wates Yogyakarta — Lab Diagnosa Penyakit",hp:"0274-773222",hp2:"0274-773223",alamat:"Jl. Raya Wates Km.27, Gamping, Sleman, Yogyakarta 55291",wilayah:"Jawa Tengah, DIY, Jawa Timur, Kalimantan",spesialisasi:"Diagnosa definitif PMK, AI, Brucella, Babesia, Anaplasma, PCR, serologi, histopatologi",jam:"Senin–Jumat 08.00–16.00",tarif:"Tarif uji lab sesuai PMK (kirim sampel darah/jaringan/swab)",catatan:"Email: bbvet.wates@pertanian.go.id | Kirim sampel untuk konfirmasi wabah sebelum laporan ke Dinas",aktif:true},
  {id:"KT086",kategori:"Laboratorium & THT",nama:"BPMSOH Gunungsindur — Uji Obat & Vaksin Hewan",hp:"0251-8610308",hp2:"",alamat:"Jl. Raya Gunungsindur, Kec. Gunungsindur, Bogor 16340",wilayah:"Seluruh Indonesia — laboratorium rujukan nasional",spesialisasi:"Pengujian mutu vaksin hewan, registrasi obat hewan, standar NKV (Nomor Kontrol Veteriner)",jam:"Senin–Jumat 08.00–15.30",tarif:"Tarif uji laboratorium",catatan:"Hubungi untuk informasi persyaratan NKV RPH dan pendaftaran produk hewan olahan",aktif:true},
  {id:"KT087",kategori:"Laboratorium & THT",nama:"PT Vaksindo Satwa Nusantara (Japfa Vaksin)",hp:"021-7800-939",hp2:"",alamat:"Jl. Raya Kemang Km.1, Kabupaten Bogor, Jawa Barat",wilayah:"Seluruh Indonesia",spesialisasi:"Vaksin unggas (ND, AI, IB, Gumboro, Marek), vaksin sapi (PMK, Anthrax, Brucella), cold chain",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga distributor — tanya sales daerah",catatan:"Anak perusahaan Japfa — produsen vaksin hewan terbesar Indonesia. Distribusi via agen Medion & apotek hewan",aktif:true},
  {id:"KT088",kategori:"Laboratorium & THT",nama:"Intervet / MSD Animal Health Indonesia",hp:"021-2995-7000",hp2:"",alamat:"Gedung Millenium, Jl. MT Haryono Kav.16, Jakarta",wilayah:"Seluruh Indonesia",spesialisasi:"Vaksin Nobilis (ND/AI/IB/Gumboro), Bovilis (sapi), obat antiparasit Ivomec, Dectomax, Panacur",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor resmi — apotek hewan & drh",catatan:"Produk premium global — Ivomec & Dectomax standar internasional untuk antiparasit sapi & domba",aktif:true},
  {id:"KT089",kategori:"Laboratorium & THT",nama:"Boehringer Ingelheim Indonesia — Vaksin Hewan",hp:"021-2993-9700",hp2:"",alamat:"Jl. MT Haryono Kav.9-11, Jakarta Selatan 12810",wilayah:"Seluruh Indonesia",spesialisasi:"Vaksin Ingelvac Circo (babi), vaksin ND/AI unggas, Draxxin (tilmicosin sapi), Metacam (meloxicam)",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor & apotek hewan",catatan:"Metacam (meloxicam) — NSAID terbaik untuk sapi & domba | Draxxin untuk pneumonia sapi 1× injeksi",aktif:true},

  // ══════════════════════════════════════════════════
  //  🌾 PAKAN HULU — BAHAN BAKU & SUPPLIER
  // ══════════════════════════════════════════════════
  {id:"KT090",kategori:"Pakan Hulu",nama:"PT SIEVERT Lyofreeze Indonesia — Additive Pakan",hp:"021-5835-3838",hp2:"",alamat:"Jl. Boulevard Raya Blok WA-2, Kelapa Gading, Jakarta",wilayah:"Seluruh Indonesia",spesialisasi:"Asam amino L-Lysine, DL-Methionine, L-Threonine, L-Tryptophan untuk pakan unggas & ruminansia",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga bulk distributor",catatan:"Supplier asam amino sintetis — komponen kritis formula pakan broiler & layer mandiri",aktif:true},
  {id:"KT091",kategori:"Pakan Hulu",nama:"PT Bungasari Flour Mills — Pollard & Wheat Bran",hp:"021-8370-0088",hp2:"",alamat:"Jl. Raya Cilincing, Tanjung Priok, Jakarta Utara",wilayah:"Jawa & Nasional",spesialisasi:"Pollard / dedak gandum untuk pakan sapi, domba, layer — by-product tepung terigu berkualitas",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga bulk per ton",catatan:"Pollard Bungasari = bahan pakan standar industri — protein 15%, serat larut tinggi, harga Rp 4.500–5.000/kg",aktif:true},
  {id:"KT092",kategori:"Pakan Hulu",nama:"PT RNI / Sugar Group — Molases (Tetes Tebu)",hp:"021-3192-4000",hp2:"",alamat:"Jl. Gambir No.2, Jakarta Pusat 10110",wilayah:"Jawa & Sumatra",spesialisasi:"Molases/tetes tebu untuk pakan fermentasi sapi, pemanis ransum, bahan silase & UMMB",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga molases Rp 1.500–2.500/kg — tergantung pabrik gula",catatan:"Hubungi pabrik gula terdekat (PTPN X, XI, XIV) untuk sumber molases lokal lebih murah",aktif:true},
  {id:"KT093",kategori:"Pakan Hulu",nama:"Bungkil Kelapa & Kopra Lokal — Pedagang Bahan Pakan",hp:"031-3981811",hp2:"",alamat:"Pasar komoditas lokal & koperasi kelapa daerah",wilayah:"Jabar, Jateng, Jatim — produsen kelapa",spesialisasi:"Bungkil kelapa untuk pakan sapi/domba — protein 18–21%, murah & melimpah di Jawa",jam:"—",tarif:"Rp 3.500–4.500/kg",catatan:"Cari via pedagang bahan pakan lokal atau pabrik pengolahan kelapa daerah — sumber energi murah",aktif:true},
  {id:"KT094",kategori:"Pakan Hulu",nama:"Ampas Tahu & Onggok — Pabrik Tahu Lokal",hp:"0265-771024",hp2:"",alamat:"Pabrik tahu terdekat / pedagang ampas kedelai",wilayah:"Seluruh Jawa — melimpah di sentra tahu",spesialisasi:"Ampas tahu segar/kering untuk sapi & domba — protein 25–30%, harga sangat murah",jam:"Setiap hari",tarif:"Rp 300–800/kg segar | Rp 2.000–3.000/kg kering",catatan:"Onggok (ampas singkong) juga tersedia di pabrik tapioka — sumber energi fermentasi murah",aktif:true},
  {id:"KT095",kategori:"Pakan Hulu",nama:"Kios Pertanian & Sapronak Setempat",hp:"0265-330163",hp2:"",alamat:"Pasar pertanian kecamatan setempat",wilayah:"Lokal",spesialisasi:"Jagung giling, dedak padi, kapur CaCO₃, garam ternak, mineral block, EM4 peternakan",jam:"Setiap hari 06.00–17.00",tarif:"Harga pasar lokal",catatan:"Beli jagung, dedak, kapur dari kios lokal — jauh lebih murah dari distributor besar untuk skala kecil",aktif:true},

  // ══════════════════════════════════════════════════
  //  🐄 SAPI — RANTAI BISNIS KHUSUS
  // ══════════════════════════════════════════════════
  {id:"KT096",kategori:"Bisnis Sapi",nama:"Pasar Hewan Ciakar Tasikmalaya",hp:"0265-331606",hp2:"",alamat:"Pasar Hewan Ciakar, Kec. Kawalu, Kota Tasikmalaya",wilayah:"Tasikmalaya & Priangan Timur",spesialisasi:"Jual beli sapi potong & domba lokal, bakalan, afkir — hari pasar Senin & Kamis",jam:"Senin & Kamis 05.00–12.00 (pasar hewan)",tarif:"Harga pasar — bisa tawar",catatan:"Pasar hewan terbesar di Tasikmalaya — beli bakalan & jual sapi siap potong langsung ke bandar",aktif:true},
  {id:"KT097",kategori:"Bisnis Sapi",nama:"Pasar Hewan Sindangkasih Ciamis",hp:"0265-771024",hp2:"",alamat:"Sindangkasih, Kab. Ciamis, Jawa Barat",wilayah:"Ciamis & sekitar",spesialisasi:"Sapi potong, domba lokal, kambing — pasar hewan utama Ciamis",jam:"Rabu & Sabtu 05.00–11.00",tarif:"Harga pasar Ciamis",catatan:"Pasar hewan aktif area Ciamis — cek kondisi kesehatan hewan sebelum beli",aktif:true},
  {id:"KT098",kategori:"Bisnis Sapi",nama:"Abattoir / RPH Kota Tasikmalaya",hp:"0265-331574",hp2:"",alamat:"Jl. Wiratanuningrat No.1, Empangsari, Tawang, Tasikmalaya",wilayah:"Kota Tasikmalaya",spesialisasi:"Pemotongan sapi & domba bersertifikat halal, daging segar ke pasar lokal",jam:"Senin–Sabtu 04.00–10.00",tarif:"Biaya potong Rp 100.000–250.000/ekor",catatan:"RPH resmi kota — syarat: surat keterangan sehat hewan dari drh/mantri",aktif:true},
  {id:"KT099",kategori:"Bisnis Sapi",nama:"Kemitraan Sapi Kurban — Masjid & Ponpes Besar",hp:"0811-100-1344",hp2:"",alamat:"Pondok Pesantren & Masjid besar Tasikmalaya–Ciamis",wilayah:"Tasikmalaya & Ciamis",spesialisasi:"Pemesanan sapi kurban Idul Adha, aqiqah kolektif, paket daging qurban",jam:"Open order mulai Rajab (3 bulan sebelum Dzulhijjah)",tarif:"Harga sapi kurban Rp 15–45 jt/ekor (2025)",catatan:"Bangun relasi dengan takmir masjid & pondok pesantren — channel penjualan kurban TERSTABIL tiap tahun",aktif:true},
  {id:"KT100",kategori:"Bisnis Sapi",nama:"PT Gresik Cipta Sejahtera (GCS Feedmix)",hp:"031-3972-200",hp2:"",alamat:"Jl. Gubernur Suryo No.7, Gresik, Jawa Timur",wilayah:"Jawa Timur & nasional",spesialisasi:"Konsentrat sapi penggemukan & laktasi, pakan feedlot, mineral blok sapi",jam:"Senin–Sabtu 08.00–16.00",tarif:"Harga grosir — per ton",catatan:"Salah satu produsen konsentrat sapi terbesar di Jawa — referensi formula penggemukan intensif",aktif:true},

  // ══════════════════════════════════════════════════
  //  🐑 DOMBA — RANTAI BISNIS KHUSUS
  // ══════════════════════════════════════════════════
  {id:"KT101",kategori:"Bisnis Domba",nama:"Pasar Domba Wanaraja Garut",hp:"0262-233-446",hp2:"",alamat:"Pasar Hewan Wanaraja, Kab. Garut, Jawa Barat",wilayah:"Priangan — pusat domba Garut nasional",spesialisasi:"Domba Garut bibit & potong, domba show/kontes, domba kurban premium",jam:"Rabu & Minggu 05.00–12.00",tarif:"Rp 1,5 jt–20 jt/ekor tergantung kelas",catatan:"PUSAT DOMBA GARUT TERBESAR — wajib kunjungi untuk harga referensi & jaringan pembeli domba nasional",aktif:true},
  {id:"KT102",kategori:"Bisnis Domba",nama:"Kontes Domba Garut Tingkat Provinsi (HPDKI Jabar)",hp:"022-2030-8588",hp2:"",alamat:"Diselenggarakan bergantian tiap kabupaten",wilayah:"Jawa Barat",spesialisasi:"Kontes domba Garut show class, breeding registry, penentuan harga bibit unggul",jam:"Setahun 2–3 kali",tarif:"Biaya pendaftaran kontes",catatan:"Ikut kontes = nilai jual domba naik 3–10× — investasi terbaik untuk peternak domba Garut",aktif:true},
  {id:"KT103",kategori:"Bisnis Domba",nama:"PT Agro Nusa Abadi — Domba Impor & Wool",hp:"021-5835-4040",hp2:"",alamat:"Jl. Lodan Raya No.2, Jakarta Utara 14430",wilayah:"Seluruh Indonesia",spesialisasi:"Impor domba Merino Australia, domba Dorper, domba Suffolk — bibit unggul",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga impor — per ekor",catatan:"Untuk upgrade genetik domba lokal dengan darah Merino/Dorper — tingkatkan kualitas wool & daging",aktif:true},
  {id:"KT104",kategori:"Bisnis Domba",nama:"Agen Domba Kurban Online — Tokopedia/Shopee",hp:"1500-920",hp2:"",alamat:"Platform: tokopedia.com | shopee.co.id | lazada.co.id",wilayah:"Seluruh Indonesia",spesialisasi:"Jual domba/kambing kurban via marketplace, foto konten, layanan antar ke pembeli",jam:"24 jam",tarif:"Komisi marketplace 1–5%",catatan:"Buka toko domba kurban di marketplace H-90 Idul Adha — pasar digital kurban terus tumbuh tiap tahun",aktif:true},

  // ══════════════════════════════════════════════════
  //  🥚 LAYER — RANTAI BISNIS KHUSUS
  // ══════════════════════════════════════════════════
  {id:"KT105",kategori:"Bisnis Layer",nama:"PINSAR Petelur Nasional (Asosiasi Peternak Layer)",hp:"021-4788-1149",hp2:"08121346780",hp2:"",alamat:"Jl. Pemuda No.25, Jakarta Timur 13220",wilayah:"Seluruh Indonesia",spesialisasi:"Harga telur referensi nasional, advocacy kebijakan layer, networking peternak telur",jam:"Senin–Jumat 09.00–16.00",tarif:"Iuran anggota",catatan:"Pantau harga telur acuan PINSAR setiap minggu — mencegah rugi jual di bawah HPP",aktif:true},
  {id:"KT106",kategori:"Bisnis Layer",nama:"Pengepul Telur — Pasar Induk Cikurubuk Tasikmalaya",hp:"0265-334455",hp2:"",alamat:"Pasar Induk Cikurubuk, Kota Tasikmalaya",wilayah:"Tasikmalaya & Priangan Timur",spesialisasi:"Pengepul telur ayam ras, distribusi ke pasar tradisional, minimarket, katering",jam:"Setiap hari 04.00–12.00",tarif:"Harga pengepul = harga referensi – Rp 200–500/butir",catatan:"Bangun relasi langsung dengan pengepul besar di Cikurubuk untuk menjamin serapan telur mingguan",aktif:true},
  {id:"KT107",kategori:"Bisnis Layer",nama:"PT Japfa Comfeed — Kemitraan Layer (JALI)",hp:"021-2854-5680",hp2:"",alamat:"Wisma Millenia Lt.7, Jakarta — Divisi Kemitraan Layer",wilayah:"Seluruh Indonesia",spesialisasi:"Program JALI (Japfa Ayam Layer Indonesia) — suplai DOC+pakan+obat, beli hasil telur",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga kemitraan — lebih stabil dari pasar bebas",catatan:"Program kemitraan closed loop — Japfa suplai input & beli output telur. Cocok untuk peternak baru layer",aktif:true},
  {id:"KT108",kategori:"Bisnis Layer",nama:"DOC Layer Lohmann Brown — via PT Malindo Feedmill",hp:"021-7661727",hp2:"",alamat:"Via distributor DOC layer resmi Lohmann Brown di Indonesia",wilayah:"Seluruh Indonesia",spesialisasi:"DOC Layer Lohmann Brown Classic & Silver — strain terbaik untuk HDP & kualitas telur",jam:"Hubungi via distributor Malindo atau Japfa",tarif:"Harga DOC layer Rp 8.000–12.000/ekor",catatan:"Lohmann Brown = strain layer #1 dunia — minta garansi produksi HDP >90% dari distributor resmi",aktif:true},

  // ══════════════════════════════════════════════════
  //  🐔 BROILER — RANTAI BISNIS KHUSUS
  // ══════════════════════════════════════════════════
  {id:"KT109",kategori:"Bisnis Broiler",nama:"PINSAR Indonesia (Asosiasi Peternak Broiler)",hp:"021-7884-5410",hp2:"08121346780",hp2:"",alamat:"Jl. RP Soeroso No.40, Menteng, Jakarta Pusat 10350",wilayah:"Seluruh Indonesia",spesialisasi:"Harga ayam hidup referensi mingguan, advokasi kebijakan broiler, program kemitraan",jam:"Senin–Jumat 09.00–16.00",tarif:"Iuran anggota",catatan:"Pantau harga ayam hidup mingguan PINSAR — jangan jual di bawah BEP yang diumumkan PINSAR",aktif:true},
  {id:"KT110",kategori:"Bisnis Broiler",nama:"PT Charoen Pokphand — Kemitraan Broiler (CPMS)",hp:"021-6919999",hp2:"",alamat:"Jl. Ancol VIII/1, Jakarta Utara 14430 — Divisi Kemitraan",wilayah:"Seluruh Indonesia",spesialisasi:"Program kemitraan CPMS/Makmur — suplai DOC+pakan+obat+teknis, beli hasil panen",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga kontrak kemitraan — fee manajemen + margin",catatan:"CP paling banyak peternak kemitraan broiler di Indonesia — cocok untuk pemula & modal terbatas",aktif:true},
  {id:"KT111",kategori:"Bisnis Broiler",nama:"Jagal / Pengepul Ayam Hidup Tasikmalaya",hp:"0265-335669",hp2:"",alamat:"Pasar unggas & jagal kota Tasikmalaya",wilayah:"Tasikmalaya & Ciamis",spesialisasi:"Beli ayam broiler hidup langsung dari kandang, distribusi ke pasar & restoran",jam:"Setiap hari 03.00–09.00 (pengambilan pagi)",tarif:"Harga ayam hidup = harga PINSAR ± kondisi pasar lokal",catatan:"Bangun relasi dengan min. 3 jagal berbeda agar ada opsi jual saat harga turun — jangan tergantung 1 jagal",aktif:true},
  {id:"KT112",kategori:"Bisnis Broiler",nama:"PT Ciomas Adisatwa (Japfa RPA) Bogor",hp:"0251-8611392",hp2:"",alamat:"Jl. Raya Parung Bogor KM.24 Gg. Sawo No.25, Kemang, Bogor 16310",wilayah:"Jawa Barat & Jabodetabek",spesialisasi:"RPA bersertifikat halal, potong & olah broiler batch, cold chain distribusi ke supermarket",jam:"Senin–Sabtu 07.00–17.00",tarif:"Biaya potong per ekor — hubungi sales",catatan:"Untuk peternak broiler yang ingin jual dalam bentuk karkas/potongan ke retail — nilai jual lebih tinggi",aktif:true},

  // ══════════════════════════════════════════════════
  //  📱 DIGITAL & TEKNOLOGI PETERNAKAN
  // ══════════════════════════════════════════════════
  {id:"KT113",kategori:"Digital & Teknologi",nama:"LandX / iGrow — Investasi & Crowdfunding Peternakan",hp:"021-5010-0818",hp2:"",alamat:"Equity Tower Lt.35, SCBD, Jakarta Selatan",wilayah:"Seluruh Indonesia",spesialisasi:"Platform crowdfunding peternakan, investor ritel beli sapi/domba online, return 15–25%/tahun",jam:"24 jam via app",tarif:"Komisi platform",catatan:"Bisa himpun modal dari investor untuk ekspansi kandang — akses di igrow.asia atau landx.id",aktif:true},
  {id:"KT114",kategori:"Digital & Teknologi",nama:"Ternakita.id — Marketplace Ternak Online",hp:"081215778768",hp2:"",alamat:"ternakita.id — platform digital",wilayah:"Seluruh Indonesia",spesialisasi:"Jual beli sapi, domba, kambing, ayam online — koneksi langsung peternak ke pembeli",jam:"24 jam",tarif:"Gratis listing / komisi transaksi",catatan:"Daftar sekarang — upload foto hewan, deskripsi, harga. Pembeli dari seluruh Indonesia bisa lihat",aktif:true},
  {id:"KT115",kategori:"Digital & Teknologi",nama:"SiagaTernak / SIMPONI PKH — Sistem Digital Kementan",hp:"021-7815380",hp2:"",alamat:"Aplikasi: play.google.com/store — cari SIMPONI PKH",wilayah:"Seluruh Indonesia",spesialisasi:"Pencatatan ternak digital pemerintah, SINI (Sistem Informasi Nasional IB), data populasi",jam:"24 jam",tarif:"Gratis",catatan:"Daftar di SIMPONI PKH untuk mendapat akses data nasional & program bantuan ternak pemerintah",aktif:true},

  // ══════════════════════════════════════════════════
  //  💼 PERIZINAN & LEGALITAS USAHA
  // ══════════════════════════════════════════════════
  {id:"KT116",kategori:"Perizinan & Legalitas",nama:"OSS (Online Single Submission) — Izin Usaha",hp:"1500-164",hp2:"",alamat:"oss.go.id — BKPM / Kementerian Investasi",wilayah:"Seluruh Indonesia",spesialisasi:"NIB (Nomor Induk Berusaha), izin usaha peternakan, SIUP, sertifikasi halal, izin lingkungan",jam:"24 jam (online) / Call center jam kerja",tarif:"Gratis",catatan:"WAJIB urus NIB sebelum expand — syarat utama akses KUR bank, mitra perusahaan besar, & kontrak ekspor",aktif:true},
  {id:"KT117",kategori:"Perizinan & Legalitas",nama:"MUI Jawa Barat — Sertifikasi Halal Produk Ternak",hp:"022-7272-588",hp2:"",alamat:"Jl. Terusan Galunggung No.4, Bandung 40264",wilayah:"Jawa Barat",spesialisasi:"Sertifikat halal MUI untuk RPH, produk daging olahan, susu, telur, pakan ternak",jam:"Senin–Jumat 08.00–16.00",tarif:"Tarif sertifikasi halal sesuai jenis produk",catatan:"Sertifikat halal WAJIB untuk masuk retail modern, ekspor, & supply ke horeca besar",aktif:true},
  {id:"KT118",kategori:"Perizinan & Legalitas",nama:"BPOM — Registrasi Produk Olahan Ternak",hp:"1500-533",hp2:"021-4244-6918",alamat:"Jl. Percetakan Negara No.23, Jakarta Pusat 10560",wilayah:"Seluruh Indonesia",spesialisasi:"Izin edar produk pangan olahan ternak (susu UHT, telur asin, daging olahan, bakso, sosis)",jam:"Senin–Jumat 08.00–15.30",tarif:"Tarif registrasi sesuai jenis produk",catatan:"Nomor BPOM = WAJIB untuk jual produk olahan ternak di minimarket, online marketplace, & ekspor",aktif:true},
  // ══════════════════════════════════════════════════
  //  🔪 RPH / RPA / RPHU — Rumah Potong Resmi
  // ══════════════════════════════════════════════════
  {id:"KT119",kategori:"RPH & RPA",nama:"Perumda Dharma Jaya — RPH Sapi Jakarta (Cakung)",hp:"021-4609193",hp2:"commercial@dharmajaya.co.id",alamat:"Jl. Raya Penggilingan No.25, Cakung, Jakarta Timur 13940",wilayah:"DKI Jakarta & Jabodetabek",spesialisasi:"RPH Sapi & Kerbau 200 ekor/hari, RPH Domba/Kambing 400 ekor/hari, Cold Storage, Distribusi Daging Karkas Halal",jam:"Senin–Sabtu 04.00–16.00",tarif:"Tarif potong Rp 100.000–250.000/ekor — hubungi komersial",catatan:"BUMD DKI Jakarta — berdiri 1966. Email komersial: commercial@dharmajaya.co.id | Web: dharmajaya.co.id",aktif:true},
  {id:"KT120",kategori:"RPH & RPA",nama:"PT RPH Surabaya Perseroda (RPH Pegirian)",hp:"082131343888",hp2:"031-3712000",alamat:"Jl. Pegirian No.258, Sidotopo, Semampir, Surabaya 60151",wilayah:"Jawa Timur & Indonesia Timur",spesialisasi:"RPH Sapi, Kerbau, Babi — standar NKV & Halal MUI, distribusi daging segar ke pasar Surabaya & sekitar",jam:"Senin–Jumat 06.00–16.00 | Sabtu 06.00–12.00",tarif:"Tarif RPH sesuai Perda Surabaya",catatan:"IG: @rph_surabaya | Web: rphsurabaya.co.id | RPHU Jeruk (unggas) diresmikan Agustus 2025 — pertama di Surabaya",aktif:true},
  {id:"KT121",kategori:"RPH & RPA",nama:"RPH Kota Tasikmalaya (Abattoir Daerah)",hp:"0265-331574",hp2:"",alamat:"Jl. Wiratanuningrat No.1, Empangsari, Tawang, Kota Tasikmalaya",wilayah:"Kota Tasikmalaya & sekitar",spesialisasi:"Pemotongan Sapi & Domba bersertifikat Halal — distribusi ke pasar tradisional Tasikmalaya",jam:"Senin–Sabtu 04.00–10.00",tarif:"Biaya potong Rp 100.000–200.000/ekor sapi | Rp 30.000–50.000/ekor domba",catatan:"Syarat masuk: surat keterangan sehat hewan dari drh/mantri. Daging berlabel ASUH (Aman Sehat Utuh Halal)",aktif:true},
  {id:"KT122",kategori:"RPH & RPA",nama:"PT Ciomas Adisatwa — RPA Broiler (Japfa)",hp:"0251-8611392",hp2:"",alamat:"Jl. Raya Parung Bogor Km.24 Gg. Sawo No.25, Kemang, Bogor 16310",wilayah:"Jawa Barat & Jabodetabek",spesialisasi:"RPA Broiler bersertifikat Halal & NKV, Cold Chain, Distribusi karkas/potongan ayam ke supermarket & horeca",jam:"Senin–Sabtu 07.00–17.00",tarif:"Biaya potong per ekor — hubungi sales",catatan:"Anak perusahaan PT Japfa Comfeed Indonesia — standar ekspor. Untuk peternak broiler yang ingin jual karkas premium",aktif:true},
  {id:"KT123",kategori:"RPH & RPA",nama:"RPHU Kapuk (Ayam & Unggas) Jakarta Barat",hp:"021-5400121",hp2:"",alamat:"Jl. Rawa Bokor, Kapuk, Cengkareng, Jakarta Barat",wilayah:"DKI Jakarta & sekitar",spesialisasi:"Pemotongan unggas (ayam broiler/layer afkir/buras), bersertifikat NKV & Halal MUI",jam:"Setiap hari 02.00–10.00",tarif:"Rp 3.000–5.000/ekor ayam",catatan:"RPHU paling aktif di Jakarta Barat — distribusi ke pasar tradisional DKI. Hubungi untuk kapasitas potong batch besar",aktif:true},
  {id:"KT124",kategori:"RPH & RPA",nama:"Pusvetma — Balai Besar Veteriner Farma Surabaya",hp:"031-8291124",hp2:"082134449266",alamat:"Jl. Ahmad Yani 68-70, Surabaya 60231, Jawa Timur",wilayah:"Jawa Timur & Indonesia Timur",spesialisasi:"Produksi & distribusi vaksin hewan, diagnosa penyakit lab, obat hewan pemerintah bersubsidi",jam:"Senin–Jumat 07.30–15.30",tarif:"Tarif PMK Kementerian Pertanian",catatan:"HP Pengaduan: 0813-8648-5599 | Kontak penting untuk vaksin bersubsidi (AI, PMK, Anthrax) untuk peternak rakyat",aktif:true},

  // ══════════════════════════════════════════════════
  //  🏢 PERUSAHAAN REKANAN — Obat & Vaksin Hewan
  // ══════════════════════════════════════════════════
  {id:"KT125",kategori:"Obat & Vaksin Hewan",nama:"PT Medion Farma Jaya — Kantor Pusat Bandung",hp:"022-6866090",hp2:"022-6866094",alamat:"Jl. Raya Batujajar No.29, Cimareme, Ngamprah, Bandung Barat 40552",wilayah:"Seluruh Indonesia — Produsen vaksin & obat hewan terbesar lokal",spesialisasi:"Vaksin Medivac (ND, AI, IB, Gumboro, Marek's), Obat Hewan, Premix Mediherba, Desinfektan, Lab Diagnosa",jam:"Senin–Jumat 08.00–16.00",tarif:"Via distributor & apotek hewan resmi",catatan:"Berdiri 1976 di Bandung. Ekspor ke 20+ negara. IG: @medionfarma | Web: medionfarma.co.id | Email: info@medionfarma.co.id",aktif:true},
  {id:"KT126",kategori:"Obat & Vaksin Hewan",nama:"PT Vaksindo Satwa Nusantara — Japfa Vaksin",hp:"021-7800939",hp2:"",alamat:"Jl. Raya Kemang Km.1, Kemang, Kabupaten Bogor, Jawa Barat",wilayah:"Seluruh Indonesia",spesialisasi:"Vaksin unggas (ND, AI, IB, Gumboro, EDS), vaksin sapi (PMK, Anthrax, Brucella, Jembrana), cold chain distribusi",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga distributor — tanya sales daerah atau apotek hewan",catatan:"Anak perusahaan Japfa Comfeed — produsen vaksin hewan terbesar Indonesia. Distribusi via Medion & apotek hewan",aktif:true},
  {id:"KT127",kategori:"Obat & Vaksin Hewan",nama:"MSD Animal Health (Intervet) Indonesia",hp:"021-2995-7000",hp2:"",alamat:"Gedung Millenium, Jl. MT Haryono Kav.16, Jakarta Selatan",wilayah:"Seluruh Indonesia",spesialisasi:"Vaksin Nobilis (ND/AI/IB/Gumboro), Bovilis (sapi PMK), Ivomec & Dectomax (antiparasit), Panacur (fenbendazole)",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor & apotek hewan resmi",catatan:"MSD = Merck Sharp & Dohme. Ivomec & Dectomax = standar internasional antiparasit sapi & domba",aktif:true},
  {id:"KT128",kategori:"Obat & Vaksin Hewan",nama:"Boehringer Ingelheim Indonesia — Hewan",hp:"021-2993-9700",hp2:"",alamat:"Jl. MT Haryono Kav.9-11, Jakarta Selatan 12810",wilayah:"Seluruh Indonesia",spesialisasi:"Metacam (meloxicam NSAID), Draxxin (tilmicosin pneumonia sapi), vaksin ND/AI unggas, Ingelvac",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor & drh resmi",catatan:"Metacam = NSAID terbaik sapi & domba. Draxxin = 1× injeksi pneumonia sapi. Web: ah.boehringer-ingelheim.com",aktif:true},

  // ══════════════════════════════════════════════════
  //  🌾 PERUSAHAAN REKANAN — Pakan & DOC Besar
  // ══════════════════════════════════════════════════
  {id:"KT129",kategori:"Penjual Pakan",nama:"PT Sido Agung Group — Kantor Pusat Jakarta",hp:"021-5300030",hp2:"",alamat:"Jl. AIP KS Tubun IIC No.30, Slipi, Palmerah, Jakarta Barat 11410",wilayah:"Jawa & Nasional — Pabrik di Cirebon (Jabar) & Magelang (Jateng)",spesialisasi:"Pakan Broiler & Layer, DOC Broiler, Kemitraan 6.500 peternak broiler aktif, Kapasitas >35.000 ton/bulan",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga pabrik — hubungi sales/kemitraan",catatan:"Berdiri 1982 oleh Liem Chien An (Magelang). Pabrik: PT Sido Agung Agro Prima (Cirebon) + PT Sido Agung Farm (Magelang). Web: sidoagunggroup.com",aktif:true},
  {id:"KT130",kategori:"Penjual Pakan",nama:"PT Agro Farma Nusantara (AFN) — Jabar",hp:"022-8732-0000",hp2:"",alamat:"Jl. Raya Padalarang, Kabupaten Bandung Barat, Jawa Barat",wilayah:"Jawa Barat & sekitar",spesialisasi:"Pakan ternak & unggas, sapronak, bahan baku pertanian, distribusi wilayah Jabar",jam:"Senin–Sabtu 08.00–16.00",tarif:"Harga distributor",catatan:"Anak perusahaan Boga Handal Indonesia (BohanFood). Website: agrofarmaka.com",aktif:true},
  {id:"KT131",kategori:"Penjual Pakan",nama:"PT Wonokoyo Feedmill — Kantor Pusat Surabaya",hp:"031-8292111",hp2:"031-8292112",alamat:"Jl. Sidotopo Wetan No.59, Surabaya, Jawa Timur",wilayah:"Jawa Timur & Nasional",spesialisasi:"Pakan Broiler Idaman BR-1/BR-2, Layer P-31/P-32/P-33, DOC Broiler Wonokoyo Super, Telur HE",jam:"Senin–Jumat 08.00–16.00",tarif:"Harga distributor — agen tersebar di Jatim, Jateng, Jabar",catatan:"Pemain besar ke-3 setelah CP & Japfa. Pabrik juga di Pasuruan & Blitar. Aktif di Tokopedia & Shopee resmi",aktif:true},
  {id:"KT132",kategori:"Penjual Pakan",nama:"PT East Hope Indonesia (New Hope) — Jakarta",hp:"021-2500-5888",hp2:"",alamat:"Jl. Letjend S. Parman Kav.91, Slipi, Jakarta Barat",wilayah:"Seluruh Indonesia",spesialisasi:"Pakan Broiler New Hope BR-1, Layer L-83/L-38-1, DOC Broiler & Layer — berbasis China",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga distributor daerah",catatan:"New Hope Group (Cina) masuk Indonesia 2000-an. Populer di Jateng, DIY, sebagian Jabar. Kualitas kompetitif vs CP/Japfa",aktif:true},
  {id:"KT133",kategori:"Penjual Pakan",nama:"PT Farmsco Feed Indonesia — Pakan Layer Premium",hp:"021-8388-6868",hp2:"",alamat:"Kawasan Industri MM2100, Bekasi, Jawa Barat",wilayah:"Jawa & Nasional",spesialisasi:"Pakan Layer Egg Max/Egg Pro/Egg Shell+, Broiler Hi-Pro Premium — merek Korea-Indonesia",jam:"Senin–Jumat 08.00–17.00",tarif:"Premium — hubungi agen Farmsco daerah",catatan:"Website: farmsco.co.id | Dipakai di farm layer besar Jabar & Jateng. Lini lengkap: Hi-Pre Starter s/d KO Super",aktif:true},

  // ══════════════════════════════════════════════════
  //  🧪 PERUSAHAAN REKANAN — Premix & Additive
  // ══════════════════════════════════════════════════
  {id:"KT134",kategori:"Premix & Additive",nama:"PT DSM Nutritional Products Indonesia",hp:"021-5790-5555",hp2:"",alamat:"Wisma BNI 46 Lt.28, Jl. Jend. Sudirman Kav.1, Jakarta",wilayah:"Seluruh Indonesia",spesialisasi:"Premix vitamin-mineral (Rovimix), Carotenoid Carophyll (pigmentor), Rovabio enzim, Crina antimicrobial",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor resmi",catatan:"DSM = perusahaan Belanda nutrisi global. Premix DSM = standar pabrik pakan besar CP, Japfa, Malindo. Web: dsm.com",aktif:true},
  {id:"KT135",kategori:"Premix & Additive",nama:"PT BASF Indonesia — Feed Additive",hp:"021-5296-2800",hp2:"",alamat:"Prudential Tower, Jl. Jend. Sudirman Kav.79, Jakarta 12910",wilayah:"Seluruh Indonesia",spesialisasi:"Enzim Natuphos (phytase), Natugrain (xylanase), DL-Methionine Alimet, vitamin E Lutavit",jam:"Senin–Jumat 08.00–17.00",tarif:"Via distributor",catatan:"BASF = perusahaan kimia Jerman. Phytase BASF dipakai hampir semua pabrik pakan besar Indonesia",aktif:true},
  {id:"KT136",kategori:"Premix & Additive",nama:"PT Evonik Indonesia — Asam Amino (MetAMINO)",hp:"021-2994-2800",hp2:"",alamat:"World Trade Center, Jl. Jend. Sudirman Kav.29-31, Jakarta",wilayah:"Seluruh Indonesia",spesialisasi:"DL-Methionine MetAMINO, L-Lysine Biolys, L-Threonine Aminopure — asam amino sintetis pakan unggas & sapi",jam:"Senin–Jumat 08.00–17.00",tarif:"Harga bulk distributor",catatan:"Evonik = perusahaan Jerman. MetAMINO & Biolys = standar industri pakan unggas. Supplier utama pabrik pakan nasional",aktif:true},
];

/* ================================================================
   PageKontak — Halaman Buku Kontak Ternak
================================================================ */
const PageKontak = () => {
  const AC = "#60a5fa";
  const [kontak, setKontak]     = useState(INIT_KONTAK);
  const [search, setSearch]     = useState("");
  const [filter, setFilter]     = useState("semua");
  const [modal, setModal]       = useState(false);
  const [editId, setEditId]     = useState(null);
  const [detail, setDetail]     = useState(null);

  const blank = {kategori:"Mantri Hewan",nama:"",hp:"",hp2:"",alamat:"",wilayah:"",spesialisasi:"",jam:"",tarif:"",catatan:"",aktif:true};
  const [form, setForm] = useState(blank);

  const kategoriList = ["Mantri Hewan","Dokter Hewan","Dinas Peternakan","Penjual Sapi","Penjual Domba","Penjual DOC/Ayam","Penjual Pakan","Darurat & Hotline","Perbankan & KUR","Asuransi & BPJS","Logistik & Transportasi","Pemasaran Digital","Breeding & Genetika","Riset & Nutrisi","Produksi & Pengolahan","Pemasaran Hilir","Sosial & Kemitraan","Laboratorium & THT","Pakan Hulu","Bisnis Sapi","Bisnis Domba","Bisnis Layer","Bisnis Broiler","Digital & Teknologi","Perizinan & Legalitas","RPH & RPA","Obat & Vaksin Hewan","Premix & Additive","Lainnya"];
  const katColor = {
    "Mantri Hewan":          "#f59e0b",
    "Dokter Hewan":          "#ec4899",
    "Dinas Peternakan":      "#3b82f6",
    "Penjual Sapi":          "#f5c842",
    "Penjual Domba":         "#a3e635",
    "Penjual DOC/Ayam":      "#e879f9",
    "Penjual Pakan":         "#f97316",
    "Darurat & Hotline":     "#ef4444",
    "Perbankan & KUR":       "#22c55e",
    "Asuransi & BPJS":       "#06b6d4",
    "Logistik & Transportasi":"#8b5cf6",
    "Pemasaran Digital":     "#f43f5e",
    "Breeding & Genetika":   "#a855f7",
    "Riset & Nutrisi":       "#10b981",
    "Produksi & Pengolahan": "#f59e0b",
    "Pemasaran Hilir":       "#0ea5e9",
    "Sosial & Kemitraan":    "#84cc16",
    "Laboratorium & THT":    "#e11d48",
    "Pakan Hulu":            "#65a30d",
    "Bisnis Sapi":           "#f5c842",
    "Bisnis Domba":          "#a3e635",
    "Bisnis Layer":          "#f59e0b",
    "Bisnis Broiler":        "#e879f9",
    "Digital & Teknologi":   "#38bdf8",
    "Perizinan & Legalitas": "#6366f1",
    "Lainnya":               "#9097a8",
    "RPH & RPA":             "#ef4444",
    "Obat & Vaksin Hewan":   "#ec4899",
    "Premix & Additive":     "#06b6d4",
  };
  const katEmoji = {
    "Mantri Hewan":"🩺","Dokter Hewan":"👨‍⚕️","Dinas Peternakan":"🏛️",
    "Penjual Sapi":"🐄","Penjual Domba":"🐑","Penjual DOC/Ayam":"🐔",
    "Penjual Pakan":"🌾","Darurat & Hotline":"🚨",
    "Perbankan & KUR":"🏦","Asuransi & BPJS":"🛡️",
    "Logistik & Transportasi":"🚛","Pemasaran Digital":"📱",
    "Breeding & Genetika":"🧬","Riset & Nutrisi":"🔬",
    "Produksi & Pengolahan":"🏭","Pemasaran Hilir":"🛒",
    "Sosial & Kemitraan":"🤝","Laboratorium & THT":"🧪",
    "Pakan Hulu":"🌽","Bisnis Sapi":"🐄","Bisnis Domba":"🐑",
    "Bisnis Layer":"🥚","Bisnis Broiler":"🍗",
    "Digital & Teknologi":"📲","Perizinan & Legalitas":"📜",
    "RPH & RPA":"🔪","Obat & Vaksin Hewan":"💊","Premix & Additive":"⚗️",
    "Lainnya":"📞",
  };

  const filtered = kontak.filter(k =>
    (filter === "semua" || k.kategori === filter) &&
    (k.nama.toLowerCase().includes(search.toLowerCase()) ||
     k.hp.includes(search) ||
     k.spesialisasi.toLowerCase().includes(search.toLowerCase()) ||
     k.wilayah.toLowerCase().includes(search.toLowerCase()))
  );

  const save = () => {
    if (!form.nama || !form.hp) return;
    if (editId) {
      setKontak(kontak.map(k => k.id === editId ? {...form, id:editId} : k));
    } else {
      const newId = "KT" + String(kontak.length + 1).padStart(3,"0");
      setKontak([...kontak, {...form, id:newId}]);
    }
    setModal(false); setEditId(null); setForm(blank);
  };
  const del = id => { if (window.confirm("Hapus kontak?")) setKontak(kontak.filter(k => k.id !== id)); };
  const openEdit = k => { setForm({...k}); setEditId(k.id); setModal(true); };
  const call = hp => { window.open("tel:"+hp.replace(/[^0-9+]/g,"")); };
  const wa   = hp => { window.open("https://wa.me/62"+hp.replace(/^0/,"").replace(/[^0-9]/g,"")); };

  // Group for summary
  const byKat = kategoriList.reduce((acc, k) => {
    acc[k] = kontak.filter(x => x.kategori === k).length;
    return acc;
  }, {});

  return (
    <div style={{display:"flex",flexDirection:"column",gap:14}}>

      {/* STAT CARDS */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(130px,1fr))",gap:10}}>
        {Object.entries(byKat).filter(([,v])=>v>0).map(([kat,n])=>{
          const col = katColor[kat]||"#9097a8";
          return (
            <div key={kat} onClick={()=>setFilter(kat===filter?"semua":kat)}
              style={{background:filter===kat?col+"18":"#0f1118",border:"1px solid "+(filter===kat?col+"50":C.border),borderRadius:12,padding:"12px 14px",cursor:"pointer",transition:"all 0.15s",position:"relative",overflow:"hidden"}}>
              <div style={{fontSize:16,marginBottom:4}}>{katEmoji[kat]||"📞"}</div>
              <div style={{color:col,fontWeight:800,fontSize:18}}>{n}</div>
              <div style={{fontSize:10,color:"#555a6a",fontWeight:700,marginTop:2,lineHeight:1.2}}>{kat}</div>
              <div style={{position:"absolute",bottom:0,left:0,right:0,height:2,background:"linear-gradient(90deg,"+col+",transparent)"}}/>
            </div>
          );
        })}
      </div>

      {/* SEARCH & FILTER */}
      <div style={{display:"flex",justifyContent:"space-between",flexWrap:"wrap",gap:8,alignItems:"center"}}>
        <div style={{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"}}>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="🔍 Cari nama, HP, spesialisasi, wilayah..."
            style={{background:"#13161f",border:"1px solid #252535",borderRadius:9,padding:"8px 14px",color:"#e2e4f0",fontSize:13,outline:"none",minWidth:260}}/>
          {filter!=="semua" && (
            <button onClick={()=>setFilter("semua")} style={{background:"#ef444415",border:"1px solid #ef444430",borderRadius:8,padding:"7px 12px",cursor:"pointer",color:"#ef4444",fontSize:12,fontWeight:700}}>
              ✕ {filter}
            </button>
          )}
        </div>
        <button onClick={()=>{setEditId(null);setForm(blank);setModal(true);}}
          style={{background:AC+"18",border:"1px solid "+AC+"30",borderRadius:9,padding:"8px 16px",cursor:"pointer",color:AC,fontWeight:700,fontSize:13,display:"flex",alignItems:"center",gap:6}}>
          ＋ Tambah Kontak
        </button>
      </div>

      {/* GRID KONTAK */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(300px,1fr))",gap:12}}>
        {filtered.length === 0 && (
          <div style={{gridColumn:"1/-1",textAlign:"center",padding:48,color:"#555a6a",fontSize:13}}>
            Tidak ada kontak ditemukan
          </div>
        )}
        {filtered.map(k => {
          const col = katColor[k.kategori]||"#9097a8";
          const isDetail = detail === k.id;
          return (
            <div key={k.id} style={{background:"#0f1118",border:"1px solid "+(isDetail?col+"40":"#1c1e2b"),borderRadius:14,padding:16,transition:"border 0.15s"}}>
              {/* Header */}
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:10}}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{display:"flex",alignItems:"center",gap:7,marginBottom:5,flexWrap:"wrap"}}>
                    <span style={{background:col+"18",color:col,border:"1px solid "+col+"30",borderRadius:20,padding:"2px 9px",fontSize:10,fontWeight:700,whiteSpace:"nowrap"}}>
                      {katEmoji[k.kategori]} {k.kategori}
                    </span>
                    {k.kategori==="Darurat & Hotline" && (
                      <span style={{background:"#ef444418",color:"#ef4444",border:"1px solid #ef444430",borderRadius:20,padding:"2px 7px",fontSize:9,fontWeight:700,animation:"pulse 1s infinite"}}>🚨 DARURAT</span>
                    )}
                  </div>
                  <div style={{color:"#e2e4f0",fontWeight:800,fontSize:15,marginBottom:2}}>{k.nama}</div>
                  <div style={{color:"#9097a8",fontSize:11}}>{k.wilayah}</div>
                </div>
                <div style={{display:"flex",gap:5,flexShrink:0}}>
                  <button onClick={()=>openEdit(k)} style={{background:"#3b82f614",border:"1px solid #3b82f622",borderRadius:7,padding:"5px 8px",cursor:"pointer",color:"#3b82f6",fontSize:11}}>✏️</button>
                  <button onClick={()=>del(k.id)} style={{background:"#ef444414",border:"1px solid #ef444422",borderRadius:7,padding:"5px 8px",cursor:"pointer",color:"#ef4444",fontSize:11}}>🗑️</button>
                </div>
              </div>

              {/* HP + Tombol */}
              <div style={{display:"flex",gap:8,marginBottom:10,flexWrap:"wrap"}}>
                <div style={{flex:1,background:"#ffffff06",borderRadius:9,padding:"8px 11px"}}>
                  <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>No. HP / Telp</div>
                  <div style={{color:col,fontWeight:800,fontSize:14,fontFamily:"'JetBrains Mono',monospace"}}>{k.hp}</div>
                  {k.hp2 && <div style={{color:"#9097a8",fontSize:11,marginTop:1}}>{k.hp2}</div>}
                </div>
                <div style={{display:"flex",flexDirection:"column",gap:5}}>
                  <button onClick={()=>call(k.hp)}
                    style={{background:"#22c55e18",border:"1px solid #22c55e30",borderRadius:8,padding:"7px 12px",cursor:"pointer",color:"#22c55e",fontWeight:700,fontSize:12,whiteSpace:"nowrap"}}>
                    📞 Telpon
                  </button>
                  <button onClick={()=>wa(k.hp)}
                    style={{background:"#22c55e18",border:"1px solid #22c55e30",borderRadius:8,padding:"7px 12px",cursor:"pointer",color:"#22c55e",fontWeight:700,fontSize:12,whiteSpace:"nowrap"}}>
                    💬 WhatsApp
                  </button>
                </div>
              </div>

              {/* Spesialisasi */}
              <div style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:8,padding:"7px 11px",marginBottom:8}}>
                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>Spesialisasi</div>
                <div style={{fontSize:12,color:"#e2e4f0"}}>{k.spesialisasi}</div>
              </div>

              {/* Toggle detail */}
              <button onClick={()=>setDetail(isDetail?null:k.id)}
                style={{width:"100%",background:"none",border:"1px solid #1c1e2b",borderRadius:8,padding:"6px",cursor:"pointer",color:"#555a6a",fontSize:11,marginBottom:isDetail?8:0}}>
                {isDetail?"▲ Sembunyikan":"▼ Lihat Detail"}
              </button>

              {isDetail && (
                <div style={{display:"flex",flexDirection:"column",gap:6,marginTop:4}}>
                  {[["📍 Alamat",k.alamat],["🕐 Jam Operasional",k.jam],["💰 Tarif",k.tarif],["📝 Catatan",k.catatan]].map(([lbl,val])=>
                    val ? (
                      <div key={lbl} style={{display:"flex",gap:8,alignItems:"flex-start"}}>
                        <span style={{fontSize:11,color:"#555a6a",minWidth:130,flexShrink:0}}>{lbl}</span>
                        <span style={{fontSize:12,color:"#9097a8",lineHeight:1.4}}>{val}</span>
                      </div>
                    ) : null
                  )}
                  {k.hp2 && (
                    <button onClick={()=>call(k.hp2)}
                      style={{background:"#3b82f615",border:"1px solid #3b82f625",borderRadius:8,padding:"7px",cursor:"pointer",color:"#3b82f6",fontWeight:700,fontSize:12}}>
                      📞 Telpon No.2: {k.hp2}
                    </button>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* MODAL TAMBAH/EDIT */}
      {modal && (
        <Modal title={editId?"Edit Kontak":"Tambah Kontak Baru"} onClose={()=>{setModal(false);setEditId(null);}}>
          <div style={S.grid2}>
            <div style={{gridColumn:"1/-1"}}>
              <label style={S.label}>Kategori</label>
              <select value={form.kategori} onChange={e=>setForm({...form,kategori:e.target.value})} style={S.select}>
                {kategoriList.map(k=><option key={k} value={k}>{katEmoji[k]} {k}</option>)}
              </select>
            </div>
            <div style={{gridColumn:"1/-1"}}>
              <label style={S.label}>Nama Lengkap *</label>
              <input value={form.nama} onChange={e=>setForm({...form,nama:e.target.value})} placeholder="drh. Nama / Pak Nama / Toko ..."
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>No. HP / WA * (utama)</label>
              <input value={form.hp} onChange={e=>setForm({...form,hp:e.target.value})} placeholder="08xxxxxxxxxx"
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>No. Telepon / HP 2 (opsional)</label>
              <input value={form.hp2} onChange={e=>setForm({...form,hp2:e.target.value})} placeholder="Telp kantor / alternatif"
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div style={{gridColumn:"1/-1"}}>
              <label style={S.label}>Spesialisasi / Layanan</label>
              <input value={form.spesialisasi} onChange={e=>setForm({...form,spesialisasi:e.target.value})} placeholder="Sapi Potong, Vaksin, Pakan Layer..."
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>Wilayah Layanan</label>
              <input value={form.wilayah} onChange={e=>setForm({...form,wilayah:e.target.value})} placeholder="Kec. / Kab. ..."
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>Jam Operasional</label>
              <input value={form.jam} onChange={e=>setForm({...form,jam:e.target.value})} placeholder="07.00–17.00 Senin–Sabtu"
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div style={{gridColumn:"1/-1"}}>
              <label style={S.label}>Alamat</label>
              <input value={form.alamat} onChange={e=>setForm({...form,alamat:e.target.value})} placeholder="Jl. ..."
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>Tarif / Harga</label>
              <input value={form.tarif} onChange={e=>setForm({...form,tarif:e.target.value})} placeholder="Rp 50.000/kunjungan"
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
            <div>
              <label style={S.label}>Catatan Tambahan</label>
              <input value={form.catatan} onChange={e=>setForm({...form,catatan:e.target.value})} placeholder="Info penting..."
                style={{...S.select,width:"100%",boxSizing:"border-box"}}/>
            </div>
          </div>
          <BtnPrimary onClick={save} color={AC} full disabled={!form.nama||!form.hp}>Simpan Kontak</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

const PageRPH = ({ records=[], setRecords, cattle=[] }) => {
  const AC = "#ef4444";
  const [tab, setTab]         = useState("kalkulator");
  const [form, setF0]         = useState(null);
  const [preview, setPreview] = useState(null);
  const [activeId, setActiveId] = useState(null);
  const [subTab, setSubTab]     = useState("ilmiah");

  const blankRPH = {
    sapiId:"", sapiNama:"", breed:"Simental", gender:"Jantan",
    bbHidup:"", hargaBeli:"", tglPotong:new Date().toISOString().split("T")[0],
    pctKarkas:55, status:"Selesai", buyer:"", notes:"",
    hJualHasDalam:220000, hJualHasLuar:195000, hJualTanjung:180000,
    hJualGandik:158000,   hJualLamusir:155000, hJualSengkel:153000,
    hJualSandung:148000,  hJualPahaD:148000,   hJualPahaB:160000,
    hJualIga:165000,      hJualPunuk:148000,   hJualLeher:138000,
    hJualEkor:172000,     hJualTulang:25000,
    bRetribusi:300000, bUpah:425000, bListrik:90000,
    bKemasan:70000,    bTransport:375000, bLainnya:140000,
    aKarkas:"", aTulang:"",
    aHasDalam:"", aHasLuar:"", aTanjung:"", aGandik:"",
    aLamusir:"", aSengkel:"", aSandung:"", aPahaD:"",
    aPahaB:"", aIga:"", aPunuk:"", aLeher:"", aEkor:"",
    aHati:"", aParu:"", aJantung:"", aGinjal:"",
    aLimpa:"", aOtak:"", aLidah:"", aBabat:"",
    aUsusB:"", aUsusH:"", aKepala:"", aKikil:"",
    aKulit:"", aDarah:"", aTetelan:"",
    aFeses:"", aRumen:"",
  };

  // Init form
  const f = form || blankRPH;
  const setF = patch => {
    const nf = { ...f, ...patch };
    setF0(nf);
    setPreview(hitungRPH(nf));
  };

  const saveRecord = () => {
    if (!f.bbHidup || !f.hargaBeli) return;
    const sapi = cattle.find(c => c.id === f.sapiId);
    const id = "RPH" + String(records.length + 1).padStart(3, "0");
    setRecords([{ id, ...f, bbHidup: +f.bbHidup, hargaBeli: +f.hargaBeli, pctKarkas: +f.pctKarkas, sapiNama: sapi ? sapi.name : f.sapiNama }, ...records]);
    setF0(null); setPreview(null);
  };

  // Cetak laporan — pakai string concat bukan template literal nested
  const cetakLaporan = (rec, c) => {
    const rp = n => "Rp " + new Intl.NumberFormat("id-ID").format(Math.round(n || 0));
    const pctBH = (v) => (+(v / c.bb * 100).toFixed(2)) + "%";
    const badgeA = (isAkt) => isAkt
      ? '<span class="badge-a">Aktual</span>'
      : '<span class="badge-e">Estimasi</span>';
    const gradeSpan = (g) => {
      const cls = g === "Premium" ? "gprem" : g === "Superior" ? "gsup" : "gstd";
      return '<span class="' + cls + '">' + g + '</span>';
    };
    const katSpan = (k) => '<span class="kat">' + (k || "—") + '</span>';

    const rowsPotongan = c.potongan.map((p, i) =>
      "<tr><td>" + (i + 1) + "</td><td><b>" + p.nama + "</b></td><td>" + gradeSpan(p.grade) + "</td><td><b>" + p.beratKg + " kg</b></td><td>" + pctBH(p.beratKg) + "</td><td>" + rp(p.harga) + "</td><td class='green'>" + rp(p.pend) + "</td><td>" + badgeA(p.aktual) + "</td></tr>"
    ).join("");

    const rowsByP = c.byProducts.map(b =>
      "<tr><td><b>" + b.nama + "</b></td><td>" + katSpan(b.kat) + "</td><td>" + b.beratKg + " kg</td><td>" + pctBH(b.beratKg) + "</td><td>" + rp(b.harga) + "</td><td class='green'>" + rp(b.pend) + "</td><td>" + badgeA(b.aktual) + "</td></tr>"
    ).join("");

    const rowsNeraca = [
      ["Karkas", c.beratKarkas, !!rec.aKarkas, "Setelah kepala+kaki+kulit+jeroan dilepas"],
      ["— Daging", c.totalDaging, false, "13 potongan primer"],
      ["— Tulang", c.beratTulang, !!rec.aTulang, "Rangka axial + appendicular"],
      ["— Lemak/Trim", Math.max(0, c.beratSusut), false, "Lemak, jaringan ikat, drip loss"],
      ["Jeroan Edible", +c.byProducts.filter(b => b.kat !== "Kulit/Darah").reduce((s, b) => s + b.beratKg, 0).toFixed(1), false, "Organ + fancy meat edible"],
      ["Kulit + Darah", +c.byProducts.filter(b => b.kat === "Kulit/Darah").reduce((s, b) => s + b.beratKg, 0).toFixed(1), false, "Kulit segar + darah"],
      ["Isi Rumen+Usus", c.bRumen, !!rec.aRumen, "Digesta / pakan belum tercerna"],
      ["Feses & Urin", c.bFeses, !!rec.aFeses, "Kotoran saat pemotongan (~4% BH)"],
    ].map(([nm, brt, akt, ket]) =>
      "<tr><td><b>" + nm + "</b></td><td>" + brt + " kg</td><td>" + pctBH(brt) + "</td><td>" + badgeA(akt) + "</td><td>" + ket + "</td></tr>"
    ).join("");

    const rowsBiaya = [
      ["Harga Beli Sapi", rp(c.hBeli)], ["Retribusi RPH", rp(c.biaya.retribusi)],
      ["Upah Potong", rp(c.biaya.upah)], ["Listrik & Air", rp(c.biaya.listrik)],
      ["Kemasan", rp(c.biaya.kemasan)], ["Transportasi", rp(c.biaya.transport)],
      ["Lainnya", rp(c.biaya.lainnya)], ["TOTAL BIAYA", rp(c.totalBiaya)],
    ].map(([k, v]) => "<div class='r'><span>" + k + "</span><span class='red'>" + v + "</span></div>").join("");

    const rowsPend = [
      ["Daging", rp(c.pendDaging)], ["Tulang", rp(c.pendTulang)],
      ["Jeroan & By-Product", rp(c.pendByP)], ["TOTAL PENDAPATAN", rp(c.pendTotal)],
      ["PROFIT BERSIH", rp(c.profit)], ["ROI", c.roi + "%"],
      ["HPP Daging/kg", rp(c.hppPerKg) + "/kg"],
    ].map(([k, v]) => "<div class='r'><span>" + k + "</span><span class='green'>" + v + "</span></div>").join("");

    const infoCards = [
      ["Nama Sapi", rec.sapiNama || "—"], ["Ras", rec.breed], ["JK", rec.gender],
      ["Bobot Hidup", c.bb + " kg"], ["% Karkas", rec.pctKarkas + "%"],
      ["Berat Karkas", c.beratKarkas + " kg"], ["Tgl Potong", rec.tglPotong],
      ["Pembeli", rec.buyer || "—"],
    ].map(([k, v]) => "<div class='s'><div class='v'>" + v + "</div><div class='k'>" + k + "</div></div>").join("");

    const indikator = [
      ["Profit Bersih", rp(c.profit)], ["ROI", c.roi + "%"],
      ["HPP Daging/kg", rp(c.hppPerKg) + "/kg"], ["Total Pendapatan", rp(c.pendTotal)],
      ["DCP (Dressing)", c.pctKarkas + "%"], ["Meat-Bone Ratio", c.mbr + ":1"],
    ].map(([k, v]) => "<div class='ind'><div class='v'>" + v + "</div><div class='k'>" + k + "</div></div>").join("");

    const css = [
      "*{margin:0;padding:0;box-sizing:border-box}",
      "body{font-family:'Segoe UI',Arial,sans-serif;font-size:11px;color:#111;padding:14mm}",
      "h1{font-size:17px;font-weight:800;margin-bottom:3px}",
      "h2{font-size:12px;font-weight:700;color:#c0392b;margin:14px 0 6px;border-bottom:2px solid #c0392b;padding-bottom:2px}",
      ".meta{color:#666;font-size:10px;margin-bottom:10px}",
      ".hbox{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:10px 14px;margin-bottom:12px;display:flex;gap:24px;flex-wrap:wrap}",
      ".hbox .s{text-align:center}.hbox .v{font-size:16px;font-weight:800;color:#c0392b}.hbox .k{font-size:9px;color:#888;text-transform:uppercase}",
      "table{width:100%;border-collapse:collapse;margin-bottom:10px;font-size:10px}",
      "th{background:#222;color:#fff;padding:5px 8px;text-align:left;font-size:9px;text-transform:uppercase}",
      "td{padding:4px 8px;border-bottom:1px solid #eee}tr:nth-child(even)td{background:#fafafa}",
      ".tr{font-weight:700;background:#f0f0f0}",
      ".g2{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px}",
      ".card{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:8px 12px}",
      ".card .r{display:flex;justify-content:space-between;padding:3px 0;border-bottom:1px solid #eee;font-size:10px}",
      ".green{color:#1a7a1a;font-weight:700}.red{color:#c0392b;font-weight:700}",
      ".badge-a{background:#e8f8e8;color:#1a7a1a;border:1px solid #1a7a1a;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".badge-e{background:#fff8dc;color:#b8860b;border:1px solid #daa520;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".gprem{background:#fff8dc;color:#b8860b;border:1px solid #daa520;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".gsup{background:#e8f0ff;color:#1565c0;border:1px solid #1565c0;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".gstd{background:#f5f5f5;color:#555;border:1px solid #bbb;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".kat{background:#f0e6ff;color:#6c3483;border:1px solid #a569bd;border-radius:10px;padding:1px 5px;font-size:8px;font-weight:700}",
      ".ind-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:10px}",
      ".ind{background:#f5f5f5;border:1px solid #ddd;border-radius:5px;padding:7px 10px;text-align:center}",
      ".ind .v{font-size:14px;font-weight:800;color:#c0392b}.ind .k{font-size:8px;color:#888;text-transform:uppercase}",
      ".footer{margin-top:16px;padding-top:8px;border-top:1px solid #ddd;color:#999;font-size:9px;text-align:center}",
      "@media print{body{padding:8mm}@page{size:A4;margin:8mm}}",
    ].join("");

    const html = [
      "<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'/>",
      "<title>Laporan RPH - " + (rec.sapiNama || rec.id) + "</title>",
      "<style>" + css + "</style></head><body>",
      "<h1>Laporan Pemotongan Sapi RPH</h1>",
      "<p class='meta'>ID: " + rec.id + " | Dicetak: " + new Date().toLocaleString("id-ID") + " | Status: " + rec.status + "</p>",
      "<div class='hbox'>" + infoCards + "</div>",
      "<div class='ind-grid'>" + indikator + "</div>",
      "<h2>I. Neraca Bobot (BH = " + c.bb + " kg)</h2>",
      "<table><thead><tr><th>Komponen</th><th>Berat (kg)</th><th>% BH</th><th>Data</th><th>Keterangan</th></tr></thead>",
      "<tbody>" + rowsNeraca + "</tbody></table>",
      "<h2>II. Rincian Potongan Daging Primer</h2>",
      "<table><thead><tr><th>No</th><th>Potongan</th><th>Grade</th><th>Berat</th><th>% BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead>",
      "<tbody>" + rowsPotongan,
      "<tr class='tr'><td colspan='3'>TOTAL DAGING</td><td>" + c.totalDaging + " kg</td><td>" + pctBH(c.totalDaging) + "</td><td></td><td class='green'>" + rp(c.pendDaging) + "</td><td></td></tr>",
      "<tr><td colspan='3'>Tulang</td><td>" + c.beratTulang + " kg</td><td>" + pctBH(c.beratTulang) + "</td><td>" + rp(rec.hJualTulang || 25000) + "</td><td>" + rp(c.pendTulang) + "</td><td>" + badgeA(!!rec.aTulang) + "</td></tr>",
      "</tbody></table>",
      "<h2>III. Jeroan & By-Product</h2>",
      "<table><thead><tr><th>Produk</th><th>Kategori</th><th>Berat</th><th>% BH</th><th>Harga/kg</th><th>Nilai</th><th>Data</th></tr></thead>",
      "<tbody>" + rowsByP,
      "<tr><td>Isi Rumen+Usus</td><td>Non-Edible</td><td>" + c.bRumen + " kg</td><td>" + pctBH(c.bRumen) + "</td><td>-</td><td>-</td><td>" + badgeA(!!rec.aRumen) + "</td></tr>",
      "<tr><td>Feses & Urin</td><td>Limbah</td><td>" + c.bFeses + " kg</td><td>~4%</td><td>-</td><td>-</td><td>-</td></tr>",
      "<tr class='tr'><td colspan='2'>TOTAL BY-PRODUCT (edible)</td><td>" + c.byProducts.reduce((s, b) => +(s + b.beratKg).toFixed(2), 0) + " kg</td><td></td><td></td><td class='green'>" + rp(c.pendByP) + "</td><td></td></tr>",
      "</tbody></table>",
      "<div class='g2'><div class='card'><b>Rincian Biaya</b>" + rowsBiaya + "</div>",
      "<div class='card'><b>Rincian Pendapatan</b>" + rowsPend + "</div></div>",
      rec.notes ? "<p style='background:#f5f5f5;padding:8px 12px;border-radius:5px;border:1px solid #ddd;font-size:11px;margin-bottom:10px'><b>Catatan:</b> " + rec.notes + "</p>" : "",
      "<div class='footer'><b>TernakPro RPH</b> | " + rec.id + " | " + rec.tglPotong + " | Harga: PIHPS BI + Daging Semarang Jun 2026</div>",
      "<script>window.onload=function(){setTimeout(function(){window.print()},300)}</script>",
      "</body></html>",
    ].join("");

    const blob = new Blob([html], { type: "text/html" });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement("a");
    a.href = url; a.target = "_blank"; a.click();
    setTimeout(() => URL.revokeObjectURL(url), 5000);
  };

  // Reusable input
  const Inp = ({ label, value, onChange, type = "text", options, small, placeholder, hl }) => (
    <div>
      <label style={{ fontSize: 9, color: "#555a6a", fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, display: "block", marginBottom: 3 }}>{label}</label>
      {options ? (
        <select value={value || ""} onChange={e => onChange(e.target.value)} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 8, padding: small ? "5px 8px" : "8px 11px", color: "#e2e4f0", fontSize: small ? 11 : 13, width: "100%", outline: "none" }}>
          {options.map(o => <option key={o.v ?? o} value={o.v ?? o}>{o.l ?? o}</option>)}
        </select>
      ) : (
        <input type={type} value={value || ""} onChange={e => onChange(e.target.value)} placeholder={placeholder || ""} style={{ background: "#13161f", border: "1px solid " + (hl && value ? "#22c55e40" : "#252535"), borderRadius: 8, padding: small ? "5px 8px" : "8px 11px", color: "#e2e4f0", fontSize: small ? 11 : 13, width: "100%", outline: "none", boxSizing: "border-box" }} />
      )}
    </div>
  );

  // Mini bar chart
  const BarChart = ({ data, title, height = 110 }) => {
    const max = Math.max(...data.map(d => d.value || 0), 1);
    const W = 460; const bw = Math.floor((W - 16) / data.length) - 2;
    return (
      <div style={{ background: "#0a0c16", borderRadius: 10, padding: "10px 12px" }}>
        <div style={{ color: "#9097a8", fontSize: 10, fontWeight: 700, marginBottom: 6 }}>{title}</div>
        <svg width="100%" viewBox={"0 0 " + W + " " + (height + 38)} style={{ overflow: "visible" }}>
          {data.map((d, i) => {
            const bh = Math.max(2, (d.value / max) * height);
            const x = 8 + i * (bw + 2);
            const y = height - bh + 2;
            const col = d.color || "#22c55e";
            return (
              <g key={i}>
                <rect x={x} y={y} width={bw} height={bh} rx={2} fill={col} opacity={0.82} />
                {d.value > 0 && <text x={x + bw / 2} y={y - 2} textAnchor="middle" fill={col} fontSize={6} fontWeight="700">{d.label2 || ""}</text>}
                <text x={x + bw / 2} y={height + 20} textAnchor="middle" fill="#555a6a" fontSize={6.5} transform={"rotate(-38," + (x + bw / 2) + "," + (height + 20) + ")"}>
                  {d.label.length > 9 ? d.label.slice(0, 8) + "…" : d.label}
                </text>
              </g>
            );
          })}
          <line x1={8} y1={height + 2} x2={W - 8} y2={height + 2} stroke="#252535" strokeWidth={1} />
        </svg>
      </div>
    );
  };

  const gradeC = g => g === "Premium" ? "#f5c842" : g === "Superior" ? "#3b82f6" : "#9097a8";
  const thS = { padding: "8px 10px", color: "#555a6a", textAlign: "left", fontSize: 9, fontWeight: 800, textTransform: "uppercase", whiteSpace: "nowrap", borderBottom: "1px solid #1c1e2b" };
  const tdS = (col = "#e2e4f0", bold = false) => ({ padding: "8px 10px", color: col, fontWeight: bold ? 700 : 400, fontSize: 12 });
  const BadgeAkt = ({ isAkt }) => (
    <span style={{ background: isAkt ? "#22c55e18" : "#f5c84218", color: isAkt ? "#22c55e" : "#f5c842", border: "1px solid " + (isAkt ? "#22c55e30" : "#f5c84230"), borderRadius: 20, padding: "1px 7px", fontSize: 9, fontWeight: 700 }}>
      {isAkt ? "✅ Aktual" : "📊 Est."}
    </span>
  );

  // Summary stats
  const totalPend = records.reduce((s, r) => { const c = hitungRPH(r); return c ? s + c.pendTotal : s; }, 0);
  const totalProf = records.reduce((s, r) => { const c = hitungRPH(r); return c ? s + c.profit : s; }, 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* STAT CARDS */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
        {[
          ["Catatan Potong", records.length + " ekor", AC, "🔪"],
          ["Total Pendapatan", "Rp " + (totalPend / 1e6).toFixed(1) + "jt", "#3b82f6", "💰"],
          ["Total Profit", "Rp " + (totalProf / 1e6).toFixed(1) + "jt", totalProf >= 0 ? "#22c55e" : AC, "📊"],
          ["Sapi Siap Potong", cattle.filter(c => c.status === "Siap Jual").length + " ekor", "#f5c842", "🐄"],
        ].map(([l, v, c, e]) => (
          <div key={l} style={{ background: c + "0c", border: "1px solid " + c + "25", borderRadius: 13, padding: "15px 17px", position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", top: 10, right: 12, fontSize: 24, opacity: 0.12 }}>{e}</div>
            <div style={{ fontSize: 10, color: "#555a6a", textTransform: "uppercase", letterSpacing: 1.5, fontWeight: 700, marginBottom: 5 }}>{l}</div>
            <div style={{ fontSize: 19, fontWeight: 800, color: c }}>{v}</div>
            <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 2, background: "linear-gradient(90deg," + c + ",transparent)" }} />
          </div>
        ))}
      </div>

      {/* TABS */}
      <div style={{ display: "flex", borderBottom: "1px solid #1c1e2b" }}>
        {[{ id: "kalkulator", l: "🔢 Kalkulator" }, { id: "riwayat", l: "📋 Riwayat Pemotongan" }, { id: "standar", l: "📊 Tabel Standar" }].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{ background: "none", border: "none", borderBottom: "2px solid " + (tab === t.id ? AC : "transparent"), color: tab === t.id ? AC : "#555a6a", padding: "8px 18px", cursor: "pointer", fontWeight: 700, fontSize: 13, marginBottom: -1 }}>{t.l}</button>
        ))}
      </div>

      {/* ═══ TAB KALKULATOR ═══ */}
      {tab === "kalkulator" && (
        <div style={{ display: "grid", gridTemplateColumns: "370px 1fr", gap: 18, alignItems: "start" }}>
          {/* INPUT PANEL */}
          <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 14, padding: 18, display: "flex", flexDirection: "column", gap: 14, maxHeight: "88vh", overflowY: "auto" }}>
            <div style={{ color: AC, fontFamily: "'DM Serif Display',serif", fontSize: 15, fontWeight: 700 }}>🐄 Data Sapi</div>

            <div>
              <label style={{ fontSize: 9, color: "#555a6a", fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, display: "block", marginBottom: 4 }}>Pilih Sapi (opsional)</label>
              <select value={f.sapiId} onChange={e => {
                const s = cattle.find(c => c.id === e.target.value);
                const pct = s ? (RPH_STANDAR.persen_karkas[s.breed] || RPH_STANDAR.persen_karkas.default)[s.gender === "Jantan" ? "jantan" : "betina"] : f.pctKarkas;
                setF({ sapiId: e.target.value, sapiNama: s ? s.name : "", breed: s ? s.breed : f.breed, gender: s ? s.gender : f.gender, bbHidup: s ? s.weightCurrent : f.bbHidup, hargaBeli: s ? s.priceBuy : f.hargaBeli, pctKarkas: pct });
              }} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 8, padding: "8px 11px", color: "#e2e4f0", fontSize: 13, width: "100%" }}>
                <option value="">-- Pilih atau isi manual --</option>
                {cattle.map(c => <option key={c.id} value={c.id}>{c.name} ({c.breed}) — {c.weightCurrent}kg</option>)}
              </select>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <Inp label="Bobot Hidup (kg)" value={f.bbHidup} onChange={v => setF({ bbHidup: v })} type="number" />
              <Inp label="% Karkas" value={f.pctKarkas} onChange={v => setF({ pctKarkas: v })} type="number" />
              <Inp label="Ras" value={f.breed} onChange={v => setF({ breed: v })} options={["Simental","Limousin","PO","Bali","Brahman","FH Afkir"]} />
              <Inp label="Jenis Kelamin" value={f.gender} onChange={v => setF({ gender: v })} options={["Jantan","Betina"]} />
              <Inp label="Harga Beli (Rp)" value={f.hargaBeli} onChange={v => setF({ hargaBeli: v })} type="number" />
              <Inp label="Tanggal Potong" value={f.tglPotong} onChange={v => setF({ tglPotong: v })} type="date" />
              <Inp label="Pembeli" value={f.buyer} onChange={v => setF({ buyer: v })} />
              <Inp label="Status" value={f.status} onChange={v => setF({ status: v })} options={["Selesai","Proses","Antrian"]} />
            </div>

            {/* Biaya RPH */}
            <div style={{ borderTop: "1px solid #1c1e2b", paddingTop: 12 }}>
              <div style={{ color: "#f59e0b", fontFamily: "'DM Serif Display',serif", fontSize: 13, marginBottom: 10 }}>🏭 Biaya RPH</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[["Retribusi","bRetribusi"],["Upah Potong","bUpah"],["Listrik & Air","bListrik"],["Kemasan","bKemasan"],["Transportasi","bTransport"],["Lainnya","bLainnya"]].map(([l, k]) => (
                  <Inp key={k} label={l} value={f[k]} onChange={v => setF({ [k]: v })} type="number" small />
                ))}
              </div>
            </div>

            {/* Harga Jual */}
            <div style={{ borderTop: "1px solid #1c1e2b", paddingTop: 12 }}>
              <div style={{ color: "#3b82f6", fontFamily: "'DM Serif Display',serif", fontSize: 13, marginBottom: 10 }}>💲 Harga Jual Daging/kg</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[["Has Dalam","hJualHasDalam"],["Has Luar","hJualHasLuar"],["Tanjung","hJualTanjung"],["Gandik","hJualGandik"],["Lamusir","hJualLamusir"],["Sengkel","hJualSengkel"],["Sandung Lamur","hJualSandung"],["Paha Depan","hJualPahaD"],["Paha Belakang","hJualPahaB"],["Iga","hJualIga"],["Punuk","hJualPunuk"],["Leher","hJualLeher"],["Buntut/Ekor","hJualEkor"],["Tulang","hJualTulang"]].map(([l, k]) => (
                  <Inp key={k} label={l} value={f[k]} onChange={v => setF({ [k]: v })} type="number" small />
                ))}
              </div>
            </div>

            {/* Berat Fisik Nyata */}
            <div style={{ borderTop: "1px solid #1c1e2b", paddingTop: 12 }}>
              <div style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 13, marginBottom: 4 }}>📏 Berat Fisik Nyata (Opsional)</div>
              <div style={{ fontSize: 10, color: "#555a6a", marginBottom: 10 }}>Isi hasil timbangan. Kosong = estimasi % standar.</div>
              <div style={{ color: "#f5c842", fontSize: 10, fontWeight: 700, marginBottom: 6 }}>Karkas & Potongan</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 6, marginBottom: 10 }}>
                {[["Karkas","aKarkas"],["Tulang","aTulang"],["Has Dalam","aHasDalam"],["Has Luar","aHasLuar"],["Tanjung","aTanjung"],["Gandik","aGandik"],["Lamusir","aLamusir"],["Sengkel","aSengkel"],["Sandung","aSandung"],["Paha Depan","aPahaD"],["Paha Blkg","aPahaB"],["Iga","aIga"],["Punuk","aPunuk"],["Leher","aLeher"],["Buntut/Ekor","aEkor"]].map(([l, k]) => (
                  <Inp key={k} label={l} value={f[k]} onChange={v => setF({ [k]: v })} type="number" small placeholder="kg" hl />
                ))}
              </div>
              <div style={{ color: "#a855f7", fontSize: 10, fontWeight: 700, marginBottom: 6 }}>Jeroan & By-Product</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 6, marginBottom: 10 }}>
                {[["Hati","aHati"],["Paru","aParu"],["Jantung","aJantung"],["Ginjal","aGinjal"],["Limpa","aLimpa"],["Otak","aOtak"],["Lidah","aLidah"],["Babat","aBabat"],["Usus Besar","aUsusB"],["Usus Halus","aUsusH"],["Kepala","aKepala"],["Kikil/Kaki","aKikil"],["Kulit","aKulit"],["Darah (L)","aDarah"],["Tetelan","aTetelan"]].map(([l, k]) => (
                  <Inp key={k} label={l} value={f[k]} onChange={v => setF({ [k]: v })} type="number" small placeholder="kg" hl />
                ))}
              </div>
              <div style={{ color: "#555a6a", fontSize: 10, fontWeight: 700, marginBottom: 6 }}>Limbah</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
                <Inp label="Isi Rumen+Usus" value={f.aRumen} onChange={v => setF({ aRumen: v })} type="number" small placeholder="kg" hl />
                <Inp label="Feses & Urin" value={f.aFeses} onChange={v => setF({ aFeses: v })} type="number" small placeholder="kg" hl />
              </div>
            </div>

            <div style={{ borderTop: "1px solid #1c1e2b", paddingTop: 12 }}>
              <label style={{ fontSize: 9, color: "#555a6a", fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, display: "block", marginBottom: 4 }}>Catatan</label>
              <textarea value={f.notes || ""} onChange={e => setF({ notes: e.target.value })} rows={2} style={{ background: "#13161f", border: "1px solid #252535", borderRadius: 8, padding: "8px 11px", color: "#e2e4f0", fontSize: 12, width: "100%", outline: "none", boxSizing: "border-box", resize: "vertical" }} />
            </div>

            <button onClick={saveRecord} disabled={!f.bbHidup || !f.hargaBeli} style={{ background: (!f.bbHidup || !f.hargaBeli) ? "#333" : AC, color: "#fff", border: "none", borderRadius: 10, padding: 12, cursor: (!f.bbHidup || !f.hargaBeli) ? "not-allowed" : "pointer", fontWeight: 800, fontSize: 14, width: "100%" }}>
              💾 Simpan ke Riwayat RPH
            </button>
          </div>

          {/* HASIL KALKULASI */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {!preview ? (
              <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 14, padding: 48, textAlign: "center", color: "#555a6a", fontSize: 13 }}>← Isi data sapi di kiri untuk melihat hasil kalkulasi RPH</div>
            ) : (
              <>
                {/* RINGKASAN */}
                <div style={{ background: "#0f1118", border: "1px solid " + AC + "28", borderRadius: 14, padding: 18 }}>
                  <div style={{ color: AC, fontFamily: "'DM Serif Display',serif", fontSize: 15, marginBottom: 12 }}>📊 Ringkasan RPH</div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(125px,1fr))", gap: 10 }}>
                    {[["Berat Karkas", preview.beratKarkas + " kg", "#f5c842", preview.pctKarkas + "% dari BH"],
                      ["Total Daging", preview.totalDaging + " kg", "#22c55e", ""],
                      ["Tulang", preview.beratTulang + " kg", "#9097a8", ""],
                      ["Lemak/Susut", Math.max(0, preview.beratSusut).toFixed(1) + " kg", "#555a6a", ""],
                      ["HPP Daging/kg", "Rp " + preview.hppPerKg.toLocaleString("id-ID"), "#f59e0b", "BEP"],
                      ["Total Biaya", "Rp " + (preview.totalBiaya / 1e6).toFixed(2) + "jt", AC, ""],
                      ["Total Pend.", "Rp " + (preview.pendTotal / 1e6).toFixed(2) + "jt", "#3b82f6", ""],
                      ["PROFIT", "Rp " + (preview.profit / 1e6).toFixed(2) + "jt", preview.profit >= 0 ? "#22c55e" : AC, ""],
                      ["ROI", preview.roi + "%", preview.roi >= 15 ? "#22c55e" : "#f59e0b", ""],
                      ["MBR", preview.mbr + ":1", "#a855f7", "Meat:Bone"],
                    ].map(([l, v, c, s]) => (
                      <div key={l} style={{ background: "#ffffff07", borderRadius: 9, padding: "10px 12px" }}>
                        <div style={{ fontSize: 9, color: "#555a6a", fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, marginBottom: 4 }}>{l}</div>
                        <div style={{ color: c, fontWeight: 700, fontSize: 14, lineHeight: 1.2 }}>{v}</div>
                        {s && <div style={{ fontSize: 10, color: "#555a6a", marginTop: 2 }}>{s}</div>}
                      </div>
                    ))}
                  </div>
                </div>

                {/* BREAKDOWN */}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
                  {[["🥩 Daging", preview.pendDaging, "#22c55e"], ["🦴 Tulang", preview.pendTulang, "#9097a8"], ["🫀 By-Product", preview.pendByP, "#a855f7"]].map(([l, v, c]) => (
                    <div key={l} style={{ background: c + "0c", border: "1px solid " + c + "22", borderRadius: 11, padding: 14, textAlign: "center" }}>
                      <div style={{ color: c, fontSize: 11, fontWeight: 700, marginBottom: 4 }}>{l}</div>
                      <div style={{ color: c, fontSize: 15, fontWeight: 800 }}>{"Rp " + (v / 1e6).toFixed(2) + "jt"}</div>
                      <div style={{ color: "#555a6a", fontSize: 10, marginTop: 2 }}>{((v / preview.pendTotal) * 100).toFixed(1) + "% total"}</div>
                    </div>
                  ))}
                </div>

                {/* TABEL POTONGAN */}
                <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 14, padding: 18 }}>
                  <div style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 12 }}>🥩 Rincian Potongan Daging</div>
                  <div style={{ overflowX: "auto" }}>
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                      <thead><tr style={{ background: "#22c55e09", borderBottom: "1px solid #22c55e22" }}>
                        {["Potongan", "Grade", "%Karkas", "Berat", "Harga/kg", "Pendapatan"].map(h => <th key={h} style={{ ...thS, color: "#22c55e" }}>{h}</th>)}
                      </tr></thead>
                      <tbody>
                        {preview.potongan.map((p, i) => {
                          const gc = gradeC(p.grade);
                          return (
                            <tr key={p.kode} style={{ borderBottom: "1px solid #1c1e2b", background: p.aktual ? "#22c55e05" : i % 2 ? "#ffffff02" : "transparent" }}>
                              <td style={{ ...tdS("#e2e4f0", true), position: "relative" }}>
                                {p.aktual && <span style={{ position: "absolute", left: 6, top: "50%", transform: "translateY(-50%)", width: 3, height: 16, background: "#22c55e", borderRadius: 2 }} />}
                                <span style={{ paddingLeft: p.aktual ? 10 : 0 }}>{p.nama}</span>
                              </td>
                              <td style={{ padding: "8px 10px" }}><span style={{ background: gc + "15", color: gc, border: "1px solid " + gc + "28", borderRadius: 20, padding: "2px 7px", fontSize: 10, fontWeight: 700 }}>{p.grade}</span></td>
                              <td style={tdS("#9097a8")}>{p.pct}%</td>
                              <td style={tdS("#f5c842", true)}>{p.beratKg} kg</td>
                              <td style={tdS("#9097a8")}>{"Rp " + p.harga.toLocaleString("id-ID")}</td>
                              <td style={tdS("#22c55e", true)}>{"Rp " + p.pend.toLocaleString("id-ID")}</td>
                            </tr>
                          );
                        })}
                        <tr style={{ borderTop: "2px solid #22c55e33", background: "#22c55e09" }}>
                          <td colSpan={3} style={{ padding: "8px 10px", color: "#22c55e", fontWeight: 800 }}>TOTAL DAGING</td>
                          <td style={tdS("#f5c842", true)}>{preview.totalDaging} kg</td>
                          <td />
                          <td style={tdS("#22c55e", true)}>{"Rp " + preview.pendDaging.toLocaleString("id-ID")}</td>
                        </tr>
                        <tr style={{ background: "#9097a809" }}>
                          <td colSpan={2} style={tdS("#9097a8")}>Tulang</td>
                          <td style={tdS("#9097a8")}>{RPH_STANDAR.pct_tulang}%</td>
                          <td style={tdS("#9097a8", true)}>{preview.beratTulang} kg</td>
                          <td style={tdS("#9097a8")}>{"Rp " + (f.hJualTulang || 25000).toLocaleString("id-ID")}</td>
                          <td style={tdS("#9097a8", true)}>{"Rp " + preview.pendTulang.toLocaleString("id-ID")}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                {/* TABEL BY-PRODUCT */}
                <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 14, padding: 18 }}>
                  <div style={{ color: "#a855f7", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 12 }}>🫀 Jeroan & By-Product</div>
                  <div style={{ overflowX: "auto" }}>
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                      <thead><tr style={{ background: "#a855f709", borderBottom: "1px solid #a855f722" }}>
                        {["Produk", "Kategori", "%BH", "Berat", "Harga/kg", "Pendapatan"].map(h => <th key={h} style={{ ...thS, color: "#a855f7" }}>{h}</th>)}
                      </tr></thead>
                      <tbody>
                        {preview.byProducts.map((b, i) => {
                          const catC = { "Fancy Meat": "#f5c842", "Jeroan Merah": "#ef4444", "Jeroan Putih": "#9097a8", "Kulit/Darah": "#555a6a" };
                          const cc = catC[b.kat] || "#666";
                          return (
                            <tr key={b.nama} style={{ borderBottom: "1px solid #1c1e2b", background: b.aktual ? "#a855f706" : i % 2 ? "#ffffff02" : "transparent" }}>
                              <td style={tdS("#e2e4f0", true)}>{b.nama}{b.aktual && <span style={{ marginLeft: 6, background: "#22c55e18", color: "#22c55e", border: "1px solid #22c55e30", borderRadius: 20, padding: "1px 6px", fontSize: 9, fontWeight: 700 }}>✅</span>}</td>
                              <td style={{ padding: "8px 10px" }}><span style={{ background: cc + "14", color: cc, border: "1px solid " + cc + "28", borderRadius: 20, padding: "2px 7px", fontSize: 9, fontWeight: 700 }}>{b.kat}</span></td>
                              <td style={tdS("#9097a8")}>{+(b.beratKg / preview.bb * 100).toFixed(2)}%</td>
                              <td style={tdS("#f5c842", true)}>{b.beratKg} kg</td>
                              <td style={tdS("#9097a8")}>{"Rp " + b.harga.toLocaleString("id-ID")}</td>
                              <td style={tdS("#a855f7", true)}>{"Rp " + b.pend.toLocaleString("id-ID")}</td>
                            </tr>
                          );
                        })}
                        <tr style={{ borderTop: "2px solid #a855f733", background: "#a855f709" }}>
                          <td colSpan={3} style={{ padding: "8px 10px", color: "#a855f7", fontWeight: 800 }}>TOTAL BY-PRODUCT</td>
                          <td style={tdS("#f5c842", true)}>{+preview.byProducts.reduce((s, b) => s + b.beratKg, 0).toFixed(2)} kg</td>
                          <td />
                          <td style={tdS("#a855f7", true)}>{"Rp " + preview.pendByP.toLocaleString("id-ID")}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                {/* BIAYA & PROFIT */}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 13, padding: 16 }}>
                    <div style={{ color: AC, fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 12 }}>💸 Rincian Biaya</div>
                    {[["Harga Beli Sapi", f.hargaBeli, "#f5c842"], ["Retribusi RPH", f.bRetribusi, "#9097a8"], ["Upah Potong", f.bUpah, "#9097a8"], ["Listrik & Air", f.bListrik, "#9097a8"], ["Kemasan", f.bKemasan, "#9097a8"], ["Transportasi", f.bTransport, "#9097a8"], ["Lainnya", f.bLainnya, "#9097a8"], ["TOTAL BIAYA", preview.totalBiaya, AC]].map(([k, v, c], i) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: i < 7 ? "1px solid #1c1e2b" : "none", borderTop: i === 7 ? "2px solid " + AC + "33" : "none", marginTop: i === 7 ? 4 : 0 }}>
                        <span style={{ fontSize: 12, color: "#9097a8" }}>{k}</span>
                        <span style={{ color: c, fontWeight: i === 7 ? 800 : 600, fontSize: i === 7 ? 13 : 12 }}>{"Rp " + Number(v).toLocaleString("id-ID")}</span>
                      </div>
                    ))}
                  </div>
                  <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 13, padding: 16 }}>
                    <div style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 12 }}>💰 Rekap Keuangan</div>
                    {[["Pend. Daging", preview.pendDaging, "#22c55e"], ["Pend. Tulang", preview.pendTulang, "#9097a8"], ["Pend. By-Product", preview.pendByP, "#a855f7"], ["TOTAL PEND.", preview.pendTotal, "#3b82f6"], ["Total Biaya", preview.totalBiaya, AC], ["PROFIT BERSIH", preview.profit, preview.profit >= 0 ? "#22c55e" : AC], ["ROI", preview.roi + "%", "#f5c842"], ["HPP/kg", "Rp " + preview.hppPerKg.toLocaleString("id-ID"), "#f59e0b"]].map(([k, v, c], i) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: i < 7 ? "1px solid #1c1e2b" : "none", borderTop: [3, 5].includes(i) ? "2px solid #1c1e2b" : "none", marginTop: [4, 5].includes(i) ? 4 : 0 }}>
                        <span style={{ fontSize: 12, color: "#9097a8" }}>{k}</span>
                        <span style={{ color: c, fontWeight: [3, 5, 6].includes(i) ? 800 : 600, fontSize: [3, 5].includes(i) ? 13 : 12 }}>{typeof v === "string" ? v : "Rp " + v.toLocaleString("id-ID")}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* ═══ TAB RIWAYAT ═══ */}
      {tab === "riwayat" && (
        records.length === 0 ? (
          <div style={{textAlign:"center",padding:60,color:"#555a6a",background:"#0f1118",borderRadius:12,border:"1px solid #1c1e2b",fontSize:13}}>
            Belum ada riwayat. Tambahkan di tab Kalkulator.
          </div>
        ) : (() => {
          const curId  = activeId || records[0]?.id;
          const rec    = records.find(r => r.id === curId) || records[0];
          const c      = rec ? hitungRPH(rec) : null;
          if (!c || !rec) return null;

          const gJ = nm => c.byProducts.find(b => b.nama === nm) || {beratKg:0,pend:0,aktual:false,harga:0,kat:"—",latin:"—"};
          const hati=gJ("Hati"), paru=gJ("Paru-paru"), jantung=gJ("Jantung"),
                ginjal=gJ("Ginjal"), limpa=gJ("Limpa"), otak=gJ("Otak"),
                lidah=gJ("Lidah"), babat=gJ("Babat (Rumen)"),
                ususB=gJ("Usus Besar"), ususH=gJ("Usus Halus"),
                kepala=gJ("Kepala (daging)"), kikil=gJ("Kikil/Kaki (4)"),
                kulit=gJ("Kulit Sapi"), darah=gJ("Darah Sapi (L)"), tetelan=gJ("Tetelan (Koyor)");

          const jerMerahKg  = +[hati,paru,jantung,ginjal,limpa,otak].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const jerPutihKg  = +[babat,ususB,ususH,tetelan].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const fancyKg     = +[lidah,kepala,kikil].reduce((s,b)=>s+b.beratKg,0).toFixed(1);
          const jerMerahPend= hati.pend+paru.pend+jantung.pend+ginjal.pend+limpa.pend+otak.pend;
          const jerPutihPend= babat.pend+ususB.pend+ususH.pend+tetelan.pend;
          const fancyPend   = lidah.pend+kepala.pend+kikil.pend;

          const chartKomp = [
            {label:"Daging",    value:c.totalDaging,               label2:c.totalDaging+"kg",  color:"#22c55e"},
            {label:"Tulang",    value:c.beratTulang,               label2:c.beratTulang+"kg",  color:"#9097a8"},
            {label:"Lemak",     value:Math.max(0,c.beratSusut),    label2:"",                  color:"#555a6a"},
            {label:"Jer.Merah", value:jerMerahKg,                  label2:"",                  color:"#ef4444"},
            {label:"Jer.Putih", value:jerPutihKg,                  label2:"",                  color:"#a855f7"},
            {label:"Fancy",     value:fancyKg,                     label2:"",                  color:"#f5c842"},
            {label:"Kulit",     value:kulit.beratKg,               label2:"",                  color:"#f59e0b"},
            {label:"Darah",     value:darah.beratKg,               label2:"",                  color:"#ef4444"},
            {label:"Rumen",     value:c.bRumen,                    label2:c.bRumen+"kg",       color:"#444"},
            {label:"Feses",     value:c.bFeses,                    label2:c.bFeses+"kg",       color:"#333"},
          ];
          const chartPot = c.potongan.map(p=>({
            label:p.nama.split("(")[0].trim(), value:p.beratKg,
            label2:p.beratKg+"kg", color:gradeC(p.grade)
          })).concat([{label:"Tulang",value:c.beratTulang,label2:c.beratTulang+"kg",color:"#555a6a"}]);
          const chartPend = [
            {label:"Premium",  value:Math.round(c.potongan.filter(p=>p.grade==="Premium").reduce((s,p)=>s+p.pend,0)/1000),  color:"#f5c842"},
            {label:"Superior", value:Math.round(c.potongan.filter(p=>p.grade==="Superior").reduce((s,p)=>s+p.pend,0)/1000), color:"#3b82f6"},
            {label:"Standar",  value:Math.round(c.potongan.filter(p=>p.grade==="Standar").reduce((s,p)=>s+p.pend,0)/1000),  color:"#9097a8"},
            {label:"Tulang",   value:Math.round(c.pendTulang/1000),                                                          color:"#555a6a"},
            {label:"Jer.Merah",value:Math.round(jerMerahPend/1000),                                                          color:"#ef4444"},
            {label:"Fancy",    value:Math.round(fancyPend/1000),                                                              color:"#f5c842"},
            {label:"Jer.Putih",value:Math.round(jerPutihPend/1000),                                                          color:"#a855f7"},
          ];

          const stl = {
            th: {padding:"8px 10px",color:"#555a6a",textAlign:"left",fontSize:9,fontWeight:800,textTransform:"uppercase",whiteSpace:"nowrap",borderBottom:"1px solid #1c1e2b"},
            td: (col="#e2e4f0",bold=false)=>({padding:"8px 10px",color:col,fontWeight:bold?700:400,fontSize:12}),
            badgeAkt: (isA)=>({background:isA?"#22c55e18":"#f5c84218",color:isA?"#22c55e":"#f5c842",border:"1px solid "+(isA?"#22c55e30":"#f5c84230"),borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}),
          };

          return (
            <div style={{display:"grid",gridTemplateColumns:"250px 1fr",gap:14,alignItems:"start"}}>

              {/* ══ PANEL KIRI: LIST ══ */}
              <div style={{background:"#0a0c16",border:"1px solid #1c1e2b",borderRadius:13,overflow:"hidden",position:"sticky",top:0}}>
                <div style={{background:"#ef444412",padding:"11px 15px",borderBottom:"1px solid #ef444428"}}>
                  <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:13,fontWeight:700}}>📋 Daftar Pemotongan</div>
                  <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{records.length} ekor tercatat</div>
                </div>
                <div style={{maxHeight:"78vh",overflowY:"auto"}}>
                  {records.map(r=>{
                    const rc = hitungRPH(r); if(!rc) return null;
                    const isActive = r.id === curId;
                    return (
                      <div key={r.id} onClick={()=>setActiveId(r.id)}
                        style={{padding:"10px 15px",borderBottom:"1px solid #1c1e2b",cursor:"pointer",
                          background:isActive?"#ef444412":"transparent",
                          borderLeft:"3px solid "+(isActive?AC:"transparent"),transition:"all 0.1s"}}>
                        <div style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                          <span style={{color:isActive?AC:"#e2e4f0",fontWeight:700,fontSize:12}}>{r.sapiNama||"—"}</span>
                          <span style={{fontSize:9,fontWeight:700,padding:"2px 6px",borderRadius:10,
                            background:rc.profit>=0?"#22c55e18":"#ef444418",
                            color:rc.profit>=0?"#22c55e":"#ef4444"}}>
                            {rc.profit>=0?"+":"-"}{"Rp "+(Math.abs(rc.profit)/1e6).toFixed(1)+"jt"}
                          </span>
                        </div>
                        <div style={{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"}}>
                          <span style={{color:"#f5c842",fontSize:10,fontWeight:700}}>{r.bbHidup}kg</span>
                          <span style={{color:"#555a6a",fontSize:9}}>·</span>
                          <span style={{color:"#9097a8",fontSize:10}}>{r.breed}</span>
                          <span style={{color:"#555a6a",fontSize:9}}>·</span>
                          <span style={{color:"#555a6a",fontSize:9}}>{r.tglPotong}</span>
                        </div>
                        <div style={{display:"flex",gap:8,marginTop:3}}>
                          <span style={{color:"#3b82f6",fontSize:9}}>{"Rp "+(rc.pendTotal/1e6).toFixed(1)+"jt"}</span>
                          <span style={{color:"#555a6a",fontSize:9}}>ROI {rc.roi}%</span>
                          {rc.hasAktual&&<span style={{color:"#22c55e",fontSize:8,background:"#22c55e12",padding:"1px 5px",borderRadius:8}}>✅</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* ══ PANEL KANAN: DETAIL ══ */}
              <div style={{display:"flex",flexDirection:"column",gap:11,minWidth:0}}>

                {/* Header */}
                <div style={{background:"#0c0f1a",border:"1px solid #252535",borderRadius:13,padding:"13px 17px",
                  display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:10}}>
                  <div>
                    <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:18,fontWeight:700,
                      display:"flex",alignItems:"center",gap:9,flexWrap:"wrap"}}>
                      🔪 {rec.sapiNama||"—"}
                      <span style={{fontSize:11,color:"#555a6a",fontWeight:400}}>({rec.id})</span>
                      <span style={{background:c.hasAktual?"#22c55e18":"#f5c84218",
                        color:c.hasAktual?"#22c55e":"#f5c842",
                        border:"1px solid "+(c.hasAktual?"#22c55e30":"#f5c84230"),
                        borderRadius:20,padding:"2px 9px",fontSize:10,fontWeight:700}}>
                        {c.hasAktual?"✅ Data Aktual":"📊 Estimasi"}
                      </span>
                    </div>
                    <div style={{color:"#9097a8",fontSize:11,marginTop:3}}>
                      {rec.breed} · {rec.gender} · BH: {c.bb}kg · Karkas: {rec.pctKarkas}% ({c.beratKarkas}kg)
                      {rec.tglPotong?" · "+rec.tglPotong:""}{rec.buyer?" · "+rec.buyer:""}
                    </div>
                  </div>
                  <button onClick={()=>cetakLaporan(rec,c)}
                    style={{background:"#ef444418",color:AC,border:"1px solid #ef444430",
                      borderRadius:9,padding:"8px 15px",cursor:"pointer",fontWeight:700,fontSize:12}}>
                    🖨️ Cetak
                  </button>
                </div>

                {/* KPI Strip */}
                <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:9}}>
                  {[["💰 Pendapatan","Rp "+(c.pendTotal/1e6).toFixed(2)+"jt","#3b82f6"],
                    ["💸 Biaya",      "Rp "+(c.totalBiaya/1e6).toFixed(2)+"jt","#ef4444"],
                    ["📈 Profit",     "Rp "+(c.profit/1e6).toFixed(2)+"jt",   c.profit>=0?"#22c55e":"#ef4444"],
                    ["🔄 ROI",        c.roi+"%",                               +c.roi>=15?"#22c55e":"#f59e0b"],
                    ["🏷️ HPP/kg",    "Rp "+c.hppPerKg.toLocaleString("id-ID"),"#f5c842"],
                  ].map(([l,v,col])=>(
                    <div key={l} style={{background:col+"0d",border:"1px solid "+col+"25",borderRadius:10,padding:"9px 11px",textAlign:"center"}}>
                      <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:3}}>{l}</div>
                      <div style={{color:col,fontWeight:800,fontSize:13}}>{v}</div>
                    </div>
                  ))}
                </div>

                {/* Sub-Tabs */}
                <div style={{display:"flex",gap:2,background:"#0a0c16",borderRadius:"10px 10px 0 0",
                  border:"1px solid #1c1e2b",borderBottom:"none",padding:"0 4px",paddingTop:4}}>
                  {[["ilmiah","🔬 Ilmiah"],["bisnis","💰 Bisnis"],["grafik","📊 Grafik"],
                    ["potongan","🥩 Potongan"],["jeroan","🫀 Jeroan"]].map(([id,lbl])=>(
                    <button key={id} onClick={()=>setSubTab(id)}
                      style={{flex:1,background:subTab===id?"#0f1118":"none",border:"none",
                        borderBottom:subTab===id?"2px solid "+AC:"2px solid transparent",
                        color:subTab===id?AC:"#555a6a",padding:"8px 4px",cursor:"pointer",
                        fontWeight:700,fontSize:11,borderRadius:"6px 6px 0 0",transition:"all 0.1s"}}>
                      {lbl}
                    </button>
                  ))}
                </div>

                {/* ─── Sub-tab content ─── */}
                <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:"0 0 13px 13px",
                  padding:16,marginTop:-1}}>

                  {/* ILMIAH */}
                  {subTab==="ilmiah" && (
                    <div style={{display:"flex",flexDirection:"column",gap:14}}>
                      <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:4}}>
                        📐 Komposisi Tubuh (BH = {c.bb} kg)
                      </div>
                      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
                        {[
                          ["Karkas",       c.beratKarkas,                          rec.pctKarkas+"%",   "#f5c842",!!rec.aKarkas],
                          ["Daging",       c.totalDaging,                          +(c.totalDaging/c.bb*100).toFixed(1)+"%","#22c55e",false],
                          ["Tulang",       c.beratTulang,                          RPH_STANDAR.pct_tulang+"% karkas","#9097a8",!!rec.aTulang],
                          ["Lemak/Trim",   +Math.max(0,c.beratSusut).toFixed(1),   c.pctSusut+"% karkas","#555a6a",false],
                          ["Jer.Merah",    jerMerahKg,                             +(jerMerahKg/c.bb*100).toFixed(1)+"%","#ef4444",false],
                          ["Jer.Putih",    jerPutihKg,                             +(jerPutihKg/c.bb*100).toFixed(1)+"%","#a855f7",false],
                          ["Fancy Meat",   fancyKg,                                +(fancyKg/c.bb*100).toFixed(1)+"%","#f5c842",false],
                          ["Kulit+Darah",  +(kulit.beratKg+darah.beratKg).toFixed(1),+(((kulit.beratKg+darah.beratKg)/c.bb)*100).toFixed(1)+"%","#f59e0b",false],
                          ["Isi Rumen",    c.bRumen,                               +(c.bRumen/c.bb*100).toFixed(0)+"%","#555a6a",!!rec.aRumen],
                          ["Feses & Urin", c.bFeses,                               "~4% BH",            "#444",!!rec.aFeses],
                          ["Teridentifikasi",+(c.beratKarkas+c.byProducts.reduce((s,b)=>s+b.beratKg,0)+c.bFeses+c.bRumen).toFixed(1),"dari BH","#3b82f6",false],
                          ["Selisih",      +(c.bb-c.beratKarkas-c.byProducts.reduce((s,b)=>s+b.beratKg,0)-c.bFeses-c.bRumen).toFixed(1),"shrinkage","#555a6a",false],
                        ].map(([nm,brt,pct,col,isAkt])=>(
                          <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:9,padding:"9px 11px"}}>
                            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:2}}>
                              <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>{nm}</div>
                              {isAkt!==false&&<span style={{...stl.badgeAkt(isAkt),fontSize:8,padding:"0px 5px"}}>{isAkt?"✅":"📊"}</span>}
                            </div>
                            <div style={{color:col,fontWeight:800,fontSize:16}}>{brt} <span style={{fontSize:10,fontWeight:400}}>kg</span></div>
                            <div style={{color:"#555a6a",fontSize:10,marginTop:1}}>{pct}</div>
                          </div>
                        ))}
                      </div>
                      <div style={{borderTop:"1px solid #1c1e2b",paddingTop:12}}>
                        <div style={{color:"#3b82f6",fontFamily:"'DM Serif Display',serif",fontSize:12,marginBottom:10}}>🔬 Indikator Kualitas Ilmiah</div>
                        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8}}>
                          {[
                            ["DCP (Dressing %)",    c.pctKarkas+"%",                                   c.pctKarkas>=55?"#22c55e":c.pctKarkas>=50?"#f59e0b":"#ef4444","Ideal ≥52%. Efisiensi konversi BH→karkas"],
                            ["Meat-Bone Ratio",     c.mbr+":1",                                        +c.mbr>=3.5?"#22c55e":"#f59e0b","Rasio daging:tulang. Ideal ≥3.5:1"],
                            ["% Lean dari Karkas",  +(c.totalDaging/c.beratKarkas*100).toFixed(1)+"%",  c.totalDaging/c.beratKarkas>=0.75?"#22c55e":"#f59e0b","% daging bersih. Ideal ≥75% karkas"],
                            ["% Lean dari BH",      +(c.totalDaging/c.bb*100).toFixed(1)+"%",           c.totalDaging/c.bb>=0.38?"#22c55e":"#f59e0b","% daging dari BH. Ideal ≥38%"],
                            ["% Tulang dr Karkas",  +(c.beratTulang/c.beratKarkas*100).toFixed(1)+"%",  "#9097a8","Standar 16–20% dari berat karkas"],
                            ["By-Product Revenue",  +(c.pendByP/c.pendTotal*100).toFixed(1)+"%",        "#a855f7","Kontribusi jeroan dari total omzet RPH"],
                          ].map(([k,v,col,desc])=>(
                            <div key={k} style={{background:"#ffffff05",borderRadius:8,padding:"9px 11px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:8}}>
                              <div style={{flex:1}}>
                                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                                <div style={{fontSize:10,color:"#444",lineHeight:1.3}}>{desc}</div>
                              </div>
                              <div style={{color:col,fontWeight:800,fontSize:16,textAlign:"right",whiteSpace:"nowrap"}}>{v}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* BISNIS */}
                  {subTab==="bisnis" && (
                    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
                      {/* Biaya */}
                      <div>
                        <div style={{color:"#ef4444",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💸 Rincian Biaya Modal</div>
                        {[
                          ["Harga Beli Sapi",c.hBeli,"#f5c842",true],
                          ["Retribusi RPH",  c.biaya.retribusi,"#9097a8"],
                          ["Upah Potong",    c.biaya.upah,"#9097a8"],
                          ["Listrik & Air",  c.biaya.listrik,"#9097a8"],
                          ["Kemasan",        c.biaya.kemasan,"#9097a8"],
                          ["Transportasi",   c.biaya.transport,"#9097a8"],
                          ["Lainnya",        c.biaya.lainnya,"#9097a8"],
                          ["Total Ops RPH",  c.biayaOps,"#ef4444",false,true],
                          ["TOTAL MODAL",    c.totalBiaya,"#ef4444",true],
                        ].map(([k,v,col,bold,sep])=>(
                          <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",
                            borderBottom:"1px solid #1c1e2b",
                            borderTop:sep?"1px solid #ef444422":"none",marginTop:sep?6:0}}>
                            <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                            <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{"Rp "+Number(v).toLocaleString("id-ID")}</span>
                          </div>
                        ))}
                        <div style={{marginTop:12,background:"#ef444410",border:"1px solid #ef444428",borderRadius:9,padding:"10px 12px"}}>
                          <div style={{fontSize:10,color:"#9097a8",marginBottom:3}}>HPP (Harga Pokok Produksi)</div>
                          <div style={{fontSize:20,fontWeight:800,color:"#f5c842"}}>{"Rp "+c.hppPerKg.toLocaleString("id-ID")}<span style={{fontSize:11,fontWeight:400,color:"#555a6a"}}>/kg daging</span></div>
                          <div style={{fontSize:10,color:"#555a6a",marginTop:2}}>Harga jual minimal agar balik modal</div>
                        </div>
                      </div>
                      {/* Pendapatan */}
                      <div>
                        <div style={{color:"#22c55e",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>💰 Rincian Pendapatan</div>
                        {[
                          ["Daging Premium",  c.potongan.filter(p=>p.grade==="Premium").reduce((s,p)=>s+p.pend,0),"#f5c842"],
                          ["Daging Superior", c.potongan.filter(p=>p.grade==="Superior").reduce((s,p)=>s+p.pend,0),"#3b82f6"],
                          ["Daging Standar",  c.potongan.filter(p=>p.grade==="Standar").reduce((s,p)=>s+p.pend,0),"#9097a8"],
                          ["Tulang",          c.pendTulang,"#9097a8"],
                          ["Fancy Meat",      fancyPend,"#f5c842"],
                          ["Jeroan Merah",    jerMerahPend,"#ef4444"],
                          ["Jeroan Putih",    jerPutihPend,"#a855f7"],
                          ["Kulit+Darah",     kulit.pend+darah.pend,"#f59e0b"],
                          ["TOTAL PENDAPATAN",c.pendTotal,"#3b82f6",true],
                          ["PROFIT BERSIH",   c.profit,c.profit>=0?"#22c55e":"#ef4444",true],
                          ["ROI",             null,"#f5c842",true],
                        ].map(([k,v,col,bold])=>{
                          const disp = k==="ROI" ? c.roi+"%" : "Rp "+Number(v).toLocaleString("id-ID");
                          return (
                            <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"5px 0",
                              borderBottom:"1px solid #1c1e2b",
                              borderTop:bold?"2px solid #1c1e2b":"none",marginTop:bold?4:0}}>
                              <span style={{fontSize:12,color:"#9097a8"}}>{k}</span>
                              <span style={{color:col,fontWeight:bold?800:500,fontSize:bold?13:12}}>{disp}</span>
                            </div>
                          );
                        })}
                        <div style={{marginTop:12,display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                          {[["MBR",c.mbr+":1","#a855f7"],["DCP",c.pctKarkas+"%",c.pctKarkas>=52?"#22c55e":"#f59e0b"]].map(([k,v,col])=>(
                            <div key={k} style={{background:col+"0d",border:"1px solid "+col+"25",borderRadius:8,padding:"9px 11px",textAlign:"center"}}>
                              <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{k}</div>
                              <div style={{color:col,fontWeight:800,fontSize:17}}>{v}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      {/* Neraca Bobot */}
                      <div style={{gridColumn:"1/-1",borderTop:"1px solid #1c1e2b",paddingTop:14}}>
                        <div style={{color:"#f5c842",fontFamily:"'DM Serif Display',serif",fontSize:13,marginBottom:10}}>⚖️ Neraca Bobot Lengkap</div>
                        <div style={{display:"grid",gridTemplateColumns:"repeat(6,1fr)",gap:7}}>
                          {[
                            ["BH Awal",        c.bb,"100%","#f5c842"],
                            ["Karkas",          c.beratKarkas,rec.pctKarkas+"%","#22c55e"],
                            ["Daging",          c.totalDaging,+(c.totalDaging/c.bb*100).toFixed(1)+"%","#22c55e"],
                            ["Tulang",          c.beratTulang,+(c.beratTulang/c.bb*100).toFixed(1)+"%","#9097a8"],
                            ["Lemak/Trim",      +Math.max(0,c.beratSusut).toFixed(1),+(Math.max(0,c.beratSusut)/c.bb*100).toFixed(1)+"%","#555a6a"],
                            ["Jeroan Ed.",      +c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0).toFixed(1),+(c.byProducts.filter(b=>b.kat!=="Kulit/Darah").reduce((s,b)=>s+b.beratKg,0)/c.bb*100).toFixed(1)+"%","#a855f7"],
                            ["Kulit+Darah",     +(kulit.beratKg+darah.beratKg).toFixed(1),+(((kulit.beratKg+darah.beratKg)/c.bb)*100).toFixed(1)+"%","#f59e0b"],
                            ["Isi Rumen",       c.bRumen,+(c.bRumen/c.bb*100).toFixed(0)+"%","#555a6a"],
                            ["Feses & Urin",    c.bFeses,"~4%","#444"],
                            ["Teridentif.",     +(c.beratKarkas+c.byProducts.reduce((s,b)=>s+b.beratKg,0)+c.bFeses+c.bRumen).toFixed(1),"dari BH","#3b82f6"],
                            ["Selisih",         +(c.bb-c.beratKarkas-c.byProducts.reduce((s,b)=>s+b.beratKg,0)-c.bFeses-c.bRumen).toFixed(1),"shrinkage","#555a6a"],
                          ].map(([nm,brt,pct,col])=>(
                            <div key={nm} style={{background:col+"0a",border:"1px solid "+col+"1e",borderRadius:8,padding:"7px 9px",textAlign:"center"}}>
                              <div style={{fontSize:8,color:"#555a6a",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{nm}</div>
                              <div style={{color:col,fontWeight:800,fontSize:14}}>{brt}<span style={{fontSize:9,fontWeight:400}}> kg</span></div>
                              <div style={{color:"#555a6a",fontSize:9}}>{pct}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* GRAFIK */}
                  {subTab==="grafik" && (
                    <div style={{display:"flex",flexDirection:"column",gap:12}}>
                      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
                        <BarChart data={chartKomp} title={"Komposisi Tubuh dari BH "+c.bb+"kg"} height={130}/>
                        <BarChart data={chartPend} title="Pendapatan per Kategori (Rp ribu)" height={130}/>
                      </div>
                      <BarChart data={chartPot} title="Berat per Potongan Daging & Tulang (kg)" height={120}/>
                      <div style={{display:"flex",gap:10,flexWrap:"wrap",fontSize:10,color:"#555a6a"}}>
                        {[["#f5c842","Premium"],["#3b82f6","Superior"],["#9097a8","Standar"],
                          ["#22c55e","Daging"],["#ef4444","Jer.Merah"],["#a855f7","Jer.Putih"],["#555a6a","Tulang"]].map(([col,lbl])=>(
                          <span key={lbl} style={{display:"flex",alignItems:"center",gap:4}}>
                            <span style={{width:9,height:9,borderRadius:2,background:col,display:"inline-block"}}/>{lbl}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* POTONGAN */}
                  {subTab==="potongan" && (
                    <div style={{overflowX:"auto"}}>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#22c55e0a",borderBottom:"1px solid #22c55e22"}}>
                          {["No","Potongan","Grade","%Karkas","Berat (kg)","%BH","Harga/kg","Nilai (Rp)","Data"].map(h=>(
                            <th key={h} style={{...stl.th,color:"#22c55e"}}>{h}</th>
                          ))}
                        </tr></thead>
                        <tbody>
                          {c.potongan.map((p,i)=>{
                            const gc=gradeC(p.grade);
                            return (
                              <tr key={p.kode} style={{borderBottom:"1px solid #1c1e2b",background:p.aktual?"#22c55e05":i%2?"#ffffff02":"transparent"}}>
                                <td style={stl.td("#555a6a")}>{i+1}</td>
                                <td style={stl.td("#e2e4f0",true)}>{p.nama}</td>
                                <td style={{padding:"8px 10px"}}><span style={{background:gc+"15",color:gc,border:"1px solid "+gc+"28",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>{p.grade}</span></td>
                                <td style={stl.td("#9097a8")}>{p.pct}%</td>
                                <td style={stl.td("#f5c842",true)}>{p.beratKg} kg</td>
                                <td style={stl.td("#555a6a")}>{+(p.beratKg/c.bb*100).toFixed(2)}%</td>
                                <td style={stl.td("#9097a8")}>{"Rp "+p.harga.toLocaleString("id-ID")}</td>
                                <td style={stl.td("#22c55e",true)}>{"Rp "+p.pend.toLocaleString("id-ID")}</td>
                                <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(p.aktual)}>{p.aktual?"✅":"📊"}</span></td>
                              </tr>
                            );
                          })}
                          <tr style={{borderTop:"2px solid #22c55e33",background:"#22c55e09"}}>
                            <td colSpan={4} style={{padding:"9px 10px",color:"#22c55e",fontWeight:800}}>TOTAL DAGING</td>
                            <td style={stl.td("#f5c842",true)}>{c.totalDaging} kg</td>
                            <td style={stl.td("#555a6a")}>{+(c.totalDaging/c.bb*100).toFixed(2)}%</td>
                            <td/>
                            <td style={stl.td("#22c55e",true)}>{"Rp "+c.pendDaging.toLocaleString("id-ID")}</td>
                            <td/>
                          </tr>
                          <tr style={{background:"#9097a80a"}}>
                            <td colSpan={2} style={stl.td("#9097a8")}>Tulang</td>
                            <td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",borderRadius:20,padding:"2px 7px",fontSize:10,fontWeight:700}}>By-product</span></td>
                            <td style={stl.td("#9097a8")}>{RPH_STANDAR.pct_tulang}%</td>
                            <td style={stl.td("#9097a8",true)}>{c.beratTulang} kg</td>
                            <td style={stl.td("#555a6a")}>{+(c.beratTulang/c.bb*100).toFixed(2)}%</td>
                            <td style={stl.td("#9097a8")}>{"Rp "+(rec.hJualTulang||25000).toLocaleString("id-ID")}</td>
                            <td style={stl.td("#9097a8",true)}>{"Rp "+c.pendTulang.toLocaleString("id-ID")}</td>
                            <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(!!rec.aTulang)}>{rec.aTulang?"✅":"📊"}</span></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* JEROAN */}
                  {subTab==="jeroan" && (
                    <div style={{overflowX:"auto"}}>
                      <table style={{width:"100%",borderCollapse:"collapse",fontSize:12}}>
                        <thead><tr style={{background:"#a855f70a",borderBottom:"1px solid #a855f722"}}>
                          {["Komponen","Kategori","Nama Latin","Berat (kg)","%BH","Harga/kg","Nilai (Rp)","Sifat","Data"].map(h=>(
                            <th key={h} style={{...stl.th,color:"#a855f7"}}>{h}</th>
                          ))}
                        </tr></thead>
                        <tbody>
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#f5c84212",color:"#f5c842",fontSize:10,fontWeight:700}}>🏆 FANCY & VARIETY MEAT</td></tr>
                          {[lidah,kepala,kikil].map((obj,i)=>(
                            <tr key={i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#f5c84205":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#f5c84215",color:"#f5c842",border:"1px solid #f5c84228",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Fancy Meat</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#f5c842",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(obj.aktual)}>{obj.aktual?"✅":"📊"}</span></td>
                            </tr>
                          ))}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#ef444412",color:"#ef4444",fontSize:10,fontWeight:700}}>🔴 JEROAN MERAH (Organ Parenkim)</td></tr>
                          {[hati,paru,jantung,ginjal,limpa,otak].map((obj,i)=>(
                            <tr key={i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#ef444406":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#ef444415",color:"#ef4444",border:"1px solid #ef444428",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Jeroan Merah</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#f5c842",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(obj.aktual)}>{obj.aktual?"✅":"📊"}</span></td>
                            </tr>
                          ))}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#9097a80a",color:"#9097a8",fontSize:10,fontWeight:700}}>⬜ JEROAN PUTIH (Saluran Cerna)</td></tr>
                          {[babat,ususB,ususH,tetelan].map((obj,i)=>(
                            <tr key={i} style={{borderBottom:"1px solid #1c1e2b",background:obj.aktual?"#9097a806":"transparent"}}>
                              <td style={stl.td("#e2e4f0",true)}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#9097a815",color:"#9097a8",border:"1px solid #9097a828",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Jeroan Putih</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin}</i></td>
                              <td style={stl.td("#f5c842",true)}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#9097a8")}>{"Rp "+obj.harga.toLocaleString("id-ID")}</td>
                              <td style={stl.td("#a855f7",true)}>{"Rp "+obj.pend.toLocaleString("id-ID")}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#22c55e14",color:"#22c55e",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Edible</span></td>
                              <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(obj.aktual)}>{obj.aktual?"✅":"📊"}</span></td>
                            </tr>
                          ))}
                          <tr><td colSpan={9} style={{padding:"5px 10px",background:"#f59e0b0a",color:"#f59e0b",fontSize:10,fontWeight:700}}>🩸 KULIT, DARAH & LIMBAH</td></tr>
                          {[
                            [kulit,"Industri/Pangan"],
                            [darah,"Edible/Industri"],
                            [{nama:"Isi Rumen+Usus",beratKg:c.bRumen,pend:0,harga:0,aktual:!!rec.aRumen,latin:"Digesta"},"Non-Edible"],
                            [{nama:"Feses & Urin",beratKg:c.bFeses,pend:0,harga:0,aktual:!!rec.aFeses,latin:"Faeces/Urina"},"Limbah"],
                          ].map(([obj,sifat],i)=>(
                            <tr key={i} style={{borderBottom:"1px solid #1c1e2b"}}>
                              <td style={stl.td("#e2e4f0")}>{obj.nama}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#f59e0b14",color:"#f59e0b",border:"1px solid #f59e0b28",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>Ikutan</span></td>
                              <td style={stl.td("#555a6a")}><i style={{fontSize:10}}>{obj.latin||"—"}</i></td>
                              <td style={stl.td("#f5c842")}>{obj.beratKg} kg</td>
                              <td style={stl.td("#9097a8")}>{+(obj.beratKg/c.bb*100).toFixed(2)}%</td>
                              <td style={stl.td("#555a6a")}>{obj.harga?"Rp "+obj.harga.toLocaleString("id-ID"):"—"}</td>
                              <td style={stl.td("#9097a8")}>{obj.pend?"Rp "+obj.pend.toLocaleString("id-ID"):"—"}</td>
                              <td style={{padding:"8px 10px"}}><span style={{background:"#ef444414",color:"#ef4444",borderRadius:20,padding:"1px 7px",fontSize:9,fontWeight:700}}>{sifat}</span></td>
                              <td style={{padding:"8px 10px"}}><span style={stl.badgeAkt(obj.aktual)}>{obj.aktual?"✅":"📊"}</span></td>
                            </tr>
                          ))}
                          <tr style={{borderTop:"2px solid #a855f733",background:"#a855f709"}}>
                            <td colSpan={3} style={{padding:"9px 10px",color:"#a855f7",fontWeight:800}}>TOTAL BY-PRODUCT (edible)</td>
                            <td style={stl.td("#f5c842",true)}>{+c.byProducts.reduce((s,b)=>s+b.beratKg,0).toFixed(2)} kg</td>
                            <td/><td/>
                            <td style={stl.td("#a855f7",true)}>{"Rp "+c.pendByP.toLocaleString("id-ID")}</td>
                            <td colSpan={2}/>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                </div>{/* end sub-tab content */}

                {rec.notes&&(
                  <div style={{background:"#ffffff05",border:"1px solid #1c1e2b",borderRadius:9,padding:"9px 13px",color:"#9097a8",fontSize:12}}>
                    📝 <strong style={{color:"#e2e4f0"}}>Catatan:</strong> {rec.notes}
                  </div>
                )}
              </div>{/* end panel kanan */}
            </div>
          );
        })()
      )}

      {/* ═══ TAB STANDAR ═══ */}
      {tab === "standar" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 13, padding: 18 }}>
            <div style={{ color: "#f5c842", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 12 }}>📊 Standar % Karkas per Ras</div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead><tr style={{ borderBottom: "1px solid #1c1e2b" }}>{["Ras", "Jantan (%)", "Betina (%)"].map(h => <th key={h} style={{ ...thS, color: "#f5c842" }}>{h}</th>)}</tr></thead>
                <tbody>{Object.entries(RPH_STANDAR.persen_karkas).filter(([k]) => k !== "default").map(([ras, v], i) => (
                  <tr key={ras} style={{ borderBottom: "1px solid #1c1e2b", background: i % 2 ? "#ffffff04" : "transparent" }}>
                    <td style={tdS("#e2e4f0", true)}>{ras}</td>
                    <td style={tdS("#22c55e", true)}>{v.jantan}%</td>
                    <td style={tdS("#60a5fa", true)}>{v.betina}%</td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
          </div>

          <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 13, padding: 18 }}>
            <div style={{ color: "#22c55e", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 6 }}>🥩 Harga Potongan Daging (Juni 2026)</div>
            <div style={{ fontSize: 11, color: "#555a6a", marginBottom: 12 }}>Sumber: PIHPS Nasional · Daging Semarang · Fadagi Meathouse · 5 Juni 2026</div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead><tr style={{ borderBottom: "1px solid #1c1e2b" }}>{["Potongan", "Grade", "%Karkas", "Harga/kg ★", "Kegunaan"].map(h => <th key={h} style={{ ...thS, color: "#22c55e" }}>{h}</th>)}</tr></thead>
                <tbody>
                  {RPH_STANDAR.potongan_primer.map((p, i) => {
                    const gc = gradeC(p.grade);
                    return (
                      <tr key={p.kode} style={{ borderBottom: "1px solid #1c1e2b", background: i % 2 ? "#ffffff04" : "transparent" }}>
                        <td style={tdS("#e2e4f0", true)}>{p.nama}</td>
                        <td style={{ padding: "8px 10px" }}><span style={{ background: gc + "15", color: gc, border: "1px solid " + gc + "28", borderRadius: 20, padding: "2px 7px", fontSize: 10, fontWeight: 700 }}>{p.grade}</span></td>
                        <td style={tdS("#9097a8")}>{p.pct}%</td>
                        <td style={tdS("#f5c842", true)}>{"Rp " + p.harga.toLocaleString("id-ID")}</td>
                        <td style={tdS("#555a6a")}><span style={{ fontSize: 11 }}>{p.ket}</span></td>
                      </tr>
                    );
                  })}
                  <tr style={{ borderTop: "2px solid #22c55e33", background: "#22c55e09" }}>
                    <td style={tdS("#9097a8", true)}>Tulang</td>
                    <td style={{ padding: "8px 10px" }}><span style={{ background: "#9097a815", color: "#9097a8", borderRadius: 20, padding: "2px 7px", fontSize: 10, fontWeight: 700 }}>By-product</span></td>
                    <td style={tdS("#9097a8")}>{RPH_STANDAR.pct_tulang}%</td>
                    <td style={tdS("#9097a8", true)}>{"Rp " + RPH_STANDAR.harga_tulang.toLocaleString("id-ID")}</td>
                    <td style={tdS("#555a6a")}>Kaldu, pakan, pupuk</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div style={{ marginTop: 14, background: "#f5c84208", border: "1px solid #f5c84222", borderRadius: 10, padding: 14 }}>
              <div style={{ color: "#f5c842", fontWeight: 700, fontSize: 12, marginBottom: 10 }}>📌 Referensi Harga Resmi (Juni 2026)</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(210px,1fr))", gap: 8 }}>
                {[["Karkas max distributor (Bapanas)", "Rp 107.000/kg", "#f5c842"], ["Retail kualitas 1 (PIHPS 5/6)", "Rp 141.650/kg", "#22c55e"], ["Retail kualitas 2", "~Rp 128.000/kg", "#3b82f6"], ["Has Dalam (Daging Semarang)", "Rp 165.000/kg", "#f5c842"], ["Has Luar / Topside / Knuckle", "Rp 155.000/kg", "#f5c842"], ["Sengkel/Kisi", "Rp 150.000/kg", "#9097a8"], ["HAP sapi feedlot (Kementan)", "Rp 55.000–56.000/kg BH", "#a855f7"], ["Buntut Import (Fadagi)", "Rp 172.000/kg", "#f59e0b"]].map(([k, v, c]) => (
                  <div key={k} style={{ background: "#ffffff06", borderRadius: 8, padding: "7px 11px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 10, color: "#9097a8" }}>{k}</span>
                    <span style={{ fontSize: 11, color: c, fontWeight: 700, whiteSpace: "nowrap" }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div style={{ background: "#0f1118", border: "1px solid #1c1e2b", borderRadius: 13, padding: 18 }}>
            <div style={{ color: "#a855f7", fontFamily: "'DM Serif Display',serif", fontSize: 14, marginBottom: 6 }}>🫀 Harga Jeroan & By-Product (Juni 2026)</div>
            <div style={{ fontSize: 11, color: "#555a6a", marginBottom: 12 }}>Sumber: Tokopedia · Blibli · Pasar Tradisional · Update Juni 2026</div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead><tr style={{ borderBottom: "1px solid #1c1e2b" }}>{["Produk", "Kategori", "Nama Latin", "%BH", "Harga/kg ★", "Keterangan"].map(h => <th key={h} style={{ ...thS, color: "#a855f7" }}>{h}</th>)}</tr></thead>
                <tbody>
                  {RPH_STANDAR.by_products.map((b, i) => {
                    const catC = { "Fancy Meat": "#f5c842", "Jeroan Merah": "#ef4444", "Jeroan Putih": "#9097a8", "Kulit/Darah": "#555a6a" };
                    const cc = catC[b.kat] || "#666";
                    return (
                      <tr key={b.nama} style={{ borderBottom: "1px solid #1c1e2b", background: i % 2 ? "#ffffff04" : "transparent" }}>
                        <td style={tdS("#e2e4f0", true)}>{b.nama}</td>
                        <td style={{ padding: "8px 10px" }}><span style={{ background: cc + "14", color: cc, border: "1px solid " + cc + "28", borderRadius: 20, padding: "2px 7px", fontSize: 9, fontWeight: 700 }}>{b.kat}</span></td>
                        <td style={tdS("#555a6a")}><i style={{ fontSize: 10 }}>{b.latin}</i></td>
                        <td style={tdS("#9097a8")}>{b.pct_live}%</td>
                        <td style={tdS("#a855f7", true)}>{"Rp " + b.harga.toLocaleString("id-ID")}</td>
                        <td style={tdS("#555a6a")}><span style={{ fontSize: 11 }}>{b.ket || "—"}</span></td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};


/* ================================================================
   DATA KARYAWAN & SHIFT
================================================================ */
const initialKaryawan = [
  {id:"K001",nama:"Budi Santoso",jabatan:"Mandor Kandang",shift:"Pagi",hp:"0812-1234-5678",gajiPokok:2500000,status:"Aktif",tglMasuk:"2023-01-10",kandang:"A,B",spesialisasi:"Broiler",catatan:""},
  {id:"K002",nama:"Siti Rahayu",jabatan:"Anak Kandang",shift:"Pagi",hp:"0813-2345-6789",gajiPokok:1800000,status:"Aktif",tglMasuk:"2024-03-01",kandang:"A",spesialisasi:"Broiler",catatan:""},
  {id:"K003",nama:"Agus Permana",jabatan:"Anak Kandang",shift:"Sore",hp:"0814-3456-7890",gajiPokok:1800000,status:"Aktif",tglMasuk:"2024-06-15",kandang:"B,C",spesialisasi:"Layer",catatan:""},
  {id:"K004",nama:"Diah Puspita",jabatan:"Admin Pakan",shift:"Pagi",hp:"0815-4567-8901",gajiPokok:2000000,status:"Aktif",tglMasuk:"2023-08-20",kandang:"Semua",spesialisasi:"Pakan",catatan:""},
  {id:"K005",nama:"Rudi Hartoyo",jabatan:"Mantri Kandang",shift:"Siang",hp:"0816-5678-9012",gajiPokok:3000000,status:"Aktif",tglMasuk:"2022-05-01",kandang:"Semua",spesialisasi:"Kesehatan",catatan:"Bersertifikat mantri hewan"},
];

/* ================================================================
   LOG HARIAN KANDANG
================================================================ */
const initialDailyLog = [
  {id:"DL001",tanggal:"2026-06-05",kandangId:"BR001",kandangNama:"Kandang A",matiPagi:2,matiSore:1,matiMalam:0,totalMati:3,suhuPagi:28,suhuSore:32,suhuMalam:27,kelembabanPagi:70,kelembabanSore:65,konsumsiPakan:285,konsumsiAir:620,amonia:"Rendah",ventilasi:"Baik",kondisiLitter:"Kering",catatan:"Normal",petugas:"Budi Santoso"},
  {id:"DL002",tanggal:"2026-06-05",kandangId:"BR002",kandangNama:"Kandang B",matiPagi:1,matiSore:0,matiMalam:1,totalMati:2,suhuPagi:27,suhuSore:31,suhuMalam:26,kelembabanPagi:68,kelembabanSore:62,konsumsiPakan:298,konsumsiAir:610,amonia:"Rendah",ventilasi:"Baik",kondisiLitter:"Kering",catatan:"D35 siap panen",petugas:"Agus Permana"},
  {id:"DL003",tanggal:"2026-06-04",kandangId:"BR001",kandangNama:"Kandang A",matiPagi:1,matiSore:2,matiMalam:0,totalMati:3,suhuPagi:29,suhuSore:33,suhuMalam:28,kelembabanPagi:72,kelembabanSore:67,konsumsiPakan:280,konsumsiAir:600,amonia:"Sedang",ventilasi:"Kurang",kondisiLitter:"Lembab",catatan:"Ventilasi perlu diperbaiki",petugas:"Budi Santoso"},
];

/* ================================================================
   INVOICE & NOTA PENJUALAN
================================================================ */
const initialInvoice = [
  {id:"INV001",nomorInvoice:"INV/2026/06/001",tanggal:"2026-06-01",pembeli:"PT Sinar Jaya",jenis:"Sapi Potong",detail:"Simental-01 340kg @ Rp 55.000/kg",jumlah:1,totalKg:340,hargaPerKg:55000,subtotal:18700000,ppn:0,totalTagihan:18700000,statusBayar:"Lunas",tglBayar:"2026-06-02",metodeBayar:"Transfer BRI",catatan:""},
  {id:"INV002",nomorInvoice:"INV/2026/06/002",tanggal:"2026-06-03",pembeli:"Jagal H. Mahmud",jenis:"Domba Potong",detail:"2 ekor Garut BB 45kg",jumlah:2,totalKg:90,hargaPerKg:48000,subtotal:4320000,ppn:0,totalTagihan:4320000,statusBayar:"Belum Lunas",tglBayar:"",metodeBayar:"Tunai",catatan:"DP 50% sudah diterima"},
  {id:"INV003",nomorInvoice:"INV/2026/06/003",tanggal:"2026-06-05",pembeli:"CV Ayam Mas",jenis:"Broiler Panen",detail:"1.850 ekor x 1.95kg x Rp 22.000",jumlah:1850,totalKg:3608,hargaPerKg:22000,subtotal:79371000,ppn:0,totalTagihan:79371000,statusBayar:"Proses",tglBayar:"",metodeBayar:"Transfer",catatan:"Panen D35"},
];

/* ================================================================
   HUTANG & PIUTANG
================================================================ */
const initialHutangPiutang = [
  {id:"HP001",tipe:"Hutang",pihak:"PT Japfa Comfeed",keperluan:"DOC Broiler Periode 14 — 2.050 ekor",jumlah:15375000,tglTransaksi:"2026-05-15",jatuhTempo:"2026-06-15",statusLunas:false,tglLunas:"",catatan:"Jatuh tempo 30 hari"},
  {id:"HP002",tipe:"Hutang",pihak:"Toko Sapronak",keperluan:"Pakan Starter BR-1 5 ton",jumlah:44000000,tglTransaksi:"2026-05-16",jatuhTempo:"2026-06-16",statusLunas:false,tglLunas:"",catatan:""},
  {id:"HP003",tipe:"Piutang",pihak:"Jagal H. Mahmud",keperluan:"Sisa bayar domba 2 ekor",jumlah:2160000,tglTransaksi:"2026-06-03",jatuhTempo:"2026-06-10",statusLunas:false,tglLunas:"",catatan:"DP sudah 50%"},
  {id:"HP004",tipe:"Hutang",pihak:"KUD Setempat",keperluan:"KUR Modal Sapi 5 ekor",jumlah:75000000,tglTransaksi:"2026-04-01",jatuhTempo:"2026-09-30",statusLunas:false,tglLunas:"",catatan:"Cicilan Rp 13jt/bulan"},
];

/* ================================================================
   BWS — Bobot Badan Standar vs Aktual
================================================================ */
const BWS_COBB500 = [
  {hari:7,standar:0.190},{hari:14,standar:0.440},{hari:21,standar:0.900},
  {hari:28,standar:1.520},{hari:35,standar:2.100},{hari:42,standar:2.650},
];
const BWS_ROSS308 = [
  {hari:7,standar:0.200},{hari:14,standar:0.460},{hari:21,standar:0.940},
  {hari:28,standar:1.590},{hari:35,standar:2.190},{hari:42,standar:2.730},
];
const BWS_LOHMANN = [
  {minggu:6,standar:0.470},{minggu:8,standar:0.600},{minggu:10,standar:0.720},
  {minggu:12,standar:0.870},{minggu:14,standar:0.990},{minggu:16,standar:1.100},
  {minggu:18,standar:1.510},{minggu:20,standar:1.620},{minggu:72,standar:1.850},
];


/* ================================================================
   PageKaryawan — SDM & Jadwal Shift
================================================================ */
const PageKaryawan = ({ karyawan=[], setKaryawan, absensi=[], setAbsensi }) => {
  const AC = "#60a5fa";
  const blank = {id:"",nama:"",jabatan:"Anak Kandang",shift:"Pagi",hp:"",gajiPokok:"",status:"Aktif",tglMasuk:new Date().toISOString().split("T")[0],kandang:"",spesialisasi:"",catatan:""};
  const [form, setForm] = useState({...blank});
  const [tabKar, setTabKar] = React.useState("data");
  const [modal, setModal] = useState(false);
  const [editId, setEditId] = useState(null);
  const [search, setSearch] = useState("");

  const save = () => {
    if (!form.nama) return;
    if (editId) {
      setKaryawan(karyawan.map(k => k.id===editId ? {...form} : k));
    } else {
      const id = "K" + String(Date.now()).slice(-4);
      setKaryawan([...karyawan, {...form, id}]);
    }
    setModal(false); setEditId(null); setForm({...blank});
  };

  const totalGaji = karyawan.filter(k=>k.status==="Aktif").reduce((s,k)=>s+(parseInt(k.gajiPokok)||0),0);
  const filtered = karyawan.filter(k => k.nama.toLowerCase().includes(search.toLowerCase()) || k.jabatan.toLowerCase().includes(search.toLowerCase()));
  const shiftGroups = {Pagi:0,Sore:0,Siang:0,Malam:0};
  karyawan.forEach(k=>{if(shiftGroups[k.shift]!==undefined) shiftGroups[k.shift]++;});

  return (
    <div style={S.col}>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))",gap:10}}>
        <KartuStat label="Total Karyawan" value={karyawan.filter(k=>k.status==="Aktif").length+" orang"} color={AC} icon="chart"/>
        <KartuStat label="Total Gaji/Bln" value={rp(totalGaji)} color="#22c55e" icon="biaya"/>
        {Object.entries(shiftGroups).filter(([,v])=>v>0).map(([s,n])=>(
          <KartuStat key={s} label={"Shift "+s} value={n+" orang"} color="#f59e0b" icon="chart"/>
        ))}
      </div>

      {/* Jadwal Shift Visual */}
      <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
        <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:12}}>📅 Jadwal Shift Hari Ini</div>
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))",gap:8}}>
          {["Pagi","Siang","Sore","Malam"].map(s=>{
            const pegawai = karyawan.filter(k=>k.shift===s&&k.status==="Aktif");
            const shiftColor = {Pagi:"#f59e0b",Siang:"#f97316",Sore:"#60a5fa",Malam:"#a855f7"}[s];
            return (
              <div key={s} style={{background:shiftColor+"0a",border:"1px solid "+shiftColor+"20",borderRadius:10,padding:12}}>
                <div style={{color:shiftColor,fontWeight:700,fontSize:12,marginBottom:6}}>
                  🕐 Shift {s} ({pegawai.length} orang)
                </div>
                {pegawai.length===0 ? <div style={{color:"#555a6a",fontSize:11}}>Kosong</div> :
                  pegawai.map(p=>(
                    <div key={p.id} style={{fontSize:11,color:"#e2e4f0",padding:"3px 0",borderBottom:"1px solid "+shiftColor+"18"}}>
                      {p.nama} — <span style={{color:"#9097a8"}}>{p.jabatan}</span>
                    </div>
                  ))}
              </div>
            );
          })}
        </div>
      </div>

      {/* Tabs */}
      <div style={{display:"flex",gap:6,borderBottom:"1px solid #1c1e2b",marginBottom:2}}>
        {[{id:"data",l:"👥 Karyawan"},{id:"absensi",l:"📅 Absensi"},{id:"gaji",l:"💰 Penggajian"}].map(t=>(
          <button key={t.id} onClick={()=>setTabKar(t.id)}
            style={{background:"none",border:"none",borderBottom:"2px solid "+(tabKar===t.id?AC:"transparent"),color:tabKar===t.id?AC:"#555a6a",padding:"8px 14px",cursor:"pointer",fontWeight:700,fontSize:12,marginBottom:-1}}>
            {t.l}
          </button>
        ))}
      </div>

      {/* Absensi Tab */}
      {tabKar==="absensi" && (
        <div style={S.col}>
          <div style={{...S.row,justifyContent:"space-between",flexWrap:"wrap",gap:8}}>
            <div style={{display:"flex",gap:8,alignItems:"center"}}>
              <input type="date" defaultValue={new Date().toISOString().split("T")[0]} id="absDate"
                style={{background:"#13161f",border:"1px solid "+AC+"40",borderRadius:8,padding:"6px 10px",color:AC,fontSize:12}}/>
              <span style={{fontSize:11,color:"#555a6a"}}>
                Hadir: <b style={{color:"#22c55e"}}>{(absensi||[]).filter(a=>a.tanggal===new Date().toISOString().split("T")[0]&&a.status==="Hadir").length}</b>
                {" "}| Izin: <b style={{color:"#f59e0b"}}>{(absensi||[]).filter(a=>a.tanggal===new Date().toISOString().split("T")[0]&&a.status!=="Hadir").length}</b>
              </span>
            </div>
            <BtnSec color={AC} onClick={()=>{
              const d = document.getElementById("absDate")?.value || new Date().toISOString().split("T")[0];
              const missingAbs = karyawan.filter(k=>k.status==="Aktif"&&!(absensi||[]).find(a=>a.karyawanId===k.id&&a.tanggal===d));
              missingAbs.forEach(k=>{
                const newAbs = {id:"AB"+Date.now()+k.id,karyawanId:k.id,nama:k.nama,tanggal:d,status:"Hadir",jamMasuk:"",jamKeluar:"",catatan:""};
                setAbsensi(prev=>[...prev,newAbs]);
              });
            }}>+ Absen Massal Hari Ini</BtnSec>
          </div>
          <TableWrap>
            <thead><tr>{["Tanggal","Nama","Jabatan","Status","Jam Masuk","Jam Keluar","Catatan","Aksi"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
            <tbody>
              {(absensi||[]).slice(0,30).map((a,i)=>(
                <TR key={a.id} i={i} color={AC}>
                  <TD color={C.dim}>{a.tanggal}</TD>
                  <TD bold>{a.nama}</TD>
                  <TD color={C.muted}>{karyawan?.find(k=>k.id===a.karyawanId)?.jabatan||"—"}</TD>
                  <td style={S.td}><Badge text={a.status}/></td>
                  <TD color={C.muted}>{a.jamMasuk||"—"}</TD>
                  <TD color={C.muted}>{a.jamKeluar||"—"}</TD>
                  <TD color={C.muted}>{a.catatan||"—"}</TD>
                  <td style={S.td}>
                    <select value={a.status} onChange={e=>setAbsensi((absensi||[]).map(x=>x.id===a.id?{...x,status:e.target.value}:x))}
                      style={{background:"#13161f",border:"1px solid #252535",borderRadius:5,color:"#e2e4f0",fontSize:10,padding:"2px 4px"}}>
                      {["Hadir","Izin","Sakit","Alpha","Cuti"].map(s=><option key={s}>{s}</option>)}
                    </select>
                  </td>
                </TR>
              ))}
            </tbody>
          </TableWrap>
        </div>
      )}

      {/* Penggajian Tab */}
      {tabKar==="gaji" && (
        <div style={S.col}>
          <div style={{background:"#0f1118",border:"1px solid #1c1e2b",borderRadius:13,padding:16}}>
            <div style={{color:AC,fontFamily:"'DM Serif Display',serif",fontSize:14,marginBottom:12}}>💰 Rekap Penggajian Bulan Ini</div>
            <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(160px,1fr))",gap:10,marginBottom:14}}>
              <div style={{background:"#22c55e0a",border:"1px solid #22c55e20",borderRadius:9,padding:12}}>
                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>Total Gaji Pokok</div>
                <div style={{color:"#22c55e",fontWeight:800,fontSize:16,marginTop:4}}>{rp(karyawan.filter(k=>k.status==="Aktif").reduce((s,k)=>s+(parseInt(k.gajiPokok)||0),0))}</div>
              </div>
              <div style={{background:"#60a5fa0a",border:"1px solid #60a5fa20",borderRadius:9,padding:12}}>
                <div style={{fontSize:9,color:"#555a6a",fontWeight:700,textTransform:"uppercase"}}>Karyawan Aktif</div>
                <div style={{color:"#60a5fa",fontWeight:800,fontSize:16,marginTop:4}}>{karyawan.filter(k=>k.status==="Aktif").length} orang</div>
              </div>
            </div>
            <TableWrap>
              <thead><tr>{["Nama","Jabatan","Shift","Gaji Pokok","Kehadiran","Est. Gaji","Status"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
              <tbody>
                {karyawan.filter(k=>k.status==="Aktif").map((k,i)=>{
                  const bln = new Date().toISOString().slice(0,7);
                  const hadirBulan = (absensi||[]).filter(a=>a.karyawanId===k.id&&a.tanggal.startsWith(bln)&&a.status==="Hadir").length;
                  const hariKerja = 26;
                  const gajiEst = Math.round((parseInt(k.gajiPokok)||0) * Math.min(1, hadirBulan/hariKerja));
                  return (
                    <TR key={k.id} i={i} color={AC}>
                      <TD bold>{k.nama}</TD>
                      <TD color={C.muted}>{k.jabatan}</TD>
                      <td style={S.td}><Badge text={k.shift}/></td>
                      <TD color="#22c55e">{rp(k.gajiPokok)}</TD>
                      <TD color={C.muted}>{hadirBulan}/{hariKerja} hari</TD>
                      <TD color="#f59e0b" bold>{rp(gajiEst)}</TD>
                      <td style={S.td}><Badge text="Belum Bayar"/></td>
                    </TR>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      {tabKar==="data" && (<div style={S.col}>
      {/* Toolbar */}
      <div style={{...S.row,justifyContent:"space-between",flexWrap:"wrap",gap:8}}>
        <Cari value={search} onChange={setSearch} placeholder="Cari nama / jabatan..."/>
        <BtnSec onClick={()=>{setForm({...blank});setEditId(null);setModal(true);}} color={AC}>
          <Ico n="plus" size={13} color={AC}/> Tambah Karyawan
        </BtnSec>
      </div>

      {/* Tabel */}
      <TableWrap>
        <thead><tr>{["ID","Nama","Jabatan","Shift","HP","Gaji/Bln","Kandang","Status","Aksi"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
        <tbody>
          {filtered.map((k,i)=>(
            <TR key={k.id} i={i} color={AC}>
              <TD color={C.dim} mono>{k.id}</TD>
              <TD bold>{k.nama}</TD>
              <TD color={C.muted}>{k.jabatan}</TD>
              <td style={S.td}><Badge text={k.shift}/></td>
              <TD color={C.dim}>{k.hp}</TD>
              <TD color="#22c55e" bold>{rp(k.gajiPokok)}</TD>
              <TD color={C.muted}>{k.kandang}</TD>
              <td style={S.td}><Badge text={k.status}/></td>
              <td style={S.td}>
                <div style={{display:"flex",gap:5}}>
                  <BtnSec onClick={()=>{setForm({...k});setEditId(k.id);setModal(true);}} color={AC} small>Edit</BtnSec>
                  <BtnSec onClick={()=>{if(window.confirm("Hapus?"))setKaryawan(karyawan.filter(x=>x.id!==k.id));}} color={C.expense} small>Hapus</BtnSec>
                </div>
              </td>
            </TR>
          ))}
        </tbody>
      </TableWrap>

      </div>)}
      {modal && (
        <Modal title={editId?"Edit Karyawan":"Tambah Karyawan"} onClose={()=>setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Nama Lengkap" value={form.nama} onChange={v=>setForm({...form,nama:v})} required span/>
            <Inp label="Jabatan" value={form.jabatan} onChange={v=>setForm({...form,jabatan:v})} options={["Mandor Kandang","Anak Kandang","Admin Pakan","Mantri Kandang","Sopir","Satpam","Admin Keuangan","Manager Farm"]}/>
            <Inp label="Shift" value={form.shift} onChange={v=>setForm({...form,shift:v})} options={["Pagi","Siang","Sore","Malam"]}/>
            <Inp label="No. HP" value={form.hp} onChange={v=>setForm({...form,hp:v})}/>
            <Inp label="Gaji Pokok (Rp)" value={form.gajiPokok} onChange={v=>setForm({...form,gajiPokok:v})} type="number"/>
            <Inp label="Tanggal Masuk" value={form.tglMasuk} onChange={v=>setForm({...form,tglMasuk:v})} type="date"/>
            <Inp label="Kandang Tanggung Jawab" value={form.kandang} onChange={v=>setForm({...form,kandang:v})} placeholder="A, B, C"/>
            <Inp label="Spesialisasi" value={form.spesialisasi} onChange={v=>setForm({...form,spesialisasi:v})} options={["Broiler","Layer","Sapi","Domba","Pakan","Kesehatan"]}/>
            <Inp label="Status" value={form.status} onChange={v=>setForm({...form,status:v})} options={["Aktif","Cuti","Resign","Kontrak"]}/>
            <Textarea label="Catatan" value={form.catatan} onChange={v=>setForm({...form,catatan:v})} span/>
          </div>
          <BtnPrimary onClick={save} color={AC} full>Simpan</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ================================================================
   PageHutangPiutang — Invoice, Hutang & Piutang
================================================================ */
const PageHutangPiutang = ({ invoices=[], setInvoices, hutangPiutang=[], setHutangPiutang }) => {
  const AC = "#f59e0b";
  const [tab, setTab] = useState("invoice");
  const [modal, setModal] = useState(false);
  const [editId, setEditId] = useState(null);
  const blankInv = {id:"",nomorInvoice:"",tanggal:new Date().toISOString().split("T")[0],pembeli:"",jenis:"Sapi Potong",detail:"",jumlah:0,totalKg:0,hargaPerKg:0,subtotal:0,ppn:0,totalTagihan:0,statusBayar:"Proses",tglBayar:"",metodeBayar:"Transfer",catatan:""};
  const blankHP  = {id:"",tipe:"Hutang",pihak:"",keperluan:"",jumlah:0,tglTransaksi:new Date().toISOString().split("T")[0],jatuhTempo:"",statusLunas:false,tglLunas:"",catatan:""};
  const [formInv, setFormInv] = useState({...blankInv});
  const [formHP,  setFormHP]  = useState({...blankHP});

  const totalPiutang = (hutangPiutang||[]).filter(h=>h.tipe==="Piutang"&&!h.statusLunas).reduce((s,h)=>s+h.jumlah,0);
  const totalHutang  = (hutangPiutang||[]).filter(h=>h.tipe==="Hutang"&&!h.statusLunas).reduce((s,h)=>s+h.jumlah,0);
  const totalInvoice = (invoices||[]).reduce((s,i)=>s+i.totalTagihan,0);
  const invoiceLunas = (invoices||[]).filter(i=>i.statusBayar==="Lunas").reduce((s,i)=>s+i.totalTagihan,0);
  const today = new Date();
  const jatuhTempo7 = (hutangPiutang||[]).filter(h=>{
    if(h.statusLunas||!h.jatuhTempo) return false;
    const d=new Date(h.jatuhTempo); return (d-today)/86400000<=7 && d>=today;
  });

  const saveInv = () => {
    const sub = (formInv.totalKg||formInv.jumlah) * (formInv.hargaPerKg||0);
    const inv = {...formInv, subtotal:sub, totalTagihan:sub+(parseInt(formInv.ppn)||0)};
    if(editId) { setInvoices(invoices.map(i=>i.id===editId?inv:i)); }
    else { setInvoices([...invoices,{...inv,id:"INV"+Date.now()}]); }
    setModal(false); setEditId(null); setFormInv({...blankInv});
  };
  const saveHP = () => {
    if(editId) { setHutangPiutang(hutangPiutang.map(h=>h.id===editId?{...formHP}:h)); }
    else { setHutangPiutang([...hutangPiutang,{...formHP,id:"HP"+Date.now()}]); }
    setModal(false); setEditId(null); setFormHP({...blankHP});
  };

  return (
    <div style={S.col}>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))",gap:10}}>
        <KartuStat label="Total Invoice" value={rp(totalInvoice)} sub={invoices.length+" nota"} color={AC} icon="jual"/>
        <KartuStat label="Sudah Terbayar" value={rp(invoiceLunas)} color="#22c55e" icon="jual"/>
        <KartuStat label="Total Hutang" value={rp(totalHutang)} color="#ef4444" icon="biaya"/>
        <KartuStat label="Total Piutang" value={rp(totalPiutang)} color="#f97316" icon="laporan"/>
        {jatuhTempo7.length>0 && <KartuStat label="Jatuh Tempo 7hr" value={jatuhTempo7.length+" item"} color="#ef4444" icon="warn"/>}
      </div>

      {/* Alert jatuh tempo */}
      {jatuhTempo7.length>0 && (
        <div style={{background:"#ef444408",border:"1px solid #ef444425",borderRadius:10,padding:12}}>
          <div style={{color:"#ef4444",fontWeight:700,fontSize:13,marginBottom:8}}>⚠️ Jatuh Tempo dalam 7 Hari!</div>
          {jatuhTempo7.map(h=>(
            <div key={h.id} style={{display:"flex",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid #ef444415",fontSize:11}}>
              <span style={{color:"#e2e4f0"}}>{h.tipe==="Hutang"?"🔴":"🟡"} {h.pihak} — {h.keperluan?.substring(0,40)}</span>
              <span style={{color:"#ef4444",fontWeight:700}}>{rp(h.jumlah)} · Jatuh: {h.jatuhTempo}</span>
            </div>
          ))}
        </div>
      )}

      {/* Tabs */}
      <div style={{display:"flex",gap:8,borderBottom:"1px solid #1c1e2b"}}>
        {[{id:"invoice",l:"🧾 Invoice/Nota"},{id:"hutang",l:"💸 Hutang & Piutang"}].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            style={{background:"none",border:"none",borderBottom:"2px solid "+(tab===t.id?AC:"transparent"),color:tab===t.id?AC:"#555a6a",padding:"8px 16px",cursor:"pointer",fontWeight:700,fontSize:13,marginBottom:-1}}>
            {t.l}
          </button>
        ))}
        <BtnSec onClick={()=>{setEditId(null);if(tab==="invoice"){setFormInv({...blankInv});}else{setFormHP({...blankHP});}setModal(true);}} color={AC} style={{marginLeft:"auto"}}>
          <Ico n="plus" size={13} color={AC}/> Tambah {tab==="invoice"?"Invoice":"Hutang/Piutang"}
        </BtnSec>
      </div>

      {tab==="invoice" && (
        <TableWrap>
          <thead><tr>{["No. Invoice","Tanggal","Pembeli","Jenis","Detail","Total","Status","Bayar","Aksi"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
          <tbody>
            {invoices.map((inv,i)=>(
              <TR key={inv.id} i={i} color={AC}>
                <TD mono color={C.dim}>{inv.nomorInvoice}</TD>
                <TD color={C.dim}>{inv.tanggal}</TD>
                <TD bold>{inv.pembeli}</TD>
                <td style={S.td}><Badge text={inv.jenis}/></td>
                <TD color={C.muted}>{inv.detail?.substring(0,40)}</TD>
                <TD bold color={AC}>{rp(inv.totalTagihan)}</TD>
                <td style={S.td}><Badge text={inv.statusBayar} /></td>
                <TD color={C.muted}>{inv.metodeBayar}</TD>
                <td style={S.td}>
                  <div style={{display:"flex",gap:4}}>
                    {inv.statusBayar!=="Lunas" && <BtnSec small color="#22c55e" onClick={()=>setInvoices(invoices.map(x=>x.id===inv.id?{...x,statusBayar:"Lunas",tglBayar:new Date().toISOString().split("T")[0]}:x))}>✓ Lunas</BtnSec>}
                    <BtnSec small color="#ef4444" onClick={()=>{if(window.confirm("Hapus?"))setInvoices(invoices.filter(x=>x.id!==inv.id));}}>Hapus</BtnSec>
                  </div>
                </td>
              </TR>
            ))}
          </tbody>
        </TableWrap>
      )}

      {tab==="hutang" && (
        <TableWrap>
          <thead><tr>{["Tipe","Pihak","Keperluan","Jumlah","Tgl Transaksi","Jatuh Tempo","Status","Aksi"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
          <tbody>
            {hutangPiutang.map((h,i)=>{
              const jt=h.jatuhTempo?new Date(h.jatuhTempo):null;
              const overdue=jt&&!h.statusLunas&&jt<new Date();
              return (
                <TR key={h.id} i={i} color={AC}>
                  <td style={S.td}><Badge text={h.tipe} /></td>
                  <TD bold>{h.pihak}</TD>
                  <TD color={C.muted}>{h.keperluan?.substring(0,40)}</TD>
                  <TD bold color={h.tipe==="Hutang"?"#ef4444":"#f97316"}>{rp(h.jumlah)}</TD>
                  <TD color={C.dim}>{h.tglTransaksi}</TD>
                  <TD color={overdue?"#ef4444":C.muted}>{h.jatuhTempo||"—"}{overdue?" ⚠️":""}</TD>
                  <td style={S.td}><Badge text={h.statusLunas?"Lunas":"Belum Lunas"}/></td>
                  <td style={S.td}>
                    <div style={{display:"flex",gap:4}}>
                      {!h.statusLunas && <BtnSec small color="#22c55e" onClick={()=>setHutangPiutang(hutangPiutang.map(x=>x.id===h.id?{...x,statusLunas:true,tglLunas:new Date().toISOString().split("T")[0]}:x))}>✓ Lunas</BtnSec>}
                      <BtnSec small color="#ef4444" onClick={()=>{if(window.confirm("Hapus?"))setHutangPiutang(hutangPiutang.filter(x=>x.id!==h.id));}}>Hapus</BtnSec>
                    </div>
                  </td>
                </TR>
              );
            })}
          </tbody>
        </TableWrap>
      )}

      {modal && tab==="invoice" && (
        <Modal title={editId?"Edit Invoice":"Buat Invoice"} onClose={()=>setModal(false)}>
          <div style={S.grid2}>
            <Inp label="No. Invoice" value={formInv.nomorInvoice} onChange={v=>setFormInv({...formInv,nomorInvoice:v})} placeholder="INV/2026/06/001" span/>
            <Inp label="Tanggal" value={formInv.tanggal} onChange={v=>setFormInv({...formInv,tanggal:v})} type="date"/>
            <Inp label="Pembeli" value={formInv.pembeli} onChange={v=>setFormInv({...formInv,pembeli:v})}/>
            <Inp label="Jenis" value={formInv.jenis} onChange={v=>setFormInv({...formInv,jenis:v})} options={["Sapi Potong","Domba Potong","Broiler","Telur","Susu","Lainnya"]}/>
            <Inp label="Detail" value={formInv.detail} onChange={v=>setFormInv({...formInv,detail:v})} span/>
            <Inp label="Total Kg / Ekor" value={formInv.totalKg} onChange={v=>setFormInv({...formInv,totalKg:+v})} type="number"/>
            <Inp label="Harga/kg atau /ekor (Rp)" value={formInv.hargaPerKg} onChange={v=>setFormInv({...formInv,hargaPerKg:+v,subtotal:(formInv.totalKg||formInv.jumlah)*+v,totalTagihan:(formInv.totalKg||formInv.jumlah)*+v})} type="number"/>
            <Inp label="Status Bayar" value={formInv.statusBayar} onChange={v=>setFormInv({...formInv,statusBayar:v})} options={["Proses","Lunas","Belum Lunas","DP"]}/>
            <Inp label="Metode Bayar" value={formInv.metodeBayar} onChange={v=>setFormInv({...formInv,metodeBayar:v})} options={["Transfer","Tunai","DP+Pelunasan","Kredit"]}/>
            <Textarea label="Catatan" value={formInv.catatan} onChange={v=>setFormInv({...formInv,catatan:v})} span/>
          </div>
          <div style={{background:"#22c55e0a",border:"1px solid #22c55e20",borderRadius:8,padding:10,marginBottom:12,fontSize:12}}>
            <span style={{color:"#22c55e",fontWeight:700}}>Total Tagihan: </span>
            <span style={{color:"#22c55e",fontWeight:800,fontSize:14}}>{rp((formInv.totalKg||formInv.jumlah)*(formInv.hargaPerKg||0))}</span>
          </div>
          <BtnPrimary onClick={saveInv} color={AC} full>Simpan Invoice</BtnPrimary>
        </Modal>
      )}
      {modal && tab==="hutang" && (
        <Modal title="Tambah Hutang / Piutang" onClose={()=>setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Tipe" value={formHP.tipe} onChange={v=>setFormHP({...formHP,tipe:v})} options={["Hutang","Piutang"]}/>
            <Inp label="Pihak" value={formHP.pihak} onChange={v=>setFormHP({...formHP,pihak:v})}/>
            <Inp label="Keperluan" value={formHP.keperluan} onChange={v=>setFormHP({...formHP,keperluan:v})} span/>
            <Inp label="Jumlah (Rp)" value={formHP.jumlah} onChange={v=>setFormHP({...formHP,jumlah:+v})} type="number"/>
            <Inp label="Tgl Transaksi" value={formHP.tglTransaksi} onChange={v=>setFormHP({...formHP,tglTransaksi:v})} type="date"/>
            <Inp label="Jatuh Tempo" value={formHP.jatuhTempo} onChange={v=>setFormHP({...formHP,jatuhTempo:v})} type="date"/>
            <Textarea label="Catatan" value={formHP.catatan} onChange={v=>setFormHP({...formHP,catatan:v})} span/>
          </div>
          <BtnPrimary onClick={saveHP} color={AC} full>Simpan</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};

/* ================================================================
   PageLogHarian — Log Harian Kandang (Mortalitas, Suhu, Pakan)
================================================================ */
const PageLogHarian = ({ dailyLog=[], setDailyLog, broilerFlocks=[], layerFlocks=[] }) => {
  const AC = "#06b6d4";
  const allFlocks = [...(broilerFlocks||[]), ...(layerFlocks||[])];
  const blank = {id:"",tanggal:new Date().toISOString().split("T")[0],kandangId:"",kandangNama:"",matiPagi:0,matiSore:0,matiMalam:0,totalMati:0,suhuPagi:"",suhuSore:"",suhuMalam:"",kelembabanPagi:"",kelembabanSore:"",konsumsiPakan:"",konsumsiAir:"",amonia:"Rendah",ventilasi:"Baik",kondisiLitter:"Kering",catatan:"",petugas:""};
  const [form, setForm] = useState({...blank});
  const [modal, setModal] = useState(false);
  const [filterKandang, setFilterKandang] = useState("Semua");

  const save = () => {
    const total = (parseInt(form.matiPagi)||0)+(parseInt(form.matiSore)||0)+(parseInt(form.matiMalam)||0);
    const entry = {...form, id:"DL"+Date.now(), totalMati:total};
    setDailyLog([entry, ...dailyLog]);
    setModal(false); setForm({...blank});
  };

  const filtered = filterKandang==="Semua" ? (dailyLog||[]) : (dailyLog||[]).filter(l=>l.kandangId===filterKandang);
  const totalMatiToday = (dailyLog||[]).filter(l=>l.tanggal===new Date().toISOString().split("T")[0]).reduce((s,l)=>s+(l.totalMati||0),0);
  const avgSuhu = (dailyLog||[]).length ? ((dailyLog||[]).slice(0,5).reduce((s,l)=>s+(parseFloat(l.suhuSore)||0),0)/Math.min(dailyLog.length,5)).toFixed(1) : 0;

  return (
    <div style={S.col}>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))",gap:10}}>
        <KartuStat label="Log Hari Ini" value={dailyLog.filter(l=>l.tanggal===new Date().toISOString().split("T")[0]).length+" kandang"} color={AC} icon="chart"/>
        <KartuStat label="Total Mati Hari Ini" value={totalMatiToday+" ekor"} color={totalMatiToday>10?"#ef4444":"#22c55e"} icon="warn"/>
        <KartuStat label="Suhu Rata Sore" value={avgSuhu+"°C"} color={avgSuhu>32?"#ef4444":"#22c55e"} icon="chart"/>
        <KartuStat label="Total Record" value={dailyLog.length} color={C.info} icon="laporan"/>
      </div>

      <div style={{...S.row,justifyContent:"space-between",flexWrap:"wrap",gap:8}}>
        <select value={filterKandang} onChange={e=>setFilterKandang(e.target.value)}
          style={{background:"#13161f",border:"1px solid #252535",borderRadius:9,padding:"8px 12px",color:"#e2e4f0",fontSize:12}}>
          <option value="Semua">Semua Kandang</option>
          {allFlocks.map(f=><option key={f.id} value={f.id}>{f.name}</option>)}
        </select>
        <BtnSec onClick={()=>{setForm({...blank});setModal(true);}} color={AC}>
          <Ico n="plus" size={13} color={AC}/> Catat Log Harian
        </BtnSec>
      </div>

      <TableWrap>
        <thead><tr>{["Tanggal","Kandang","Mati Pg","Mati Sr","Mati Ml","Total DO","Suhu Sr°C","RH Sr%","Pakan kg","Air L","Amonia","Ventilasi","Litter","Petugas","Ket"].map(h=><TH key={h} color={AC}>{h}</TH>)}</tr></thead>
        <tbody>
          {filtered.length===0 ? <tr><td colSpan={15}><Empty/></td></tr> :
            filtered.map((l,i)=>(
              <TR key={l.id} i={i} color={AC}>
                <TD color={C.dim}>{l.tanggal}</TD>
                <TD bold>{l.kandangNama}</TD>
                <TD color={C.dim}>{l.matiPagi}</TD>
                <TD color={C.dim}>{l.matiSore}</TD>
                <TD color={C.dim}>{l.matiMalam}</TD>
                <TD color={(l.totalMati||0)>5?"#ef4444":"#22c55e"} bold>{l.totalMati||0}</TD>
                <TD color={(parseFloat(l.suhuSore)||0)>32?"#ef4444":"#22c55e"}>{l.suhuSore||"—"}</TD>
                <TD color={C.muted}>{l.kelembabanSore||"—"}</TD>
                <TD color={C.muted}>{l.konsumsiPakan||"—"}</TD>
                <TD color={C.muted}>{l.konsumsiAir||"—"}</TD>
                <td style={S.td}><Badge text={l.amonia||"—"}/></td>
                <td style={S.td}><Badge text={l.ventilasi||"—"}/></td>
                <td style={S.td}><Badge text={l.kondisiLitter||"—"}/></td>
                <TD color={C.muted}>{l.petugas}</TD>
                <TD color={C.muted}>{l.catatan?.substring(0,25)}</TD>
              </TR>
            ))}
        </tbody>
      </TableWrap>

      {modal && (
        <Modal title="Catat Log Harian Kandang" onClose={()=>setModal(false)}>
          <div style={S.grid2}>
            <Inp label="Tanggal" value={form.tanggal} onChange={v=>setForm({...form,tanggal:v})} type="date"/>
            <div style={{gridColumn:"1/-1"}}>
              <label style={{...S.label}}>Pilih Kandang</label>
              <select value={form.kandangId} onChange={e=>{const f=allFlocks?.find(x=>x.id===e.target.value);setForm({...form,kandangId:e.target.value,kandangNama:f?f.name:e.target.value});}}
                style={{...S.select,width:"100%"}}>
                <option value="">-- Pilih --</option>
                {allFlocks.map(f=><option key={f.id} value={f.id}>{f.name}</option>)}
              </select>
            </div>
            <Inp label="Mati Pagi (ekor)" value={form.matiPagi} onChange={v=>setForm({...form,matiPagi:+v})} type="number"/>
            <Inp label="Mati Sore (ekor)" value={form.matiSore} onChange={v=>setForm({...form,matiSore:+v})} type="number"/>
            <Inp label="Mati Malam (ekor)" value={form.matiMalam} onChange={v=>setForm({...form,matiMalam:+v})} type="number"/>
            <Inp label="Suhu Sore (°C)" value={form.suhuSore} onChange={v=>setForm({...form,suhuSore:v})} type="number"/>
            <Inp label="RH Sore (%)" value={form.kelembabanSore} onChange={v=>setForm({...form,kelembabanSore:v})} type="number"/>
            <Inp label="Konsumsi Pakan (kg)" value={form.konsumsiPakan} onChange={v=>setForm({...form,konsumsiPakan:v})} type="number"/>
            <Inp label="Konsumsi Air (L)" value={form.konsumsiAir} onChange={v=>setForm({...form,konsumsiAir:v})} type="number"/>
            <Inp label="Amonia" value={form.amonia} onChange={v=>setForm({...form,amonia:v})} options={["Rendah","Sedang","Tinggi","Sangat Tinggi"]}/>
            <Inp label="Kondisi Ventilasi" value={form.ventilasi} onChange={v=>setForm({...form,ventilasi:v})} options={["Baik","Kurang","Buruk"]}/>
            <Inp label="Kondisi Litter" value={form.kondisiLitter} onChange={v=>setForm({...form,kondisiLitter:v})} options={["Kering","Lembab","Basah","Caking"]}/>
            <Inp label="Petugas" value={form.petugas} onChange={v=>setForm({...form,petugas:v})}/>
            <Textarea label="Catatan" value={form.catatan} onChange={v=>setForm({...form,catatan:v})} span/>
          </div>
          <BtnPrimary onClick={save} color={AC} full>Simpan Log</BtnPrimary>
        </Modal>
      )}
    </div>
  );
};


/* ================================================================
   ANGGARAN BULANAN
================================================================ */
const initialAnggaran = [
  {id:"ANG001",bulan:"2026-06",kategori:"Pakan",anggaran:45000000,realisasi:41250000,ket:"Pakan sapi+domba+broiler+layer"},
  {id:"ANG002",bulan:"2026-06",kategori:"DOC",anggaran:16000000,realisasi:15375000,ket:"DOC Cobb 500 Kandang D"},
  {id:"ANG003",bulan:"2026-06",kategori:"Kesehatan",anggaran:3000000,realisasi:2200000,ket:"Obat, vaksin, layanan drh"},
  {id:"ANG004",bulan:"2026-06",kategori:"Tenaga Kerja",anggaran:12000000,realisasi:12000000,ket:"Gaji + bonus panen"},
  {id:"ANG005",bulan:"2026-06",kategori:"Listrik & Air",anggaran:4500000,realisasi:3830000,ket:"2 kandang broiler + 3 layer"},
  {id:"ANG006",bulan:"2026-06",kategori:"Kandang & Peralatan",anggaran:2000000,realisasi:750000,ket:"Perawatan rutin"},
  {id:"ANG007",bulan:"2026-06",kategori:"Transportasi",anggaran:2500000,realisasi:500000,ket:"Angkut ternak & produksi"},
  {id:"ANG008",bulan:"2026-05",kategori:"Pakan",anggaran:45000000,realisasi:43500000,ket:""},
  {id:"ANG009",bulan:"2026-05",kategori:"DOC",anggaran:16000000,realisasi:15840000,ket:"DOC Kandang F"},
  {id:"ANG010",bulan:"2026-05",kategori:"Kesehatan",anggaran:3000000,realisasi:3720000,ket:"Melebihi anggaran — CRD outbreak"},
];

/* ================================================================
   ABSENSI KARYAWAN
================================================================ */
const initialAbsensi = [
  {id:"AB001",karyawanId:"K001",nama:"Budi Santoso",tanggal:"2026-06-05",status:"Hadir",jamMasuk:"05:30",jamKeluar:"14:00",catatan:""},
  {id:"AB002",karyawanId:"K002",nama:"Siti Rahayu",tanggal:"2026-06-05",status:"Hadir",jamMasuk:"05:45",jamKeluar:"14:00",catatan:""},
  {id:"AB003",karyawanId:"K003",nama:"Agus Permana",tanggal:"2026-06-05",status:"Hadir",jamMasuk:"13:30",jamKeluar:"22:00",catatan:"Shift sore"},
  {id:"AB004",karyawanId:"K004",nama:"Diah Puspita",tanggal:"2026-06-05",status:"Hadir",jamMasuk:"07:00",jamKeluar:"15:00",catatan:""},
  {id:"AB005",karyawanId:"K005",nama:"Rudi Hartoyo",tanggal:"2026-06-05",status:"Izin",jamMasuk:"",jamKeluar:"",catatan:"Izin sakit — ada pengganti"},
  {id:"AB006",karyawanId:"K001",nama:"Budi Santoso",tanggal:"2026-06-04",status:"Hadir",jamMasuk:"05:30",jamKeluar:"14:00",catatan:""},
  {id:"AB007",karyawanId:"K002",nama:"Siti Rahayu",tanggal:"2026-06-04",status:"Hadir",jamMasuk:"05:45",jamKeluar:"14:00",catatan:""},
  {id:"AB008",karyawanId:"K003",nama:"Agus Permana",tanggal:"2026-06-04",status:"Terlambat",jamMasuk:"14:15",jamKeluar:"22:00",catatan:"Terlambat 15 menit"},
];

/* ================================================================
   STOK OBAT & VAKSIN
================================================================ */
const initialStokObat = [
  {id:"SO001",nama:"Vaksin ND Clone 45 (Medion)",jenis:"Vaksin",target:"Broiler/Layer",satuan:"Ampul",stok:50,minStok:20,kadaluarsa:"2026-12-31",hargaSatuan:15000,supplier:"PT Medion",catatan:"1 ampul = 1000 dosis"},
  {id:"SO002",nama:"Vaksin Gumboro (Medivac)",jenis:"Vaksin",target:"Broiler",satuan:"Ampul",stok:30,minStok:15,kadaluarsa:"2026-10-15",hargaSatuan:18000,supplier:"PT Medion",catatan:"Berikan D10-14"},
  {id:"SO003",nama:"Vaksin AI H5N1 (Medivac AI)",jenis:"Vaksin",target:"Layer",satuan:"Ampul",stok:8,minStok:10,kadaluarsa:"2026-09-30",hargaSatuan:45000,supplier:"PT Medion",catatan:"⚠️ STOK KRITIS — order sekarang!"},
  {id:"SO004",nama:"Tylosin 100 (antibiotik CRD)",jenis:"Antibiotik",target:"Broiler",satuan:"Botol 100ml",stok:12,minStok:5,kadaluarsa:"2027-03-01",hargaSatuan:85000,supplier:"Apotek Hewan",catatan:"Dosis 0.5ml/L air minum"},
  {id:"SO005",nama:"Vitamin C + Elektrolit",jenis:"Vitamin",target:"Semua",satuan:"Kg",stok:8,minStok:3,kadaluarsa:"2027-06-30",hargaSatuan:95000,supplier:"Toko Sapronak",catatan:"Anti-stres panas"},
  {id:"SO006",nama:"Ivermectin 1% (Ivomec)",jenis:"Antiparasit",target:"Sapi/Domba",satuan:"Botol 50ml",stok:5,minStok:3,kadaluarsa:"2027-01-15",hargaSatuan:120000,supplier:"Apotek Hewan",catatan:"0.2mg/kg BB sapi subkutan"},
  {id:"SO007",nama:"Obat Cacing Albendazole",jenis:"Antiparasit",target:"Sapi/Domba",satuan:"Strip 6 tablet",stok:20,minStok:10,kadaluarsa:"2027-08-01",hargaSatuan:45000,supplier:"Apotek Hewan",catatan:"7.5mg/kg BB oral"},
  {id:"SO008",nama:"Antibiotik Amoxicillin 20%",jenis:"Antibiotik",target:"Sapi/Domba",satuan:"Botol 100ml",stok:3,minStok:5,kadaluarsa:"2026-11-30",hargaSatuan:75000,supplier:"Apotek Hewan",catatan:"⚠️ STOK KRITIS — di bawah minimum"},
  {id:"SO009",nama:"Mineral Blok Sapi",jenis:"Suplemen",target:"Sapi",satuan:"Blok 5kg",stok:15,minStok:8,kadaluarsa:"2027-12-31",hargaSatuan:85000,supplier:"Toko Sapronak",catatan:"1 blok/10 ekor/bulan"},
  {id:"SO010",nama:"EM4 Peternakan 1L",jenis:"Probiotik",target:"Semua",satuan:"Botol",stok:24,minStok:10,kadaluarsa:"2027-06-01",hargaSatuan:35000,supplier:"Toko Pertanian",catatan:"Fermentasi pakan & sanitasi kandang"},
];

/* ================================================================
   JADWAL VAKSIN TERPROGRAM
================================================================ */
/* ================================================================
   TARGET PRODUKSI PER PERIODE
================================================================ */
const initialTarget = [
  {id:"TG001",bulan:"2026-06",komoditi:"Broiler",metric:"Ekor Panen",target:4000,satuan:"ekor",catatan:"2 kandang (D+E)"},
  {id:"TG002",bulan:"2026-06",komoditi:"Broiler",metric:"FCR Rata",target:1.65,satuan:"",catatan:"Target FCR optimal"},
  {id:"TG003",bulan:"2026-06",komoditi:"Layer",metric:"HDP",target:88,satuan:"%",catatan:"Target semua kandang"},
  {id:"TG004",bulan:"2026-06",komoditi:"Layer",metric:"Produksi Telur",target:165000,satuan:"butir",catatan:"2 kandang × 30 hari"},
  {id:"TG005",bulan:"2026-06",komoditi:"Sapi",metric:"Ekor Siap Jual",target:3,satuan:"ekor",catatan:"ADG ≥700g/hari"},
  {id:"TG006",bulan:"2026-06",komoditi:"Domba",metric:"Ekor Siap Jual",target:5,satuan:"ekor",catatan:"Menjelang Idul Adha"},
  {id:"TG007",bulan:"2026-06",komoditi:"Semua",metric:"Total Pendapatan",target:280000000,satuan:"Rp",catatan:"Target bulan Juni"},
  {id:"TG008",bulan:"2026-06",komoditi:"Semua",metric:"Total Biaya",target:195000000,satuan:"Rp",catatan:"Batas biaya operasional"},
];

/* ================================================================
   PROYEKSI PENDAPATAN 3 BULAN
================================================================ */
const initialProyeksi = [
  {bulan:"2026-06",pemasukanProyeksi:280000000,pengeluaranProyeksi:195000000,labaProyeksi:85000000,catatan:"Panen 2 kandang broiler + puncak produksi telur"},
  {bulan:"2026-07",pemasukanProyeksi:310000000,pengeluaranProyeksi:210000000,labaProyeksi:100000000,catatan:"Idul Adha — harga sapi & domba tinggi"},
  {bulan:"2026-08",pemasukanProyeksi:240000000,pengeluaranProyeksi:185000000,labaProyeksi:55000000,catatan:"Pasca Idul Adha — harga turun normal"},
];

function App() {
  const [page, setPage] = useState("dashboard");
  const [cattle, setCattle] = usePersistentState('cattle', initialCattle);
  const [sheep, setSheep] = usePersistentState('sheep', initialSheep);
  const [sales, setSales] = usePersistentState('sales', initialSales);
  const [purchases, setPurchases] = usePersistentState('purchases', initialPurchases);
  const [feed, setFeed] = usePersistentState('feed', initialFeed);
  const [health, setHealth] = usePersistentState('health', initialHealth);
  const [breeding, setBreeding] = usePersistentState('breeding', initialBreeding);
  const [expenses, setExpenses] = usePersistentState('expenses', initialExpenses);
  const [layerFlocks, setLayerFlocks] = usePersistentState('layerFlocks', initialLayerFlocks);
  const [broilerFlocks, setBroilerFlocks] = usePersistentState('broilerFlocks', initialBroilerFlocks);
  const [eggProduction, setEggProduction] = usePersistentState('eggProduction', initialEggProduction);
  const [broilerHarvest, setBroilerHarvest] = usePersistentState('broilerHarvest', initialBroilerHarvest);
  // RPH
  const [rphRecords, setRphRecords]           = usePersistentState('rphRecords', initialRphRecords);
  const [rphDombaRecords, setRphDombaRecords]       = usePersistentState('rphDombaRecords', initialRphDombaRecords);
  const [rphBroilerRecords, setRphBroilerRecords]   = usePersistentState('rphBroilerRecords', initialRphBroilerRecords);
  const [sideOpen, setSideOpen] = useState(true);
  const [karyawan,      setKaryawan]      = usePersistentState('karyawan', initialKaryawan);
  const [dailyLog,      setDailyLog]      = usePersistentState('dailyLog', initialDailyLog);
  const [invoices,      setInvoices]      = usePersistentState('invoices', initialInvoice);
  const [hutangPiutang, setHutangPiutang] = usePersistentState('hutangPiutang', initialHutangPiutang);
  const [anggaran,      setAnggaran]      = usePersistentState('anggaran', initialAnggaran);
  const [absensi,       setAbsensi]       = usePersistentState('absensi', initialAbsensi);
  const [stokObat,      setStokObat]      = usePersistentState('stokObat', initialStokObat);
  const [target,        setTarget]        = usePersistentState('target', initialTarget);
  const [proyeksi,      setProyeksi]      = usePersistentState('proyeksi', initialProyeksi);

  useEffect(() => {
    const l = document.createElement("link");
    l.rel = "stylesheet";
    l.href = "https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=JetBrains+Mono:wght@400;700&family=Outfit:wght@400;500;600;700;800&display=swap";
    document.head.appendChild(l);
  }, []);

  const allSick = [...cattle, ...sheep].filter(a => a.health === "Sakit").length;
  const lowFeed = feed.filter(f => f.usagePerDay > 0 && f.stock / f.usagePerDay < 7).length;
  const broilerSiapPanen = broilerFlocks.filter(f => f.status === "Siap Panen").length;

  const NAV = [
    { id: "dashboard", label: "Dashboard", icon: "dash", color: "#60a5fa" },
    { id: "sapi", label: "Data Sapi", icon: "sapi", color: C.sapi, badge: cattle.filter(c => c.health === "Sakit").length },
    { id: "domba", label: "Data Domba", icon: "domba", color: C.domba, badge: sheep.filter(d => d.health === "Sakit").length },
    { id: "petelur", label: "Ayam Petelur", icon: "petelur", color: "#f59e0b" },
    { id: "broiler", label: "Ayam Broiler", icon: "broiler", color: "#e879f9", badge: broilerSiapPanen },
    { id: "rph",      label: "RPH Sapi",  icon: "rph", color: "#ef4444" },
    { id: "rphdmb",   label: "RPH Domba",   icon: "rph", color: "#a3e635" },
    { id: "rpabr",    label: "RPA Broiler", icon: "rph", color: "#e879f9" },
    { id: "beli", label: "Pembelian", icon: "beli", color: C.buy },
    { id: "jual", label: "Penjualan", icon: "jual", color: C.sell },
    { id: "pakan", label: "Manaj. Pakan", icon: "pakan", color: "#f97316", badge: lowFeed },
    { id: "kesehatan", label: "Kesehatan", icon: "sehat", color: C.health, badge: allSick },
    { id: "breeding", label: "Breeding", icon: "kawin", color: C.breed },
    { id: "biaya", label: "Pengeluaran", icon: "biaya", color: C.expense },
    { id: "laporan", label: "Laporan", icon: "laporan", color: C.report },
    { id: "kontak",  label: "Buku Kontak", icon: "laporan", color: "#60a5fa" },
    { id: "karyawan",  label: "SDM & Shift",   icon: "laporan", color: "#60a5fa" },
    { id: "keuangan2", label: "Invoice/Hutang", icon: "biaya",   color: "#f59e0b",
      badge: (() => { try { return initialHutangPiutang.filter(h=>!h.statusLunas&&h.jatuhTempo&&(new Date(h.jatuhTempo)-new Date())/86400000<=7).length; } catch(e){return 0;} })()
    },
    { id: "logharian", label: "Log Harian",     icon: "health",  color: "#06b6d4" },
  ];

  const PAGES = {
    dashboard: <Dashboard cattle={cattle} sheep={sheep} sales={sales} feed={feed} expenses={expenses} health={health} breeding={breeding} broilerFlocks={broilerFlocks} layerFlocks={layerFlocks} harvests={broilerHarvest} target={target} absensi={absensi} karyawan={karyawan} />,
    sapi: <PageHewan animals={cattle} setAnimals={setCattle} type="sapi" />,
    domba: <PageHewan animals={sheep} setAnimals={setSheep} type="domba" />,
    petelur: <PagePetelur flocks={layerFlocks} setFlocks={setLayerFlocks} eggs={eggProduction} setEggs={setEggProduction} />,
    broiler: <PageBroiler flocks={broilerFlocks} setFlocks={setBroilerFlocks} harvests={broilerHarvest} setHarvests={setBroilerHarvest} />,
    rph:    <PageRPH records={rphRecords} setRecords={setRphRecords} cattle={cattle} />,
    rphdmb: <PageRPHDomba records={rphDombaRecords} setRecords={setRphDombaRecords} sheep={sheep} />,
    rpabr:  <PageRPABroiler records={rphBroilerRecords} setRecords={setRphBroilerRecords} flocks={broilerFlocks} />,
    beli: <PageBeli purchases={purchases} setPurchases={setPurchases} cattle={cattle} sheep={sheep} layerFlocks={layerFlocks} broilerFlocks={broilerFlocks} />,
    jual: <PageJual sales={sales} setSales={setSales} cattle={cattle} sheep={sheep} layerFlocks={layerFlocks} broilerFlocks={broilerFlocks} />,
    pakan: <PagePakan feed={feed} setFeed={setFeed} />,
    kesehatan: <PageKesehatan health={health} setHealth={setHealth} cattle={cattle} sheep={sheep} layerFlocks={layerFlocks} broilerFlocks={broilerFlocks} stokObat={stokObat} setStokObat={setStokObat} />,
    breeding: <PageBreeding breeding={breeding} setBreeding={setBreeding} cattle={cattle} sheep={sheep} layerFlocks={layerFlocks} broilerFlocks={broilerFlocks} />,
    biaya: <PageBiaya expenses={expenses} setExpenses={setExpenses} />,
    laporan: <PageLaporan cattle={cattle} sheep={sheep} sales={sales} feed={feed} expenses={expenses} breeding={breeding} health={health} broilerFlocks={broilerFlocks} layerFlocks={layerFlocks} broilerHarvest={broilerHarvest} eggProduction={eggProduction} karyawan={karyawan} invoices={invoices} hutangPiutang={hutangPiutang} anggaran={anggaran} proyeksi={proyeksi} target={target} />,
    kontak:  <PageKontak />,
    karyawan:  <PageKaryawan karyawan={karyawan} setKaryawan={setKaryawan} absensi={absensi} setAbsensi={setAbsensi} />,
    keuangan2: <PageHutangPiutang invoices={invoices} setInvoices={setInvoices} hutangPiutang={hutangPiutang} setHutangPiutang={setHutangPiutang} />,
    logharian: <PageLogHarian dailyLog={dailyLog} setDailyLog={setDailyLog} broilerFlocks={broilerFlocks} layerFlocks={layerFlocks} />,
  };

  const an = NAV.find(n => n.id === page);
  const totalProfit = sales.reduce((s, t) => s + t.profit, 0);
  const totalPendTelur = eggProduction.reduce((s, e) => s + e.totalPendapatan, 0);
  const totalPanenBroiler = broilerHarvest.reduce((s, h) => s + h.totalPendapatan, 0);

  return (
    <div style={{ display: "flex", minHeight: "100vh", background: C.bg, fontFamily: "'Outfit', sans-serif", color: C.text }}>
      {/* SIDEBAR */}
      <div style={{ width: sideOpen ? 224 : 60, background: C.sidebar, borderRight: `1px solid ${C.border}`, display: "flex", flexDirection: "column", transition: "width 0.28s ease", overflow: "hidden", position: "sticky", top: 0, height: "100vh", flexShrink: 0 }}>
        <div style={{ padding: "16px 14px", borderBottom: `1px solid ${C.border}`, display: "flex", alignItems: "center", gap: 10, minHeight: 60 }}>
          <div style={{ width: 34, height: 34, background: "linear-gradient(135deg,#f5c842,#a3e635,#e879f9)", borderRadius: 9, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, fontSize: 16 }}>🐾</div>
          {sideOpen && (
            <div style={{ overflow: "hidden" }}>
              <div style={{ fontFamily: "'DM Serif Display',serif", fontSize: 15, color: C.sapi, whiteSpace: "nowrap" }}>TernakPro</div>
              <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", whiteSpace: "nowrap" }}>Farm Management</div>
            </div>
          )}
        </div>
        <nav style={{ padding: "10px 8px", flex: 1, overflowY: "auto" }}>
          {sideOpen && <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", padding: "6px 10px 4px", fontWeight: 700 }}>Ternak Besar</div>}
          {NAV.filter(n => ["dashboard","sapi","domba"].includes(n.id)).map(n => <NavBtn key={n.id} n={n} page={page} setPage={setPage} sideOpen={sideOpen} />)}

          {sideOpen && <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", padding: "10px 10px 4px", fontWeight: 700 }}>Unggas</div>}
          {NAV.filter(n => ["petelur","broiler"].includes(n.id)).map(n => <NavBtn key={n.id} n={n} page={page} setPage={setPage} sideOpen={sideOpen} />)}

          {sideOpen && <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", padding: "10px 10px 4px", fontWeight: 700 }}>Pemotongan</div>}
          {NAV.filter(n => ["rph","rphdmb","rpabr"].includes(n.id)).map(n => <NavBtn key={n.id} n={n} page={page} setPage={setPage} sideOpen={sideOpen} />)}

          {sideOpen && <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", padding: "10px 10px 4px", fontWeight: 700 }}>Transaksi & Ops</div>}
          {NAV.filter(n => ["beli","jual","pakan","kesehatan","breeding","biaya","laporan","kontak"].includes(n.id)).map(n => <NavBtn key={n.id} n={n} page={page} setPage={setPage} sideOpen={sideOpen} />)}

          {sideOpen && <div style={{ fontSize: 9, color: C.dim, letterSpacing: 1.5, textTransform: "uppercase", padding: "10px 10px 4px", fontWeight: 700 }}>Manajemen</div>}
          {NAV.filter(n => ["karyawan","keuangan2","logharian"].includes(n.id)).map(n => <NavBtn key={n.id} n={n} page={page} setPage={setPage} sideOpen={sideOpen} />)}
        </nav>
        <button onClick={() => setSideOpen(!sideOpen)} style={{ margin: 8, padding: 8, background: "#ffffff06", border: `1px solid ${C.border}`, borderRadius: 8, cursor: "pointer", color: C.dim, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Ico n={sideOpen ? "chev_l" : "chev_r"} size={13} color={C.dim} />
        </button>
      </div>

      {/* MAIN */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <div style={{ padding: "12px 22px", borderBottom: `1px solid ${C.border}`, display: "flex", justifyContent: "space-between", alignItems: "center", background: C.sidebar, position: "sticky", top: 0, zIndex: 100, flexWrap: "wrap", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <Ico n={an?.icon} size={18} color={an?.color} />
            <h1 style={{ fontFamily: "'DM Serif Display',serif", fontSize: 18, color: C.text, margin: 0 }}>{an?.label}</h1>
          </div>
          <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
            {allSick > 0 && <div style={{ background: C.expense + "12", border: `1px solid ${C.expense}28`, borderRadius: 20, padding: "4px 10px", fontSize: 11, color: C.expense, display: "flex", alignItems: "center", gap: 4 }}><Ico n="warn" size={11} color={C.expense} />{allSick} Sakit</div>}
            {broilerSiapPanen > 0 && <div style={{ background: "#a3e63512", border: "1px solid #a3e63528", borderRadius: 20, padding: "4px 10px", fontSize: 11, color: "#a3e635" }}>🐓 {broilerSiapPanen} Siap Panen</div>}
            <div style={{ background: C.sapi + "10", border: `1px solid ${C.sapi}22`, borderRadius: 7, padding: "4px 9px", fontSize: 10, color: C.sapi, fontFamily: "'JetBrains Mono',monospace" }}>🐄{cattle.length}</div>
            <div style={{ background: C.domba + "10", border: `1px solid ${C.domba}22`, borderRadius: 7, padding: "4px 9px", fontSize: 10, color: C.domba, fontFamily: "'JetBrains Mono',monospace" }}>🐑{sheep.length}</div>
            <div style={{ background: "#f59e0b10", border: "1px solid #f59e0b22", borderRadius: 7, padding: "4px 9px", fontSize: 10, color: "#f59e0b", fontFamily: "'JetBrains Mono',monospace" }}>🥚{layerFlocks.reduce((s,f)=>s+f.jumlah,0).toLocaleString("id-ID")}</div>
            <div style={{ background: "#e879f910", border: "1px solid #e879f922", borderRadius: 7, padding: "4px 9px", fontSize: 10, color: "#e879f9", fontFamily: "'JetBrains Mono',monospace" }}>🐓{broilerFlocks.filter(f=>f.status!=="Sudah Panen").reduce((s,f)=>s+f.jumlah,0).toLocaleString("id-ID")}</div>
            <div style={{ background: C.sell + "10", border: `1px solid ${C.sell}22`, borderRadius: 7, padding: "4px 9px", fontSize: 10, color: C.sell, fontFamily: "'JetBrains Mono',monospace" }}>💰{rp(totalProfit)}</div>
          </div>
        </div>
        <div style={{ flex: 1, padding: "20px 22px", overflowY: "auto" }}>
          <ErrorBoundary key={page}>
            {PAGES[page]}
          </ErrorBoundary>
        </div>
      </div>
    </div>
  );
}

/* Nav Button helper */
function NavBtn({ n, page, setPage, sideOpen }) {
  const active = page === n.id;
  const iconMap = { petelur: "🥚", broiler: "🐓", rph: "🔪" };
  return (
    <button onClick={() => setPage(n.id)} title={!sideOpen ? n.label : ""} style={{ width: "100%", display: "flex", alignItems: "center", gap: 9, padding: "7px 10px", marginBottom: 2, borderRadius: 9, border: "none", cursor: "pointer", background: active ? n.color + "18" : "transparent", color: active ? n.color : C.dim, transition: "all 0.15s", position: "relative", justifyContent: sideOpen ? "flex-start" : "center" }}>
      {active && <div style={{ position: "absolute", left: 0, top: "50%", transform: "translateY(-50%)", width: 2.5, height: 16, background: n.color, borderRadius: "0 3px 3px 0" }} />}
      {iconMap[n.id]
        ? <span style={{ fontSize: 14, lineHeight: 1 }}>{iconMap[n.id]}</span>
        : <Ico n={n.icon} size={15} color={active ? n.color : C.dim} />}
      {sideOpen && <span style={{ fontSize: 12, fontWeight: active ? 700 : 500, whiteSpace: "nowrap" }}>{n.label}</span>}
      {sideOpen && n.badge > 0 && <span style={{ marginLeft: "auto", background: C.expense, color: "#fff", borderRadius: 20, padding: "1px 5px", fontSize: 9, fontWeight: 800, flexShrink: 0 }}>{n.badge}</span>}
    </button>
  );
}


/* ===== Render aplikasi ke #root ===== */
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
