/* Hunian Kita — Announcements, Facilities, Visitors, Residents */

const ANN_TYPES = {
  Emergency:   { cls: "neg",  ic: "siren" },
  Maintenance: { cls: "warn", ic: "wrench" },
  Community:   { cls: "pos",  ic: "party-popper" },
  Security:    { cls: "pend", ic: "shield" },
  Water:       { cls: "info", ic: "droplet" },
};

/* ---------------- Announcements ---------------- */
function Compose({ ctx, onClose }) {
  const [type, setType] = React.useState("Community");
  const [title, setTitle] = React.useState("");
  const [body, setBody] = React.useState("");
  const [aud, setAud] = React.useState("All residents");
  const [ch, setCh] = React.useState({ Push: true, WhatsApp: true, Email: false });
  const toggle = (k) => setCh((c) => ({ ...c, [k]: !c[k] }));
  const publish = () => { onClose(); ctx.publish({ type, title: title || "Untitled notice", body: body || "—", aud, channels: Object.keys(ch).filter((k) => ch[k]) }); };

  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="megaphone" size={20} /></span>
        <div><h3 style={{ fontSize: 17, fontWeight: 800 }}>New announcement</h3><div className="statline">Reaches residents instantly across selected channels</div></div>
        <button className="iconbtn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="x" size={18} /></button></div>
      <div className="mb">
        <div className="field"><label>Type</label>
          <div className="choice-row">{Object.keys(ANN_TYPES).map((t) => (
            <button key={t} className={"choice" + (type === t ? " on" : "")} onClick={() => setType(t)}><Icon name={ANN_TYPES[t].ic} size={15} />{t}</button>
          ))}</div></div>
        <div className="field"><label>Title</label><input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Pemadaman air terjadwal — Blok A & B" /></div>
        <div className="field"><label>Message</label><textarea rows={4} value={body} onChange={(e) => setBody(e.target.value)} placeholder="Tulis pesan singkat dan jelas…" /></div>
        <div className="field"><label>Audience</label>
          <select value={aud} onChange={(e) => setAud(e.target.value)}>
            <option>All residents</option><option>Blok A & B only</option><option>Tower 1</option><option>Owners only</option><option>Tenants only</option></select></div>
        <div className="field" style={{ marginBottom: 0 }}><label>Channels</label>
          <div className="choice-row">{Object.keys(ch).map((k) => (
            <button key={k} className={"choice" + (ch[k] ? " on" : "")} onClick={() => toggle(k)}>
              <Icon name={ch[k] ? "check" : "plus"} size={14} />{k}</button>
          ))}</div></div>
      </div>
      <div className="mf"><button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={publish}><Icon name="send" size={16} />Publish now</button></div>
    </Modal>
  );
}

function Announcements({ ctx }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div className="content-inner">
      <div className="section-title"><h2>Broadcast center</h2>
        <div className="right"><button className="btn primary" onClick={() => setOpen(true)}><Icon name="plus" size={16} />New announcement</button></div></div>

      <div className="ann-list">
        {ctx.announcements.map((a) => {
          const t = ANN_TYPES[a.type] || ANN_TYPES.Community;
          const pct = Math.round((a.reach / a.total) * 100);
          return (
            <div className={"card pad ann" + (a.pinned ? " pinned" : "")} key={a.id}>
              <div className="ann-top">
                <span className={"ic badge " + t.cls} style={{ width: 38, height: 38, borderRadius: 11, padding: 0, justifyContent: "center" }}><Icon name={t.ic} size={18} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <span className={"badge " + t.cls}>{a.type}</span>
                    {a.pinned && <span className="badge calm"><Icon name="pin" size={11} />Pinned</span>}
                    <span className="statline" style={{ marginLeft: "auto" }}>{a.time} · {a.author}</span>
                  </div>
                  <h3 style={{ fontSize: 16, fontWeight: 800, margin: "8px 0 4px", letterSpacing: "-0.01em" }}>{a.title}</h3>
                  <p style={{ fontSize: 13.5, color: "var(--t2)", lineHeight: 1.5, fontWeight: 500 }}>{a.body}</p>
                </div>
              </div>
              <div className="ann-foot">
                <div className="reach"><div className="bar" style={{ width: 130 }}><span style={{ width: pct + "%" }} /></div>
                  <span className="statline">{a.reach.toLocaleString("id-ID")} / {a.total.toLocaleString("id-ID")} read · {pct}%</span></div>
                <div className="chs">{a.channels.map((c) => <span className="ch-pill" key={c}><Icon name={c === "Push" ? "bell" : c === "WhatsApp" ? "message-circle" : "mail"} size={12} />{c}</span>)}</div>
              </div>
            </div>
          );
        })}
      </div>
      {open && <Compose ctx={ctx} onClose={() => setOpen(false)} />}
    </div>
  );
}

