/* Hunian Kita — Iuran warga: jimpitan + urunan/patungan
   Dues: pengelola/admin management · UrunanCard shared with resident */

const UR_CAT = {
  Fasilitas:  { icon: "hammer", color: "#02A0C1" },
  Sosial:     { icon: "heart-handshake", color: "#DC4A3D" },
  Keamanan:   { icon: "shield", color: "#7A6CF0" },
  Komunitas:  { icon: "party-popper", color: "#C9810D" },
  Kebersihan: { icon: "trash-2", color: "#11936A" },
};

function UrunanCard({ u, actionLabel, onAction, joined }) {
  const HK = window.HK;
  const pct = Math.min(100, Math.round((u.collected / u.target) * 100));
  const done = u.status === "Tercapai" || pct >= 100;
  return (
    <div className="card pad urunan">
      <div className="uh">
        <span className="uic" style={{ background: u.color }}><Icon name={u.icon} size={22} /></span>
        <div style={{ flex: 1, minWidth: 0 }}><div className="ut">{u.title}</div><div className="um">{u.id} · {u.cat} · tenggat {u.deadline}</div></div>
        <span className={"badge " + (done ? "pos" : "info")}><span className="bdot" />{u.status}</span>
      </div>
      {u.note && <p style={{ fontSize: 13, color: "var(--t2)", fontWeight: 500, lineHeight: 1.5, margin: 0 }}>{u.note}</p>}
      <div>
        <div className="urow" style={{ marginBottom: 8 }}>
          <div className="uamt">{HK.rp(u.collected)} <small>/ {HK.rp(u.target)}</small></div>
          <div className="upct" style={done ? { color: "var(--pos)" } : null}>{pct}%</div>
        </div>
        <div className="bar tall"><span style={{ width: pct + "%", background: done ? "linear-gradient(90deg,var(--pos),#0E7C86)" : null }} /></div>
      </div>
      <div className="uf">
        <span className="umeta"><Icon name="users" size={14} />{u.contributors} warga ikut</span>
        <span className="umeta"><Icon name="calendar" size={14} />{u.deadline}</span>
        <div style={{ marginLeft: "auto" }}>
          {joined ? <span className="badge pos"><Icon name="check" size={12} />Sudah ikut · {HK.rp(joined)}</span>
            : done ? <span className="badge calm"><Icon name="check" size={12} />Selesai</span>
            : <button className="btn primary sm" onClick={() => onAction && onAction(u)}><Icon name="hand-coins" size={14} />{actionLabel}</button>}
        </div>
      </div>
    </div>
  );
}

/* ---- create campaign (pengelola) ---- */
function NewUrunan({ ctx, onClose }) {
  const [title, setTitle] = React.useState("");
  const [cat, setCat] = React.useState("Fasilitas");
  const [target, setTarget] = React.useState("");
  const [deadline, setDeadline] = React.useState("");
  const [note, setNote] = React.useState("");
  const save = () => {
    onClose();
    const meta = UR_CAT[cat];
    ctx.addUrunan({ title: title || "Urunan baru", cat, icon: meta.icon, color: meta.color,
      target: parseInt((target || "0").replace(/\D/g, "")) || 5000000, deadline: deadline || "—", note });
  };
  return (
    <Modal onClose={onClose}>
      <div className="mh"><span className="ic" style={{ width: 40, height: 40, borderRadius: 11, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center" }}><Icon name="hand-coins" size={20} /></span>
        <div><h3 style={{ fontSize: 17, fontWeight: 800 }}>Buat urunan / patungan</h3><div className="statline">Warga bisa langsung ikut menyumbang dari aplikasi</div></div>
        <button className="iconbtn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="x" size={18} /></button></div>
      <div className="mb">
        <div className="field"><label>Judul</label><input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="mis. Renovasi pos ronda timur" /></div>
        <div className="field"><label>Kategori</label>
          <div className="choice-row">{Object.keys(UR_CAT).map((c) => (
            <button key={c} className={"choice" + (cat === c ? " on" : "")} onClick={() => setCat(c)}><Icon name={UR_CAT[c].icon} size={15} />{c}</button>
          ))}</div></div>
        <div className="grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
          <div className="field"><label>Target dana (Rp)</label><input value={target} onChange={(e) => setTarget(e.target.value)} placeholder="15.000.000" /></div>
          <div className="field"><label>Tenggat</label><input value={deadline} onChange={(e) => setDeadline(e.target.value)} placeholder="15 Jun 2026" /></div>
        </div>
        <div className="field" style={{ marginBottom: 0 }}><label>Keterangan</label><textarea rows={3} value={note} onChange={(e) => setNote(e.target.value)} placeholder="Jelaskan tujuan urunan…" /></div>
      </div>
      <div className="mf"><button className="btn ghost" onClick={onClose}>Batal</button>
        <button className="btn primary" onClick={save}><Icon name="check" size={16} />Buat & umumkan</button></div>
    </Modal>
  );
}

function Dues({ ctx }) {
  const HK = window.HK;
  const [open, setOpen] = React.useState(false);
  const urunan = ctx.urunan;
  const totalCollected = urunan.reduce((s, u) => s + u.collected, 0);
  const totalTarget = urunan.reduce((s, u) => s + u.target, 0);
  const active = urunan.filter((u) => u.status === "Aktif").length;
  const done = urunan.filter((u) => u.status === "Tercapai").length;
  const contributors = urunan.reduce((s, u) => s + u.contributors, 0);
  const pct = Math.round((totalCollected / totalTarget) * 100);

  return (
    <div className="content-inner">
      <div className="mini-stats">
        <div className="ms"><span className="msv" style={{ color: "var(--accent)" }}>{active}</span><span className="msl">Urunan aktif</span></div>
        <div className="ms"><span className="msv">{HK.rp(totalCollected)}</span><span className="msl">Total terkumpul</span></div>
        <div className="ms"><span className="msv" style={{ color: "var(--pos)" }}>{done}</span><span className="msl">Target tercapai</span></div>
        <div className="ms"><span className="msv">{contributors.toLocaleString("id-ID")}</span><span className="msl">Total partisipasi warga</span></div>
      </div>

      <div className="card pad mt">
        <div className="card-h"><h3>Ringkasan iuran warga</h3><span className="hint">{HK.rp(totalCollected)} dari target {HK.rp(totalTarget)}</span>
          <div className="right"><span className="upct">{pct}%</span></div></div>
        <div className="bar tall"><span style={{ width: pct + "%" }} /></div>
        <div className="callout" style={{ marginTop: 16 }}>
          <span className="cic"><Icon name="info" size={20} /></span>
          <div style={{ flex: 1 }}><div className="ct" style={{ fontSize: 13.5 }}>Transparan untuk warga</div><div className="cm">Setiap warga bisa lihat progress & rincian dana langsung dari aplikasi.</div></div>
        </div>
      </div>

      <div className="section-title mt"><h2>Urunan & patungan warga</h2><span className="statline">{active} berjalan · {urunan.length} total</span>
        <div className="right"><button className="btn primary" onClick={() => setOpen(true)}><Icon name="plus" size={16} />Buat urunan</button></div></div>
      <div className="urunan-list">
        {urunan.map((u) => (
          <UrunanCard key={u.id} u={u} actionLabel="Lihat kontributor" onAction={() => ctx.toast("Membuka rincian kontributor " + u.id)} />
        ))}
      </div>

      {open && <NewUrunan ctx={ctx} onClose={() => setOpen(false)} />}
    </div>
  );
}

Object.assign(window, { Dues, UrunanCard, NewUrunan, UR_CAT });
