// screens/add-tenant.jsx — Add tenant modal (multi-step lite)
function AddTenantModal({ ctx, onClose, onCreate }) {
  const { data } = ctx;
  const tt = ctx.tt;
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    aptId: "",
    room: "",
    name: "",
    country: "FR",
    email: "",
    phone: "",
    university: "",
    age: 22,
    contractStart: "2026-09-01",
    contractEnd: "2027-06-30",
    rent: 540,
    deposit: 1080,
    note: "",
  });
  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const apt = data.byId.apt(form.aptId);
  const vacantRooms = apt && apt.type === "rooms"
    ? Array.from({ length: apt.bedrooms }, (_, i) => i + 1).filter((r) =>
        !data.tenants.find((t) => t.aptId === apt.id && t.room === r && t.status === "active"))
    : [];

  // Lightweight validation — inline error feedback without nagging.
  const emailValid = !form.email || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const datesValid = !form.contractStart || !form.contractEnd || form.contractStart < form.contractEnd;
  const rentValid = Number(form.rent) > 0;
  const ageValid = !form.age || (Number(form.age) >= 16 && Number(form.age) <= 120);

  const canNext = (() => {
    if (step === 1) return form.aptId && (apt?.type === "whole" || form.room);
    if (step === 2) return form.name && form.country && form.email && emailValid && ageValid;
    if (step === 3) return form.contractStart && form.contractEnd && datesValid && rentValid;
    return true;
  })();

  const submit = () => {
    const tenant = {
      id: "t-" + Math.random().toString(36).slice(2, 7),
      ...form,
      room: form.room ? Number(form.room) : null,
      rent: Number(form.rent),
      deposit: Number(form.deposit),
      age: Number(form.age),
      status: "active",
      avatarHue: Math.floor(Math.random() * 8),
    };
    onCreate(tenant);
  };

  const steps = [tt("at.step.apt"), tt("at.step.tenant"), tt("at.step.contract"), tt("at.step.review")];

  return (
    <Modal title={tt("at.title")} onClose={onClose} maxWidth={620}
      footer={
        <>
          <button className="btn ghost" onClick={onClose}>{tt("btn.cancel")}</button>
          {step > 1 && <button className="btn" onClick={() => setStep(step - 1)}>{tt("btn.back")}</button>}
          {step < 4 && <button className="btn accent" onClick={() => canNext && setStep(step + 1)} disabled={!canNext}>{tt("btn.continue")}</button>}
          {step === 4 && <button className="btn accent" onClick={submit}><Icon name="check" size={13} /> {tt("btn.createTenant")}</button>}
        </>
      }>
      {/* Stepper */}
      <div className="flex center gap-3" style={{ marginBottom: 24 }}>
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <div className="flex center gap-2" style={{ color: i + 1 <= step ? "var(--ef-ink)" : "var(--ef-muted)" }}>
              <span style={{
                width: 22, height: 22, borderRadius: 999,
                background: i + 1 < step ? "var(--ef-ink)" : i + 1 === step ? "var(--ef-accent)" : "var(--ef-bg-soft)",
                color: i + 1 <= step ? "var(--ef-bg)" : "var(--ef-muted)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontSize: 11, fontWeight: 500,
              }}>{i + 1 < step ? <Icon name="check" size={12} /> : i + 1}</span>
              <span className="txt-sm b500">{s}</span>
            </div>
            {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: "var(--ef-line)" }} />}
          </React.Fragment>
        ))}
      </div>

      {step === 1 && (
        <div className="flex col gap-4" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="field">
            <label>{tt("at.apartment")}</label>
            <div className="flex col gap-2" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {data.apartments.map((a) => {
                const tenants = data.tenants.filter((t) => t.aptId === a.id && t.status === "active");
                const rooms = a.type === "rooms" ? a.bedrooms : 1;
                const vacant = rooms - tenants.length;
                const selected = form.aptId === a.id;
                return (
                  <button key={a.id} type="button"
                          onClick={() => { upd("aptId", a.id); upd("room", ""); upd("rent", a.type === "rooms" ? a.avg.rent : (a.avg.rent)); upd("deposit", a.type === "rooms" ? a.avg.rent * 2 : a.avg.rent * 2); }}
                          className="card"
                          style={{ display: "flex", gap: 12, padding: 12, alignItems: "center", textAlign: "left", cursor: "pointer",
                                   borderColor: selected ? "var(--ef-accent)" : "var(--ef-line)",
                                   background: selected ? "var(--ef-accent-soft)" : "var(--ef-bg)" }}>
                    <div style={{ width: 56, height: 40, borderRadius: 8, overflow: "hidden", flexShrink: 0 }}>
                      <AptArchHero aptId={a.id} />
                    </div>
                    <div className="grow">
                      <div className="b500">{a.name}</div>
                      <div className="muted txt-xs">{a.neighborhood} · {a.type === "rooms" ? tt("at.roomsAvailable", { n: vacant, total: rooms }) : (tenants.length ? tt("at.currentlyLet") : tt("at.vacant"))}</div>
                    </div>
                    {selected && <Icon name="check" size={16} style={{ color: "var(--ef-accent)" }} />}
                  </button>
                );
              })}
            </div>
          </div>

          {apt && apt.type === "rooms" && (
            <div className="field">
              <label>{tt("at.room")}</label>
              {vacantRooms.length === 0 ? (
                <div className="muted txt-sm" style={{ padding: 10, background: "var(--ef-warn-soft)", borderRadius: 8, color: "var(--ef-warn)" }}>
                  {tt("at.noVacant")}
                </div>
              ) : (
                <div className="flex gap-2" style={{ flexWrap: "wrap" }}>
                  {Array.from({ length: apt.bedrooms }, (_, i) => i + 1).map((r) => {
                    const tn = data.tenants.find((t) => t.aptId === apt.id && t.room === r && t.status === "active");
                    const selected = String(form.room) === String(r);
                    return (
                      <button key={r} type="button" disabled={!!tn}
                              onClick={() => upd("room", r)}
                              className="card"
                              style={{ padding: "10px 14px", cursor: tn ? "not-allowed" : "pointer",
                                       opacity: tn ? 0.5 : 1,
                                       background: selected ? "var(--ef-accent-soft)" : "var(--ef-bg)",
                                       borderColor: selected ? "var(--ef-accent)" : "var(--ef-line)",
                                       minWidth: 90, textAlign: "left" }}>
                        <div className="muted txt-xs">{tt("at.room")}</div>
                        <div className="num b500" style={{ fontSize: 18 }}>{r}</div>
                        <div className="txt-xs" style={{ marginTop: 2, color: tn ? "var(--ef-muted)" : "var(--ef-accent-deep)" }}>
                          {tn ? tt("at.taken") : tt("at.vacant")}
                        </div>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {step === 2 && (
        <div className="flex col gap-4" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="field-row">
            <div className="field">
              <label htmlFor="addtenant-name">{tt("at.fullName")}</label>
              <input id="addtenant-name" value={form.name} onChange={(e) => upd("name", e.target.value)} placeholder={tt("at.namePh")} />
            </div>
            <div className="field">
              <label htmlFor="addtenant-country">{tt("at.country")}</label>
              <select id="addtenant-country" value={form.country} onChange={(e) => upd("country", e.target.value)}>
                {Object.entries(FLAGS).map(([code, flag]) => (
                  <option key={code} value={code}>{flag} {code}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label htmlFor="addtenant-email">{tt("at.email")}</label>
              <input id="addtenant-email" type="email" value={form.email} onChange={(e) => upd("email", e.target.value)} placeholder={tt("at.emailPh")}
                     style={!emailValid ? { borderColor: "var(--ef-danger, #C03A2B)" } : undefined}
                     aria-invalid={!emailValid} />
              {!emailValid && <span className="hint" style={{ color: "var(--ef-danger, #C03A2B)" }}>{tt("at.emailInvalid") || "Introduce un email válido."}</span>}
            </div>
            <div className="field">
              <label htmlFor="addtenant-phone">{tt("at.phone")}</label>
              <input id="addtenant-phone" value={form.phone} onChange={(e) => upd("phone", e.target.value)} placeholder={tt("at.phonePh")} />
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label htmlFor="addtenant-university">{tt("at.uni")}</label>
              <input id="addtenant-university" value={form.university} onChange={(e) => upd("university", e.target.value)} placeholder={tt("at.uniPh")} />
            </div>
            <div className="field">
              <label htmlFor="addtenant-age">{tt("at.age")}</label>
              <input id="addtenant-age" type="number" min="16" max="120" value={form.age} onChange={(e) => upd("age", e.target.value)}
                     style={!ageValid ? { borderColor: "var(--ef-danger, #C03A2B)" } : undefined}
                     aria-invalid={!ageValid} />
              {!ageValid && <span className="hint" style={{ color: "var(--ef-danger, #C03A2B)" }}>{tt("at.ageInvalid") || "Edad entre 16 y 120."}</span>}
            </div>
          </div>
        </div>
      )}

      {step === 3 && (
        <div className="flex col gap-4" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="field-row">
            <div className="field">
              <label htmlFor="addtenant-contract-start">{tt("at.contractStart")}</label>
              <input id="addtenant-contract-start" type="date" value={form.contractStart} onChange={(e) => upd("contractStart", e.target.value)} />
            </div>
            <div className="field">
              <label htmlFor="addtenant-contract-end">{tt("at.contractEnd")}</label>
              <input id="addtenant-contract-end" type="date" value={form.contractEnd} onChange={(e) => upd("contractEnd", e.target.value)}
                     style={!datesValid ? { borderColor: "var(--ef-danger, #C03A2B)" } : undefined}
                     aria-invalid={!datesValid} />
              {!datesValid && <span className="hint" style={{ color: "var(--ef-danger, #C03A2B)" }}>{tt("at.datesInvalid") || "La fecha de fin debe ser posterior al inicio."}</span>}
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label htmlFor="addtenant-rent">{tt("at.rent")}</label>
              <input id="addtenant-rent" type="number" value={form.rent} onChange={(e) => upd("rent", e.target.value)} />
              <span className="hint">{tt("at.aptAvg", { amt: fmtEUR(apt?.avg.rent) })}</span>
            </div>
            <div className="field">
              <label htmlFor="addtenant-deposit">{tt("at.deposit")}</label>
              <input id="addtenant-deposit" type="number" value={form.deposit} onChange={(e) => upd("deposit", e.target.value)} />
              <span className="hint">{tt("at.deposit.hint")}</span>
            </div>
          </div>
          <div className="field">
            <label htmlFor="addtenant-note">{tt("at.note")}</label>
            <textarea id="addtenant-note" rows="3" value={form.note} onChange={(e) => upd("note", e.target.value)} placeholder={tt("at.notePh")} />
          </div>
        </div>
      )}

      {step === 4 && (
        <div className="flex col gap-4" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="card tinted" style={{ display: "flex", gap: 14 }}>
            <div className="avatar lg a2">{initials(form.name || "?")}</div>
            <div className="grow">
              <div className="flex center gap-2"><div className="b500" style={{ fontSize: 16 }}>{form.name || "—"}</div><Flag code={form.country} /></div>
              <div className="muted txt-sm">{form.email || "—"} · {form.university || tt("at.noUni")}</div>
            </div>
          </div>
          <div className="flex col gap-2" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <ReviewRow label={tt("at.review.apt")} value={`${apt?.name} · ${apt?.neighborhood}`} />
            <ReviewRow label={tt("at.review.room")} value={apt?.type === "whole" ? tt("at.review.wholeFlat") : `${tt("at.room")} ${form.room}`} />
            <ReviewRow label={tt("at.review.contract")} value={`${fmtDate(form.contractStart, { short: true, withYear: true })} → ${fmtDate(form.contractEnd, { short: true, withYear: true })}`} />
            <ReviewRow label={tt("at.review.months")} value={tt("at.review.monthsVal", { n: monthsBetween(form.contractStart, form.contractEnd) })} />
            <ReviewRow label={tt("at.review.rent")} value={fmtEUR(form.rent)} />
            <ReviewRow label={tt("at.review.deposit")} value={fmtEUR(form.deposit)} />
            {form.note && <ReviewRow label={tt("at.review.note")} value={form.note} />}
          </div>
          <div className="card tinted txt-sm muted" style={{ background: "var(--ef-accent-soft)", color: "var(--ef-accent-deep)", border: 0 }}>
            <div className="flex center gap-2"><Icon name="check" size={14} /> {tt("at.review.firstBill", { amt: fmtEUR(Number(form.rent)) })}</div>
          </div>
        </div>
      )}
    </Modal>
  );
}

const ReviewRow = ({ label, value }) => (
  <div className="flex between" style={{ padding: "8px 0", borderBottom: "1px solid var(--ef-line)" }}>
    <span className="muted">{label}</span>
    <span className="b500">{value}</span>
  </div>
);

window.AddTenantModal = AddTenantModal;