/* ---------------- Facilities ---------------- */
function Facilities({ ctx }) {
  const HK = window.HK;
  const [bookings, setBookings] = React.useState(HK.bookings);
  const act = (id, status, name) => {
    setBookings((b) => b.map((x) => x.id === id ? { ...x, status } : x));
    ctx.toast("Booking " + id + " " + status.toLowerCase());
    // persist ke backend (PATCH pakai id numerik _id)
    const bk = bookings.find((x) => x.id === id);
    if (bk && bk._id) window.API.apiPatch("/bookings/" + bk._id, { status }).catch(() => ctx.toast("⚠️ Gagal update booking di server"));
  };
  const pending = bookings.filter((b) => b.status === "Pending");

  return (
    <div className="content-inner">
      <div className="mini-stats">
        <div className="ms"><span className="msv">{pending.length}</span><span className="msl">Awaiting approval</span></div>
        <div className="ms"><span className="msv" style={{ color: "var(--pos)" }}>{bookings.filter((b) => b.status === "Approved").length}</span><span className="msl">Approved upcoming</span></div>
        <div className="ms"><span className="msv">5</span><span className="msl">Bookable facilities</span></div>
        <div className="ms"><span className="msv">Rp 4,2jt</span><span className="msl">Booking revenue · May</span></div>
      </div>

      <div className="grid mt" style={{ gridTemplateColumns: "1.3fr 1fr" }}>
        <div className="card pad">
          <div className="card-h"><h3>Booking requests</h3><span className="hint">approve to confirm the slot</span></div>
          <div className="bk-list">
            {bookings.map((b) => {
              const f = HK.facilities.find((x) => x.name === b.facility) || {};
              return (
                <div className="bk" key={b.id}>
                  <span className="bk-ic" style={{ background: (f.color || "#02A0C1") + "22", color: f.color || "#02A0C1" }}><Icon name="calendar" size={18} /></span>
                  <div className="bk-mid">
                    <div className="bk-t">{b.facility} <span className="muted">· {b.id}</span></div>
                    <div className="statline">{b.date} · {b.time} — {b.res} ({b.unit}){b.note ? " · " + b.note : ""}</div>
                  </div>
                  {b.status === "Pending"
                    ? <div className="bk-act"><button className="btn ghost sm" onClick={() => act(b.id, "Declined", b.res)}>Decline</button>
                        <button className="btn primary sm" onClick={() => act(b.id, "Approved", b.res)}><Icon name="check" size={14} />Approve</button></div>
                    : <span className={"badge " + (b.status === "Approved" ? "pos" : "calm")}><Icon name={b.status === "Approved" ? "check" : "x"} size={12} />{b.status}</span>}
                </div>
              );
            })}
          </div>
        </div>
        <div className="card pad">
          <div className="card-h"><h3>Facilities</h3></div>
          <div className="fac-list">
            {HK.facilities.map((f) => (
              <div className="fac" key={f.name}>
                <span className="fac-dot" style={{ background: f.color }} />
                <div style={{ flex: 1 }}><div className="fac-n">{f.name}</div><div className="statline">Capacity {f.cap}</div></div>
                <div className="fac-r">{HK.rp(f.rate)}<span className="muted"> /slot</span></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Visitors ---------------- */
const VIS_STATUS = { "Inside": "pos", "Pre-approved": "info", "Awaiting approval": "warn", "Checked out": "calm" };
function Visitors({ ctx }) {
  const HK = window.HK;
  const [vis, setVis] = React.useState(HK.visitors);
  const act = (id, status, name) => {
    setVis((v) => v.map((x) => x.id === id ? { ...x, status } : x));
    ctx.toast(name + (status === "Inside" ? " approved & checked in" : " checked out"));
    const vv = vis.find((x) => x.id === id);
    if (vv && vv._id) window.API.apiPatch("/visitors/" + vv._id, { status }).catch(() => ctx.toast("⚠️ Gagal update status tamu di server"));
  };
  const inside = vis.filter((v) => v.status === "Inside").length;
  const waiting = vis.filter((v) => v.status === "Awaiting approval").length;

  return (
    <div className="content-inner">
      <div className="mini-stats">
        <div className="ms"><span className="msv">{HK.kpis.visitorsToday}</span><span className="msl">Visitors today</span></div>
        <div className="ms"><span className="msv" style={{ color: "var(--pos)" }}>{inside}</span><span className="msl">Currently inside</span></div>
        <div className="ms"><span className="msv" style={{ color: "var(--warn)" }}>{waiting}</span><span className="msl">Awaiting approval</span></div>
        <div className="ms"><span className="msv">12</span><span className="msl">Pre-approved guests</span></div>
      </div>

      <div className="card pad mt">
        <div className="card-h"><h3>Gate log — live</h3><span className="hint">East & main gate</span>
          <div className="right"><button className="btn ghost sm"><Icon name="qr-code" size={15} />Scan pass</button></div></div>
        <table className="tbl">
          <thead><tr><th>Visitor</th><th>Purpose</th><th>Host unit</th><th>Vehicle</th><th>Time</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {vis.map((v) => (
              <tr key={v.id}>
                <td><div className="who"><span className="ci" style={{ background: "var(--accent-soft)", color: "var(--accent)" }}>
                  <Icon name={v.type === "delivery" ? "bike" : v.type === "vendor" ? "wrench" : "user"} size={15} /></span>
                  <div><div className="nm">{v.name}</div><div className="meta">{v.id}</div></div></div></td>
                <td>{v.purpose}</td><td className="strong">{v.host}</td><td className="unit muted">{v.plate}</td><td>{v.time}</td>
                <td><span className={"badge " + VIS_STATUS[v.status]}><span className="bdot" />{v.status}</span></td>
                <td onClick={(e) => e.stopPropagation()}>
                  {v.status === "Awaiting approval" ? <button className="btn primary sm" onClick={() => act(v.id, "Inside", v.name)}><Icon name="check" size={14} />Approve</button>
                    : v.status === "Inside" ? <button className="btn ghost sm" onClick={() => act(v.id, "Checked out", v.name)}>Check out</button>
                    : <span className="muted">—</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------------- Residents ---------------- */
function Residents({ ctx }) {
  const HK = window.HK;
  const [q, setQ] = React.useState("");
  const list = HK.residents.filter((r) => (r.name + r.unit).toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="content-inner">
      <div className="section-title"><h2>Resident directory</h2><span className="statline">1,240 units · 3,180 residents · 86% app-active</span>
        <div className="right"><button className="btn primary"><Icon name="user-plus" size={16} />Add unit</button></div></div>
      <div className="card pad">
        <div className="card-h">
          <div className="search" style={{ marginLeft: 0, width: 320 }}><Icon name="search" size={16} />
            <input placeholder="Search by name or unit…" value={q} onChange={(e) => setQ(e.target.value)} /></div>
        </div>
        <table className="tbl">
          <thead><tr><th>Unit</th><th>Primary resident</th><th>Type</th><th>Members</th><th>IPL status</th><th>Resident since</th><th>Contact</th></tr></thead>
          <tbody>
            {list.map((r) => (
              <tr key={r.unit}>
                <td className="strong unit">{r.unit}</td>
                <td><div className="who"><Avatar name={r.name} size={28} /><span className="nm">{r.name}</span></div></td>
                <td><span className={"badge " + (r.type === "Owner" ? "info" : "calm")}>{r.type}</span></td>
                <td>{r.members}</td>
                <td><span className={"badge " + (r.status === "Paid" ? "pos" : "neg")}><span className="bdot" />{r.status}</span></td>
                <td className="muted">{r.since}</td>
                <td className="unit muted">{r.phone}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { Announcements, Facilities, Visitors, Residents, ANN_TYPES });
