/* INDIEKOS — Penghuni mobile app */
const ME = D.me;

function StatusBar({ onBrand }) {
  return (
    <div className={"statusbar" + (onBrand ? " on-brand" : "")}>
      <span>9:41</span>
      <span className="sb-icons"><Icon name="signal" size={15} /><Icon name="reception" size={15} /><Icon name="battery" size={17} /></span>
    </div>
  );
}

/* ---- Home (3 variations) ---- */
function PHome({ go, pending, openPay, variant }) {
  const cur = ME.current;
  const status = pending ? "pending" : cur.status; // open => due
  const dueState = status === "pending" ? "pending" : "due";
  const heroClass = status === "pending" ? "due" : "due"; // amber for due/pending
  const greeting = "Halo, " + ME.name.split(" ")[0];

  const Hero = (
    <div className={"status-hero " + (status === "pending" ? "due" : "due")}>
      <div className="row between" style={{ marginBottom: 14 }}>
        <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", opacity: .8 }}>Tagihan {cur.period}</span>
        {status === "pending"
          ? <span className="pill" style={{ background: "rgba(255,255,255,.5)", color: "var(--brand-on-accent)" }}><i className="dot" />Menunggu verifikasi</span>
          : <span className="pill" style={{ background: "rgba(255,255,255,.5)", color: "var(--brand-on-accent)" }}><i className="dot" />Jatuh tempo H-{cur.dueInDays}</span>}
      </div>
      <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: "-.02em" }} className="tnum">{D.rp(cur.total)}</div>
      <div style={{ fontSize: 13, opacity: .85, marginTop: 4 }}>Jatuh tempo 5 Juli 2025 · Kamar {ME.room}</div>
      {status === "pending"
        ? <div style={{ marginTop: 16, background: "rgba(255,255,255,.25)", borderRadius: 12, padding: "12px 14px", fontSize: 13, fontWeight: 600 }} className="row gap-2"><Icon name="hourglass" size={17} /> Bukti terkirim. Menunggu owner.</div>
        : <button className="btn btn-lg btn-block" style={{ marginTop: 16, background: "var(--brand-primary)", color: "#fff" }} onClick={openPay}><Icon name="upload" size={18} /> Bayar / unggah bukti</button>}
    </div>
  );

  return (
    <>
      <StatusBar onBrand={false} />
      <div className="p-appbar">
        <div><div className="mut" style={{ fontSize: 13 }}>{greeting} 👋</div><h1 style={{ fontSize: 20 }}>Kamar {ME.room}</h1></div>
        <Avatar name={ME.name} size="lg" />
      </div>
      <div className="p-body" style={{ paddingBottom: 24 }}>
        <div className="p-pad col gap-4">
          {variant !== "minimal" && Hero}
          {variant === "minimal" && (
            <div className="card" style={{ padding: 20 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Tagihan {cur.period}</div>
              <div className="row between" style={{ alignItems: "flex-end" }}>
                <div className="tnum" style={{ fontSize: 30, fontWeight: 800 }}>{D.rp(cur.total)}</div>
                {status === "pending" ? <Pill status="pending" /> : <span className="pill pill-gold"><i className="dot" />H-{cur.dueInDays}</span>}
              </div>
              {status !== "pending" && <button className="btn btn-primary btn-block btn-lg" style={{ marginTop: 16 }} onClick={openPay}><Icon name="upload" size={18} /> Bayar sekarang</button>}
            </div>
          )}

          {/* my room card */}
          <div className="card" style={{ padding: 16 }}>
            <div className="row gap-3">
              <div className="stat-chip chip-primary" style={{ width: 46, height: 46, borderRadius: 12 }}><Icon name="door" size={24} /></div>
              <div className="grow"><div style={{ fontWeight: 700 }}>Kamar {ME.room} · {ME.type}</div><div className="mut" style={{ fontSize: 12 }}>{ME.prop}</div></div>
              <div style={{ textAlign: "right" }}><div className="tnum" style={{ fontWeight: 700 }}>{D.rp(ME.price)}</div><div className="mut" style={{ fontSize: 11 }}>/ bulan</div></div>
            </div>
          </div>

          {/* deposit + since */}
          <div className="row gap-3">
            <div className="card grow" style={{ padding: 14 }}><div className="eyebrow" style={{ marginBottom: 6 }}>Deposit</div><div className="tnum" style={{ fontWeight: 700, fontSize: 18 }}>{D.rp(ME.deposit)}</div><div className="mut" style={{ fontSize: 11 }}>tersimpan</div></div>
            <div className="card grow" style={{ padding: 14 }}><div className="eyebrow" style={{ marginBottom: 6 }}>Sejak</div><div style={{ fontWeight: 700, fontSize: 18 }}>{ME.since}</div><div className="mut" style={{ fontSize: 11 }}>10 bulan</div></div>
          </div>

          {variant === "feed" && (
            <div>
              <div className="eyebrow" style={{ margin: "6px 4px 10px" }}>Aktivitas</div>
              <div className="col gap-2">
                {[["checkCircle", "var(--success)", "Bayar Mei diverifikasi", "5 Mei"], ["wrench", "var(--info-fg)", "Keluhan keran selesai", "2 Jun"], ["invoice", "var(--gold-fg)", "Tagihan Juli terbit", "1 Jul"]].map(([ic, c, t, d], i) => (
                  <div key={i} className="card row gap-3" style={{ padding: 12 }}><Icon name={ic} size={18} style={{ color: c }} /><span className="grow" style={{ fontSize: 13, fontWeight: 500 }}>{t}</span><span className="mut" style={{ fontSize: 11 }}>{d}</span></div>
                ))}
              </div>
            </div>
          )}

          {/* shortcuts */}
          <div className="row gap-3">
            <button className="card grow" style={{ padding: 14, cursor: "pointer", border: "1px solid var(--ink-200)" }} onClick={() => go("tagihan")}><Icon name="invoice" size={22} style={{ color: "var(--brand-primary)" }} /><div style={{ fontWeight: 600, fontSize: 13, marginTop: 6 }}>Tagihan</div></button>
            <button className="card grow" style={{ padding: 14, cursor: "pointer", border: "1px solid var(--ink-200)" }} onClick={() => go("keluhan")}><Icon name="wrench" size={22} style={{ color: "var(--brand-primary)" }} /><div style={{ fontWeight: 600, fontSize: 13, marginTop: 6 }}>Lapor keluhan</div></button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ---- Tagihan ---- */
function PTagihan({ openPay, pending }) {
  const cur = ME.current;
  return (
    <>
      <StatusBar />
      <div className="p-appbar"><h1>Tagihan</h1></div>
      <div className="p-body">
        <div className="p-pad col gap-4">
          <div className="card" style={{ padding: 16, borderColor: pending ? "var(--gold-bg)" : "var(--brand-accent-100)", borderWidth: 1.5 }}>
            <div className="row between" style={{ marginBottom: 8 }}><b>{cur.period}</b>{pending ? <Pill status="pending" /> : <span className="pill pill-gold"><i className="dot" />H-{cur.dueInDays}</span>}</div>
            <div className="tnum" style={{ fontSize: 26, fontWeight: 800 }}>{D.rp(cur.total)}</div>
            <div className="mut" style={{ fontSize: 12, marginTop: 2 }}>Jatuh tempo 5 Juli 2025</div>
            {pending ? <div className="banner banner-warning" style={{ marginTop: 12 }}><Icon name="hourglass" size={16} /><span>Bukti sedang ditinjau owner.</span></div>
              : <button className="btn btn-primary btn-block btn-lg" style={{ marginTop: 14 }} onClick={openPay}><Icon name="upload" size={18} /> Bayar / unggah bukti</button>}
          </div>
          <div>
            <div className="eyebrow" style={{ margin: "4px 4px 10px" }}>Riwayat</div>
            <div className="col gap-2">{ME.invoices.map(inv => (
              <div key={inv.id} className="card row between" style={{ padding: 14 }}>
                <div><div style={{ fontWeight: 600 }}>{inv.period}</div><div className="mut" style={{ fontSize: 11 }} className="tnum">{inv.id}</div></div>
                <div style={{ textAlign: "right" }}><div className="tnum" style={{ fontWeight: 700 }}>{D.rp(inv.total)}</div><Pill status="paid" /></div>
              </div>
            ))}</div>
          </div>
        </div>
      </div>
    </>
  );
}

/* ---- Keluhan ---- */
function PKeluhan({ openComplaint, complaints }) {
  const stMeta = { done: ["success", "Selesai"], in_progress: ["info", "Dikerjakan"], open: ["warning", "Menunggu"] };
  return (
    <>
      <StatusBar />
      <div className="p-appbar"><h1>Keluhan</h1></div>
      <div className="p-body">
        <div className="p-pad col gap-3">
          {complaints.length === 0 && <Empty icon="wrench" title="Belum ada keluhan" text="Laporkan kerusakan dengan tombol +" />}
          {complaints.map(c => { const [clr, lbl] = stMeta[c.status]; return (
            <div key={c.id} className="card" style={{ padding: 14 }}>
              <div className="row between" style={{ marginBottom: 6 }}><span className="mut" style={{ fontSize: 11, fontWeight: 600 }}>{c.id} · {c.cat}</span><span className={"pill pill-" + clr}><i className="dot" />{lbl}</span></div>
              <div style={{ fontWeight: 600 }}>{c.title}</div>
              <div className="mut" style={{ fontSize: 11, marginTop: 4 }}>{new Date(c.date).toLocaleDateString("id-ID", { day: "numeric", month: "long" })}</div>
            </div>
          ); })}
        </div>
      </div>
    </>
  );
}

/* ---- Profil ---- */
function PProfil() {
  return (
    <>
      <StatusBar />
      <div className="p-appbar"><h1>Profil</h1></div>
      <div className="p-body">
        <div className="p-pad col gap-4">
          <div className="card col" style={{ padding: 20, alignItems: "center", textAlign: "center" }}>
            <Avatar name={ME.name} size="xl" />
            <div style={{ fontWeight: 700, fontSize: 18, marginTop: 10 }}>{ME.name}</div>
            <div className="mut" style={{ fontSize: 12 }}>Kamar {ME.room} · {ME.prop}</div>
          </div>
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            {[["phone", "Telepon", ME.phone], ["door", "Kamar", ME.room + " · " + ME.type], ["calendar", "Bergabung", ME.since]].map(([ic, l, v], i) => (
              <div key={l} className="row gap-3" style={{ padding: "14px 16px", borderBottom: i < 2 ? "1px solid var(--ink-100)" : 0 }}>
                <Icon name={ic} size={18} style={{ color: "var(--ink-400)" }} /><span className="grow mut" style={{ fontSize: 13 }}>{l}</span><b style={{ fontSize: 13 }} className="tnum">{v}</b>
              </div>
            ))}
          </div>
          <button className="btn btn-success btn-block btn-lg"><Icon name="whatsapp" size={18} /> Hubungi pengelola</button>
          <button className="btn btn-ghost btn-block"><Icon name="logout" size={16} /> Keluar</button>
        </div>
      </div>
    </>
  );
}

/* ---- Upload bukti bottom sheet ---- */
function PaySheet({ open, onClose, onSubmit }) {
  const [step, setStep] = useState(1);
  const [amt, setAmt] = useState(String(ME.current.total));
  const [method, setMethod] = useState("Transfer BCA");
  const [hasPhoto, setHasPhoto] = useState(false);
  useEffect(() => { if (open) { setStep(1); setAmt(String(ME.current.total)); setHasPhoto(false); } }, [open]);
  return (
    <>
      <div className={"sheet-scrim" + (open ? " show" : "")} onClick={onClose} />
      <div className={"sheet" + (open ? " show" : "")}>
        <div className="grab" />
        <div className="row between" style={{ marginBottom: 8 }}><h3 style={{ fontSize: 18 }}>Unggah bukti bayar</h3><button className="icon-btn" onClick={onClose}><Icon name="x" /></button></div>
        <div className="col gap-4" style={{ paddingBottom: 8 }}>
          <div className="card row between" style={{ padding: 12, background: "var(--brand-primary-50)", border: "0" }}>
            <span style={{ fontWeight: 600, fontSize: 13 }}>Tagihan {ME.current.period}</span><b className="tnum">{D.rp(ME.current.total)}</b>
          </div>
          <div className="field"><label>Nominal dibayar</label><div className="input-group"><span className="prefix">Rp</span><input className="input" inputMode="numeric" value={amt ? Number(amt).toLocaleString("id-ID") : ""} onChange={e => setAmt(e.target.value.replace(/\D/g, ""))} /></div>
            {+amt < ME.current.total && +amt > 0 && <div className="hint" style={{ color: "var(--info-fg)" }}>Pembayaran sebagian · sisa {D.rp(ME.current.total - +amt)}</div>}</div>
          <div className="field"><label>Metode</label>
            <select className="select" value={method} onChange={e => setMethod(e.target.value)}>
              <option>Transfer BCA</option><option>Transfer Mandiri</option><option>QRIS</option><option>Cash ke penjaga</option>
            </select>
          </div>
          <div className="field"><label>Foto bukti transfer</label>
            {hasPhoto ? (
              <div className="row gap-3" style={{ padding: 12, background: "var(--success-bg)", borderRadius: "var(--r-3)" }}><Icon name="checkCircle" size={20} style={{ color: "var(--success)" }} /><span className="grow" style={{ fontSize: 13, fontWeight: 600, color: "var(--success-fg)" }}>bukti_transfer.jpg</span><button className="btn btn-quiet btn-sm" onClick={() => setHasPhoto(false)}>Ganti</button></div>
            ) : (
              <div className="dropzone" onClick={() => setHasPhoto(true)}><Icon name="camera" size={26} /><span style={{ fontSize: 13, fontWeight: 600 }}>Ambil foto dari kamera</span><span style={{ fontSize: 11 }}>atau pilih dari galeri</span></div>
            )}
          </div>
          <button className="btn btn-primary btn-block btn-lg" disabled={!hasPhoto || !amt} onClick={() => onSubmit(+amt)}><Icon name="send" size={18} /> Kirim untuk verifikasi</button>
          <div className="mut" style={{ fontSize: 11, textAlign: "center", marginBottom: 4 }}>Status akan jadi "Menunggu verifikasi" sampai owner menyetujui.</div>
        </div>
      </div>
    </>
  );
}

/* ---- Complaint sheet ---- */
function ComplaintSheet({ open, onClose, onSubmit }) {
  const cats = [["AC", "wind"], ["Bocor", "droplet"], ["Listrik", "zap"], ["Perbaikan", "wrench"], ["Lainnya", "receipt"]];
  const [cat, setCat] = useState("AC"); const [desc, setDesc] = useState(""); const [photo, setPhoto] = useState(false);
  useEffect(() => { if (open) { setDesc(""); setPhoto(false); } }, [open]);
  return (
    <>
      <div className={"sheet-scrim" + (open ? " show" : "")} onClick={onClose} />
      <div className={"sheet" + (open ? " show" : "")}>
        <div className="grab" />
        <div className="row between" style={{ marginBottom: 8 }}><h3 style={{ fontSize: 18 }}>Lapor keluhan</h3><button className="icon-btn" onClick={onClose}><Icon name="x" /></button></div>
        <div className="col gap-4" style={{ paddingBottom: 8 }}>
          <div className="field"><label>Kategori</label><div className="row gap-2 wrap">{cats.map(([c, ic]) => (<button key={c} className={"tw-opt" + (cat === c ? " on" : "")} onClick={() => setCat(c)} style={{ display: "flex", gap: 6, alignItems: "center" }}><Icon name={ic} size={14} />{c}</button>))}</div></div>
          <div className="field"><label>Deskripsi</label><textarea className="textarea" value={desc} onChange={e => setDesc(e.target.value)} placeholder="Jelaskan masalahnya…" /></div>
          <div className="field"><label>Foto</label>{photo ? <div className="row gap-3" style={{ padding: 12, background: "var(--success-bg)", borderRadius: "var(--r-3)" }}><Icon name="checkCircle" size={20} style={{ color: "var(--success)" }} /><span className="grow" style={{ fontSize: 13, fontWeight: 600, color: "var(--success-fg)" }}>foto_keluhan.jpg</span></div> : <div className="dropzone" onClick={() => setPhoto(true)}><Icon name="camera" size={24} /><span style={{ fontSize: 13, fontWeight: 600 }}>Ambil foto</span></div>}</div>
          <button className="btn btn-primary btn-block btn-lg" disabled={!desc} onClick={() => onSubmit({ cat, desc })}><Icon name="send" size={18} /> Kirim keluhan</button>
        </div>
      </div>
    </>
  );
}

/* ---- App shell ---- */
function PenghuniApp({ opts }) {
  const [tab, setTab] = useState("home");
  const [pay, setPay] = useState(false);
  const [comp, setComp] = useState(false);
  const [pending, setPending] = useState(false);
  const [complaints, setComplaints] = useState(() => ME.complaints.map(c => ({ ...c })));
  const [toastNode, toast] = useToast();
  const homeVar = opts.penghuniHome || "hero";

  const submitPay = (amt) => { setPending(true); setPay(false); toast("Bukti terkirim — menunggu verifikasi"); };
  const submitComplaint = ({ cat, desc }) => { setComplaints(c => [{ id: "KEL-" + (22 + c.length), title: desc, cat, date: "2025-06-09", status: "open" }, ...c]); setComp(false); toast("Keluhan terkirim"); };

  const TABS = [["home", "Beranda", "home"], ["tagihan", "Tagihan", "invoice"], ["keluhan", "Keluhan", "wrench"], ["profil", "Profil", "user"]];

  return (
    <div className="phone-stage">
      <div className="phone" data-screen-label="Penghuni">
        {tab === "home" && <PHome go={setTab} pending={pending} openPay={() => setPay(true)} variant={homeVar} />}
        {tab === "tagihan" && <PTagihan openPay={() => setPay(true)} pending={pending} />}
        {tab === "keluhan" && <PKeluhan openComplaint={() => setComp(true)} complaints={complaints} />}
        {tab === "profil" && <PProfil />}

        {tab === "keluhan" && <button className="fab" onClick={() => setComp(true)}><Icon name="plus" size={26} /></button>}

        <nav className="p-tabbar">
          {TABS.map(([id, lbl, ic]) => (
            <div key={id} className={"p-tab" + (tab === id ? " active" : "")} onClick={() => setTab(id)}>
              <Icon name={ic} size={24} /><span>{lbl}</span>
            </div>
          ))}
        </nav>

        <PaySheet open={pay} onClose={() => setPay(false)} onSubmit={submitPay} />
        <ComplaintSheet open={comp} onClose={() => setComp(false)} onSubmit={submitComplaint} />
        {toastNode}
      </div>
    </div>
  );
}
window.PenghuniApp = PenghuniApp;
