// screens/modals.jsx — All the action modals
// Add bill, add expense, new booking, new ticket, edit tenant, new apartment.
// Each modal validates locally and on save calls ctx.add* (which routes
// through the overlay system in app.jsx) + showToast.

// ───────────────────────── ADD BILL ─────────────────────────
function AddBillModal({ ctx, onClose, prefillAptId, prefillTenantId }) {
  const { data, addBill } = ctx;
  const tt = ctx.tt || ((k) => k);
  const [form, setForm] = React.useState({
    aptId: prefillAptId || data.apartments[0].id,
    tenantId: prefillTenantId || "",
    type: "rent",
    label: "",
    period: "2026-06",
    dueDate: "2026-06-05",
    amount: 540,
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const apt = data.byId.apt(form.aptId);
  const aptTenants = data.tenants.filter((t) => t.aptId === form.aptId && t.status === "active");

  // Auto-suggest label from type + period
  React.useEffect(() => {
    if (!form.label) {
      const periodLabel = monthLabel(form.period);
      if (form.type === "rent") upd("label", `Rent — ${periodLabel}`);
      else if (form.type === "utility") upd("label", `Electricity — ${periodLabel}`);
      else if (form.type === "charge") upd("label", `Charge — ${periodLabel}`);
      else if (form.type === "deposit") upd("label", `Deposit`);
    }
  }, [form.type, form.period]);

  const canSave = form.amount > 0 && form.label && form.aptId;
  const submit = () => {
    const tn = form.tenantId && data.byId.tenant(form.tenantId);
    addBill({
      id: "b-" + Math.random().toString(36).slice(2, 7),
      aptId: form.aptId,
      tenantId: form.tenantId || null,
      type: form.type,
      label: form.label,
      period: form.period,
      dueDate: form.dueDate,
      amount: Number(form.amount),
      status: "pending",
      paidOn: null,
    });
    onClose();
  };

  return (
    <Modal title={tt("mod.bill.title")} onClose={onClose} maxWidth={520}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
        <button className="btn accent" onClick={submit} disabled={!canSave}>
          <Icon name="check" size={13} /> {tt("mod.bill.submit")}
        </button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field-row">
          <div className="field">
            <label htmlFor="addbill-apt">{tt("mod.field.apt")}</label>
            <select id="addbill-apt" value={form.aptId} onChange={(e) => upd("aptId", e.target.value)}>
              {data.apartments.map((a) => <option key={a.id} value={a.id}>{a.name} · {a.neighborhood}</option>)}
            </select>
          </div>
          <div className="field">
            <label htmlFor="addbill-type">{tt("mod.field.type")}</label>
            <select id="addbill-type" value={form.type} onChange={(e) => upd("type", e.target.value)}>
              <option value="rent">{tt("mod.bill.type.rent")}</option>
              <option value="utility">{tt("mod.bill.type.utility")}</option>
              <option value="charge">{tt("mod.bill.type.charge")}</option>
              <option value="deposit">{tt("mod.bill.type.deposit")}</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label htmlFor="addbill-tenant">{tt("mod.field.tenant")} {form.type === "utility" && <span className="muted">({tt("mod.field.optionalSplit")})</span>}</label>
          <select id="addbill-tenant" value={form.tenantId} onChange={(e) => upd("tenantId", e.target.value)}>
            <option value="">{tt("mod.field.allTenants")}</option>
            {aptTenants.map((t) => <option key={t.id} value={t.id}>{t.name}{t.room ? ` · ${tt("ad.room")} ${t.room}` : ""}</option>)}
          </select>
        </div>
        <div className="field">
          <label htmlFor="addbill-label">{tt("mod.field.label")}</label>
          <input id="addbill-label" value={form.label} onChange={(e) => upd("label", e.target.value)} placeholder={tt("mod.bill.labelPh")} />
        </div>
        <div className="field-row-3">
          <div className="field">
            <label htmlFor="addbill-period">{tt("mod.field.period")}</label>
            <input id="addbill-period" type="month" value={form.period} onChange={(e) => upd("period", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="addbill-due">{tt("mod.field.due")}</label>
            <input id="addbill-due" type="date" value={form.dueDate} onChange={(e) => upd("dueDate", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="addbill-amount">{tt("mod.field.amount")}</label>
            <input id="addbill-amount" type="number" value={form.amount} onChange={(e) => upd("amount", e.target.value)} />
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ───────────────────────── ADD EXPENSE ─────────────────────────
function AddExpenseModal({ ctx, onClose, prefillAptId }) {
  const { data, addExpense } = ctx;
  const tt = ctx.tt || ((k) => k);
  const [form, setForm] = React.useState({
    aptId: prefillAptId || data.apartments[0].id,
    date: ArcoData.ISO(ArcoData.today),
    category: "maintenance",
    label: "",
    amount: 0,
    vendor: "",
    note: "",
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const canSave = form.amount > 0 && form.label;
  const submit = () => {
    addExpense({
      id: "e-" + Math.random().toString(36).slice(2, 7),
      aptId: form.aptId,
      date: form.date,
      category: form.category,
      label: form.label,
      amount: Number(form.amount),
      vendor: form.vendor,
      note: form.note,
    });
    onClose();
  };
  return (
    <Modal title={tt("mod.exp.title")} onClose={onClose} maxWidth={520}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
        <button className="btn accent" onClick={submit} disabled={!canSave}>
          <Icon name="check" size={13} /> {tt("mod.exp.submit")}
        </button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field-row">
          <div className="field">
            <label htmlFor="addexp-apt">{tt("mod.field.apt")}</label>
            <select id="addexp-apt" value={form.aptId} onChange={(e) => upd("aptId", e.target.value)}>
              {data.apartments.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
          </div>
          <div className="field">
            <label htmlFor="addexp-category">{tt("mod.exp.cat")}</label>
            <select id="addexp-category" value={form.category} onChange={(e) => upd("category", e.target.value)}>
              <option value="maintenance">{tt("mod.exp.cat.maintenance")}</option>
              <option value="supplies">{tt("mod.exp.cat.supplies")}</option>
              <option value="community">{tt("mod.exp.cat.community")}</option>
              <option value="utility">{tt("mod.exp.cat.utility")}</option>
              <option value="cleaning">{tt("mod.exp.cat.cleaning")}</option>
              <option value="tax">{tt("mod.exp.cat.tax")}</option>
              <option value="insurance">{tt("mod.exp.cat.insurance")}</option>
              <option value="other">{tt("mod.exp.cat.other")}</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label htmlFor="addexp-what">{tt("mod.exp.what")}</label>
          <input id="addexp-what" value={form.label} onChange={(e) => upd("label", e.target.value)} placeholder={tt("mod.exp.whatPh")} />
        </div>
        <div className="field-row-3">
          <div className="field">
            <label htmlFor="addexp-date">{tt("mod.exp.date")}</label>
            <input id="addexp-date" type="date" value={form.date} onChange={(e) => upd("date", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="addexp-amount">{tt("mod.field.amount")}</label>
            <input id="addexp-amount" type="number" value={form.amount} onChange={(e) => upd("amount", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="addexp-vendor">{tt("mod.exp.vendor")}</label>
            <input id="addexp-vendor" value={form.vendor} onChange={(e) => upd("vendor", e.target.value)} placeholder={tt("mod.exp.vendorPh")} />
          </div>
        </div>
        <div className="field">
          <label htmlFor="addexp-note">{tt("mod.exp.note")}</label>
          <textarea id="addexp-note" rows="2" value={form.note} onChange={(e) => upd("note", e.target.value)} />
        </div>
      </div>
    </Modal>
  );
}

// ───────────────────────── NEW / EDIT BOOKING ─────────────────────────
// Same form, two modes: pass `editingId` to populate from an existing booking
// and route the submit through ctx.updateBooking instead of ctx.addBooking.
function NewBookingModal({ ctx, onClose, prefillAptId, editingId }) {
  const { data, addBooking, updateBooking } = ctx;
  const tt = ctx.tt || ((k) => k);
  const existing = editingId && data.bookings.find((b) => b.id === editingId);
  const [form, setForm] = React.useState(() => existing ? {
    aptId: existing.aptId,
    guestName: existing.guestName,
    guestCountry: existing.guestCountry,
    start: existing.start,
    end: existing.end,
    nightly: existing.nightly,
    source: existing.source,
    status: existing.status,
    note: existing.note || "",
  } : {
    aptId: prefillAptId || data.apartments[0].id,
    guestName: "",
    guestCountry: "GB",
    start: "2026-07-01",
    end: "2026-07-08",
    nightly: 180,
    source: "Direct",
    status: "tentative",
    note: "",
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const apt = data.byId.apt(form.aptId);
  const nts = nightsBetween(form.start, form.end);
  const total = nts * Number(form.nightly);

  // Conflict check — any confirmed booking overlapping the date range for this apt.
  // Exclude the one we're editing so we don't conflict with ourselves.
  const conflict = data.bookings.find((b) =>
    b.id !== editingId &&
    b.aptId === form.aptId &&
    b.status !== "blocked" &&
    b.end > form.start && b.start < form.end
  );

  const canSave = form.guestName && nts > 0 && form.nightly >= 0 && !conflict;
  const submit = () => {
    if (editingId) {
      updateBooking(editingId, {
        aptId: form.aptId,
        guestName: form.guestName,
        guestCountry: form.guestCountry,
        start: form.start,
        end: form.end,
        nightly: Number(form.nightly),
        source: form.source,
        status: form.status,
        note: form.note,
      });
    } else {
      addBooking({
        id: "bk-" + Math.random().toString(36).slice(2, 7),
        aptId: form.aptId,
        guestName: form.guestName,
        guestCountry: form.guestCountry,
        start: form.start,
        end: form.end,
        nightly: Number(form.nightly),
        source: form.source,
        status: form.status,
        note: form.note,
      });
    }
    onClose();
  };

  const statusLabel = (s) => s === "tentative" ? tt("st.tentative") : s === "confirmed" ? tt("st.confirmed") : tt("st.blocked");
  return (
    <Modal title={editingId ? tt("mod.bk.titleEdit") : tt("mod.bk.titleNew")} onClose={onClose} maxWidth={560}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
        <button className="btn accent" onClick={submit} disabled={!canSave}>
          <Icon name="check" size={13} /> {editingId ? tt("mod.bk.submitEdit") : (form.status === "confirmed" ? tt("mod.bk.submitConfirm") : tt("mod.bk.submitNew"))}
        </button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field-row">
          <div className="field">
            <label htmlFor="booking-apt">{tt("mod.field.apt")}</label>
            <select id="booking-apt" value={form.aptId} onChange={(e) => upd("aptId", e.target.value)}>
              {data.apartments.map((a) => <option key={a.id} value={a.id}>{a.name} · €{a.summerNightly}/{tt("common.nights").slice(0, 5)}</option>)}
            </select>
          </div>
          <div className="field">
            <label htmlFor="booking-source">{tt("mod.bk.source")}</label>
            <select id="booking-source" value={form.source} onChange={(e) => upd("source", e.target.value)}>
              <option value="Direct">{tt("bk.source.direct")}</option>
              <option value="Airbnb">Airbnb</option>
              <option value="Booking">Booking</option>
              <option value="Vrbo">Vrbo</option>
              <option value="Other">{tt("bk.source.other")}</option>
            </select>
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="booking-guest-name">{tt("mod.bk.guestName")}</label>
            <input id="booking-guest-name" value={form.guestName} onChange={(e) => upd("guestName", e.target.value)} placeholder={tt("mod.bk.guestNamePh")} />
          </div>
          <div className="field">
            <label htmlFor="booking-country">{tt("mod.bk.country")}</label>
            <select id="booking-country" value={form.guestCountry} onChange={(e) => upd("guestCountry", e.target.value)}>
              {Object.entries(FLAGS).map(([code, f]) => <option key={code} value={code}>{f} {code}</option>)}
            </select>
          </div>
        </div>
        <div className="field-row-3">
          <div className="field">
            <label htmlFor="booking-check-in">{tt("mod.bk.checkIn")}</label>
            <input id="booking-check-in" type="date" value={form.start} onChange={(e) => upd("start", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="booking-check-out">{tt("mod.bk.checkOut")}</label>
            <input id="booking-check-out" type="date" value={form.end} onChange={(e) => upd("end", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="booking-nightly">{tt("mod.bk.nightly")}</label>
            <input id="booking-nightly" type="number" value={form.nightly} onChange={(e) => upd("nightly", e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label>{tt("mod.bk.status")}</label>
          <div className="flex gap-2">
            {["tentative", "confirmed", "blocked"].map((s) => (
              <button key={s} type="button" className="chip" onClick={() => upd("status", s)}
                      style={{ cursor: "pointer", padding: "5px 14px",
                               background: form.status === s ? "var(--ef-ink)" : "var(--ef-bg)",
                               color: form.status === s ? "var(--ef-bg)" : "var(--ef-ink)",
                               border: "1px solid " + (form.status === s ? "var(--ef-ink)" : "var(--ef-line)") }}>
                {statusLabel(s)}
              </button>
            ))}
          </div>
        </div>
        <div className="field">
          <label htmlFor="booking-note">{tt("mod.exp.note")}</label>
          <textarea id="booking-note" rows="2" value={form.note} onChange={(e) => upd("note", e.target.value)} placeholder={tt("mod.bk.notePh")} />
        </div>

        {/* Live summary */}
        <div style={{ padding: 14, background: conflict ? "var(--ef-danger-soft)" : "var(--ef-accent-soft)",
                      color: conflict ? "var(--ef-danger)" : "var(--ef-accent-deep)",
                      borderRadius: 10, border: "1px solid " + (conflict ? "var(--ef-danger)" : "transparent") }}>
          {conflict ? (
            <div className="flex center gap-2">
              <Icon name="bell" size={14} />
              <div>
                <b>{tt("mod.bk.conflict")}</b> · {tt("mod.bk.conflictBody", {
                  guest: conflict.guestName,
                  start: fmtDate(conflict.start, { short: true }),
                  end: fmtDate(conflict.end, { short: true }),
                })}
              </div>
            </div>
          ) : (
            <div className="flex center gap-2">
              <Icon name="check" size={14} />
              <div>
                <b>{tt("mod.bk.summaryNts", { n: nts, rate: fmtEUR(Number(form.nightly)) })}</b> = <b className="num">{fmtEUR(total)}</b> · {apt.name} · {fmtDate(form.start, { short: true })} → {fmtDate(form.end, { short: true })}
              </div>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

// ───────────────────────── NEW MAINTENANCE TICKET ─────────────────────────
function NewTicketModal({ ctx, onClose, prefillAptId, prefillTenantId }) {
  const { data, addTicket } = ctx;
  const tt = ctx.tt || ((k) => k);
  const [form, setForm] = React.useState({
    aptId: prefillAptId || data.apartments[0].id,
    tenantId: prefillTenantId || "",
    title: "",
    priority: "med",
    note: "",
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const aptTenants = data.tenants.filter((t) => t.aptId === form.aptId && t.status === "active");
  const canSave = form.title && form.aptId;
  const submit = () => {
    addTicket({
      id: "tk-" + Math.random().toString(36).slice(2, 7),
      title: form.title,
      aptId: form.aptId,
      tenantId: form.tenantId || null,
      room: null,
      openedAt: ArcoData.ISO(ArcoData.today),
      status: "open",
      priority: form.priority,
      note: form.note,
    });
    onClose();
  };
  return (
    <Modal title={tt("mod.tk.title")} onClose={onClose} maxWidth={520}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
        <button className="btn accent" onClick={submit} disabled={!canSave}>
          <Icon name="check" size={13} /> {tt("mod.tk.submit")}
        </button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field">
          <label htmlFor="ticket-title">{tt("mod.tk.titleField")}</label>
          <input id="ticket-title" value={form.title} onChange={(e) => upd("title", e.target.value)} placeholder={tt("mod.tk.titlePh")} />
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="ticket-apt">{tt("mod.field.apt")}</label>
            <select id="ticket-apt" value={form.aptId} onChange={(e) => upd("aptId", e.target.value)}>
              {data.apartments.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
          </div>
          <div className="field">
            <label htmlFor="ticket-priority">{tt("mod.tk.priority")}</label>
            <select id="ticket-priority" value={form.priority} onChange={(e) => upd("priority", e.target.value)}>
              <option value="low">{tt("mod.tk.pri.low")}</option>
              <option value="med">{tt("mod.tk.pri.med")}</option>
              <option value="high">{tt("mod.tk.pri.high")}</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label htmlFor="ticket-tenant">{tt("mod.field.tenant")} <span className="muted">({tt("mod.field.optionalSplit").split(" · ")[0]})</span></label>
          <select id="ticket-tenant" value={form.tenantId} onChange={(e) => upd("tenantId", e.target.value)}>
            <option value="">{tt("mod.tk.tenantOpt")}</option>
            {aptTenants.map((t) => <option key={t.id} value={t.id}>{t.name}{t.room ? ` · ${tt("ad.room")} ${t.room}` : ""}</option>)}
          </select>
        </div>
        <div className="field">
          <label htmlFor="ticket-note">{tt("mod.tk.note")}</label>
          <textarea id="ticket-note" rows="3" value={form.note} onChange={(e) => upd("note", e.target.value)} placeholder={tt("mod.tk.notePh")} />
        </div>
      </div>
    </Modal>
  );
}

// ───────────────────────── EDIT TENANT ─────────────────────────
function EditTenantModal({ ctx, onClose, tenantId }) {
  const { data, updateTenant } = ctx;
  const tt = ctx.tt || ((k) => k);
  const original = data.byId.tenant(tenantId);
  const [form, setForm] = React.useState({ ...original });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const submit = () => {
    updateTenant(tenantId, {
      rent: Number(form.rent),
      deposit: Number(form.deposit),
      contractStart: form.contractStart,
      contractEnd: form.contractEnd,
      phone: form.phone,
      email: form.email,
      note: form.note,
    });
    onClose();
  };
  if (!original) return null;
  return (
    <Modal title={tt("mod.edit.title", { name: original.name })} onClose={onClose} maxWidth={560}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
        <button className="btn accent" onClick={submit}><Icon name="check" size={13} /> {tt("mod.edit.submit")}</button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field-row">
          <div className="field">
            <label htmlFor="edittenant-rent">{tt("mod.edit.rent")}</label>
            <input id="edittenant-rent" type="number" value={form.rent} onChange={(e) => upd("rent", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="edittenant-deposit">{tt("mod.edit.deposit")}</label>
            <input id="edittenant-deposit" type="number" value={form.deposit} onChange={(e) => upd("deposit", e.target.value)} />
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="edittenant-contract-start">{tt("mod.edit.start")}</label>
            <input id="edittenant-contract-start" type="date" value={form.contractStart} onChange={(e) => upd("contractStart", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="edittenant-contract-end">{tt("mod.edit.end")}</label>
            <input id="edittenant-contract-end" type="date" value={form.contractEnd} onChange={(e) => upd("contractEnd", e.target.value)} />
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="edittenant-email">{tt("mod.edit.email")}</label>
            <input id="edittenant-email" type="email" value={form.email} onChange={(e) => upd("email", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="edittenant-phone">{tt("mod.edit.phone")}</label>
            <input id="edittenant-phone" value={form.phone} onChange={(e) => upd("phone", e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label htmlFor="edittenant-note">{tt("mod.edit.note")}</label>
          <textarea id="edittenant-note" rows="3" value={form.note || ""} onChange={(e) => upd("note", e.target.value)} />
        </div>
      </div>
    </Modal>
  );
}

// ───────────────────────── NEW APARTMENT ─────────────────────────
function NewApartmentModal({ ctx, onClose }) {
  const { addApartment, L } = ctx;
  const [form, setForm] = React.useState({
    name: "",
    address: "",
    neighborhood: "",
    type: "rooms",
    bedrooms: 3,
    bathrooms: 1,
    size: 75,
    floor: "",
    summerNightly: 160,
    rent: 540,
    notes: "",
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const canSave = form.name && form.address;
  const submit = () => {
    addApartment({
      id: "ap-" + Math.random().toString(36).slice(2, 7),
      name: form.name,
      address: form.address,
      neighborhood: form.neighborhood,
      type: form.type,
      bedrooms: Number(form.bedrooms),
      bathrooms: Number(form.bathrooms),
      size: Number(form.size),
      floor: form.floor,
      notes: form.notes,
      summerNightly: Number(form.summerNightly),
      avg: { rent: Number(form.rent), util: 90 },
    });
    onClose();
  };
  return (
    <Modal title={L("mod.new_apt.title")} onClose={onClose} maxWidth={720}
      footer={<>
        <button className="btn ghost" onClick={onClose}>{L("btn.cancel")}</button>
        <button className="btn accent" onClick={submit} disabled={!canSave}>
          <Icon name="check" size={13} /> {L("mod.new_apt.submit")}
        </button>
      </>}>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="field-row">
          <div className="field">
            <label htmlFor="newapt-name">{L("mod.new_apt.short_name")}</label>
            <input id="newapt-name" value={form.name} onChange={(e) => upd("name", e.target.value)} placeholder={L("mod.new_apt.short_name.ph")} />
          </div>
          <div className="field">
            <label htmlFor="newapt-type">{L("mod.new_apt.rental_type")}</label>
            <select id="newapt-type" value={form.type} onChange={(e) => upd("type", e.target.value)}>
              <option value="rooms">{L("mod.new_apt.rooms_type")}</option>
              <option value="whole">{L("mod.new_apt.whole_type")}</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label htmlFor="newapt-address">{L("mod.new_apt.address")}</label>
          <input id="newapt-address" value={form.address} onChange={(e) => upd("address", e.target.value)} placeholder={L("mod.new_apt.address.ph")} />
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="newapt-neighborhood">{L("mod.new_apt.neighborhood")}</label>
            <input id="newapt-neighborhood" value={form.neighborhood} onChange={(e) => upd("neighborhood", e.target.value)} placeholder={L("mod.new_apt.neighborhood.ph")} />
          </div>
          <div className="field">
            <label htmlFor="newapt-floor">{L("mod.new_apt.floor")}</label>
            <input id="newapt-floor" value={form.floor} onChange={(e) => upd("floor", e.target.value)} placeholder={L("mod.new_apt.floor.ph")} />
          </div>
        </div>
        <div className="field-row-3">
          <div className="field">
            <label htmlFor="newapt-bedrooms">{L("mod.new_apt.bedrooms")}</label>
            <input id="newapt-bedrooms" type="number" value={form.bedrooms} onChange={(e) => upd("bedrooms", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="newapt-bathrooms">{L("mod.new_apt.bathrooms")}</label>
            <input id="newapt-bathrooms" type="number" value={form.bathrooms} onChange={(e) => upd("bathrooms", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="newapt-size">{L("mod.new_apt.size")}</label>
            <input id="newapt-size" type="number" value={form.size} onChange={(e) => upd("size", e.target.value)} />
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label htmlFor="newapt-rent">{L("mod.new_apt.rent")}</label>
            <input id="newapt-rent" type="number" value={form.rent} onChange={(e) => upd("rent", e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="newapt-nightly">{L("mod.new_apt.nightly")}</label>
            <input id="newapt-nightly" type="number" value={form.summerNightly} onChange={(e) => upd("summerNightly", e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label htmlFor="newapt-notes">{L("mod.new_apt.notes")}</label>
          <textarea id="newapt-notes" rows="2" value={form.notes} onChange={(e) => upd("notes", e.target.value)} placeholder={L("mod.new_apt.notes.ph")} />
        </div>
      </div>
    </Modal>
  );
}

// Helper used by Add Bill — month label like "January 2026"
function monthLabel(p) {
  const [y, m] = p.split("-").map(Number);
  const longNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  return `${longNames[m - 1]} ${y}`;
}

window.AddBillModal = AddBillModal;
window.AddExpenseModal = AddExpenseModal;
window.NewBookingModal = NewBookingModal;
window.NewTicketModal = NewTicketModal;
window.EditTenantModal = EditTenantModal;
window.NewApartmentModal = NewApartmentModal;

// ───────────────────────── BOOKING DETAIL ─────────────────────────
// Shown when a user clicks a booking pill in the Gantt or a contract card.
// Surfaces everything we know about a short-stay booking + actions.
function BookingDetailModal({ ctx, onClose, bookingId }) {
  const { data, nav, openModal, showToast } = ctx;
  const tt = ctx.tt || ((k) => k);
  const booking = data.bookings.find((b) => b.id === bookingId);
  if (!booking) return null;
  const apt = data.byId.apt(booking.aptId);
  const nts = nightsBetween(booking.start, booking.end);
  const total = nts * booking.nightly;
  const palette = bookingPaletteFor(booking);
  const initials2 = booking.guestName.split(/\s+|—|\(/).filter(Boolean).slice(0, 2).map((s) => s[0]).join("").toUpperCase();
  const isResident = booking.status === "resident";
  const isBlocked = booking.status === "blocked";
  const todayISO = ArcoData.ISO(ArcoData.today);
  const startedAgo = booking.start < todayISO;
  const endedAgo = booking.end < todayISO;

  return (
    <Modal onClose={onClose} maxWidth={620}
      footer={
        !isBlocked && !isResident ? (
          <>
            <button className="btn ghost" onClick={onClose}>{tt("bd.close")}</button>
            <Dropdown align="right" trigger={
              <button className="btn"><Icon name="moreH" size={14} /> {tt("bd.more")}</button>
            }>
              <MenuItem icon="file" label={tt("bd.dlContract")} onClick={() => showToast(`Contract — ${booking.guestName}.pdf`)} />
              <MenuItem icon="euro" label={tt("bd.payLink")} onClick={() => showToast(tt("bd.payLink"))} />
              <MenuItem icon="chat" label={tt("bd.sendConfirm")} onClick={() => showToast(tt("bd.sendConfirm"))} />
              <MenuItem icon="calendar" label={tt("bd.addCal")} onClick={() => showToast(tt("bd.addCal"))} />
              <MenuItem icon="building" label={tt("bd.openApt")} onClick={() => { onClose(); nav("apartment", apt.id); }} />
              <MenuDivider />
              <MenuItem icon="x" label={tt("bd.cancel")} danger onClick={() => { showToast(tt("bd.cancel")); onClose(); }} />
            </Dropdown>
            <button className="btn" onClick={() => { onClose(); openModal("newBooking", { editingId: booking.id }); }}>
              <Icon name="file" size={13} /> {tt("bd.edit")}
            </button>
            <button className="btn accent" onClick={onClose}>
              <Icon name="check" size={13} /> {tt("bd.ok")}
            </button>
          </>
        ) : (
          <>
            <button className="btn ghost" onClick={onClose}>{tt("bd.close")}</button>
            <button className="btn accent" onClick={onClose}><Icon name="check" size={13} /> {tt("bd.ok")}</button>
          </>
        )
      }>
      <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Hero */}
        <div className="flex center gap-3" style={{ paddingBottom: 14, borderBottom: "1px solid var(--ef-line)" }}>
          <div className={`avatar lg a${(booking.id.charCodeAt(3) + booking.id.charCodeAt(4)) % 8}`}
               style={{ flexShrink: 0 }}>{initials2}</div>
          <div className="grow" style={{ minWidth: 0 }}>
            <div className="flex center gap-2" style={{ marginBottom: 2 }}>
              <h2 className="display" style={{ fontSize: 20 }}>{booking.guestName}</h2>
              <Flag code={booking.guestCountry} />
              <StatusBadge status={booking.status} />
            </div>
            <div className="muted txt-sm">
              <Link onClick={() => { onClose(); nav("apartment", apt.id); }}>{apt.name}</Link>
              {" · "}{apt.neighborhood}
            </div>
          </div>
        </div>

        {/* Stay summary */}
        <div className="grid-2" style={{ gap: 12 }}>
          <KPIInline label={tt("bd.checkIn")} value={fmtDate(booking.start)}
                     hint={endedAgo ? tt("bd.stayEnded") : startedAgo ? tt("bd.inHouse") : tt("bd.inDays", { n: Math.round((new Date(booking.start) - new Date(todayISO))/86400000) })} />
          <KPIInline label={tt("bd.checkOut")} value={fmtDate(booking.end)}
                     hint={tt("bd.nightsTotal", { n: nts })} />
        </div>

        {!isBlocked && !isResident && (
          <div style={{ padding: 16, background: "var(--ef-accent-soft)", color: "var(--ef-accent-deep)", borderRadius: 12, display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
            <div>
              <div className="muted-2 b500" style={{ fontSize: 12, marginBottom: 2 }}>{tt("mod.bk.summaryNts", { n: nts, rate: fmtEUR(booking.nightly) })}</div>
              <div style={{ fontSize: 11, opacity: 0.75 }}>{tt("bd.bookedVia", { source: booking.source })}</div>
            </div>
            <div className="num b500" style={{ fontSize: 26, color: "var(--ef-ink)" }}>{fmtEUR(total)}</div>
          </div>
        )}

        {/* Details grid */}
        <div className="flex col" style={{ display: "flex", flexDirection: "column", gap: 0 }}>
          <DetailLine label={tt("bd.source")} value={<Pill>{booking.source}</Pill>} />
          <DetailLine label={tt("bd.status")} value={<StatusBadge status={booking.status} />} />
          {!isBlocked && !isResident && <DetailLine label={tt("bd.nightly")} value={<span className="num">{fmtEUR(booking.nightly)}</span>} />}
          {!isBlocked && !isResident && <DetailLine label={tt("bd.total")} value={<span className="num b500">{fmtEUR(total)}</span>} />}
          <DetailLine label={tt("bd.country")} value={<span className="flex center gap-2"><Flag code={booking.guestCountry} /> {booking.guestCountry}</span>} />
          <DetailLine label={tt("bd.apartment")} value={
            <Link onClick={() => { onClose(); nav("apartment", apt.id); }}>{apt.name} · {apt.neighborhood}</Link>
          } />
        </div>

        {booking.note && (
          <div style={{ padding: 12, background: "var(--ef-bg-soft)", borderRadius: 10, fontSize: 13, color: "var(--ef-ink-2)" }}>
            <Icon name="flag" size={11} style={{ marginRight: 6, verticalAlign: -1, color: "var(--ef-muted)" }} />
            {booking.note}
          </div>
        )}

        {/* Quick actions */}
        {!isBlocked && !isResident && (
          <div className="flex gap-2" style={{ paddingTop: 14, borderTop: "1px solid var(--ef-line)" }}>
            <button className="btn sm" onClick={() => showToast(tt("bd.msgGuest"))}>
              <Icon name="chat" size={12} /> {tt("bd.msgGuest")}
            </button>
            <button className="btn sm" onClick={() => openModal("addExpense", { prefillAptId: apt.id })}>
              <Icon name="receipt" size={12} /> {tt("bd.logClean")}
            </button>
            <button className="btn sm" onClick={() => openModal("newTicket", { prefillAptId: apt.id })}>
              <Icon name="wrench" size={12} /> {tt("bd.reportIssue")}
            </button>
          </div>
        )}

        {isResident && (
          <div style={{ padding: 14, background: "var(--info-soft)", color: "var(--info)", borderRadius: 10, fontSize: 13 }}>
            {tt("bd.residentNote")}
          </div>
        )}
      </div>
    </Modal>
  );
}

function KPIInline({ label, value, hint }) {
  return (
    <div style={{ padding: "12px 14px", background: "var(--ef-bg-soft)", borderRadius: 10, border: "1px solid var(--ef-line)" }}>
      <div className="muted txt-xs" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600, fontSize: 10.5 }}>{label}</div>
      <div className="num b500" style={{ fontSize: 17, marginTop: 4 }}>{value}</div>
      {hint && <div className="muted txt-xs" style={{ marginTop: 2 }}>{hint}</div>}
    </div>
  );
}

function DetailLine({ label, value }) {
  return (
    <div className="flex between center" style={{ padding: "10px 0", borderBottom: "1px solid var(--ef-line)" }}>
      <span className="muted txt-sm">{label}</span>
      <span style={{ minWidth: 0, maxWidth: "70%", textAlign: "right" }}>{value}</span>
    </div>
  );
}

function bookingPaletteFor(b) {
  if (b.status === "tentative") return "warn";
  if (b.status === "blocked")   return "muted";
  if (b.status === "resident")  return "info";
  return "accent";
}

window.BookingDetailModal = BookingDetailModal;

// Expose modal components globally so app.jsx renderModal switch can reach them
window.AddBillModal = AddBillModal;
window.AddExpenseModal = AddExpenseModal;
window.NewBookingModal = NewBookingModal;
window.NewTicketModal = NewTicketModal;
window.EditTenantModal = EditTenantModal;
window.NewApartmentModal = NewApartmentModal;
