// PonteREI — property card + interest form + helpers

function PropertyCard({ p }) {
  const { locale } = useLocale();
  const { navigate } = useRouter();
  const f = p.financials;
  const modalityBadge = p.modality.length === 2 ? "badgeBoth" : (p.primaryModality === "inteiro" ? "badgeWhole" : "badgeShares");

  return (
    <article className="prop-card" onClick={() => navigate(`/property/${p.slug}`)}>
      <div className="prop-card-img" style={{ backgroundImage: `url(${p.images[0]})` }}>
        <div className="prop-card-badges">
          <span className="badge badge-primary">{t(`card.${modalityBadge}`, locale)}</span>
          {p.isJustAdded && <span className="badge badge-accent">{t("card.badgeJustAdded", locale)}</span>}
        </div>
        <button className="prop-card-fav" aria-label="Save" onClick={(e) => e.stopPropagation()}>
          <Icon.Heart />
        </button>
      </div>
      <div className="prop-card-body">
        <div className="prop-card-loc">
          {p.address.city}, {p.address.state || localized(p.address.country, locale)}
        </div>
        <h3 className="prop-card-title">{localized(p.title, locale)}</h3>
        <div className="prop-card-stats">
          <span><strong>{p.specs.bedrooms}</strong> {t("detail.bedrooms", locale)}</span>
          <span><strong>{p.specs.bathrooms}</strong> {t("detail.bathrooms", locale)}</span>
          <span><strong>{p.specs.areaSqm}</strong> m²</span>
        </div>
        <div className="prop-card-financials">
          <div>
            <div className="prop-card-fin-label">{t("card.fromShare", locale)}</div>
            <div className="prop-card-fin-value">{formatBRL(f.shareUnitPrice)}</div>
          </div>
          <div>
            <div className="prop-card-fin-label">{t("card.yield", locale)}</div>
            <div className="prop-card-fin-value yield-pct">{formatPctLocalized(f.projectedAnnualYield, locale)}</div>
          </div>
        </div>
        <div className="prop-progress">
          <div className="prop-progress-bar"><div className="prop-progress-fill" style={{ width: f.fundingProgressPct + "%" }} /></div>
          <div className="prop-progress-meta">
            <span>{f.fundingProgressPct}% {t("card.funded", locale)}</span>
            <span>{formatBRL(f.totalPrice, { compact: true })}</span>
          </div>
        </div>
      </div>
    </article>
  );
}

// Interest form
function InterestForm({ property, onSuccess, defaultModality = "cotas" }) {
  const { locale } = useLocale();
  const { push } = useToast();
  const [vals, setVals] = useState({ name: "", email: "", phone: "", modality: defaultModality, amount: "", message: "" });
  const [errs, setErrs] = useState({});
  const [submitting, setSubmitting] = useState(false);

  const set = (k, v) => setVals((cur) => ({ ...cur, [k]: v }));
  const validate = () => {
    const e = {};
    if (!vals.name.trim()) e.name = t("form.errRequired", locale);
    if (!vals.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) e.email = t("form.errEmail", locale);
    if (!vals.phone.replace(/\D/g, "").match(/^\d{8,15}$/)) e.phone = t("form.errPhone", locale);
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      push(t("form.success", locale));
      onSuccess && onSuccess();
    }, 900);
  };

  return (
    <form onSubmit={submit} noValidate>
      <div className="flex" style={{ gap: 12, marginBottom: 14 }}>
        <div style={{ flex: 1 }}>
          <label className="label">{t("form.name", locale)}</label>
          <input className={`input ${errs.name ? "input-error" : ""}`} placeholder={t("form.placeholderName", locale)} value={vals.name} onChange={(e) => set("name", e.target.value)} />
          {errs.name && <div className="error-msg">{errs.name}</div>}
        </div>
      </div>
      <div className="flex" style={{ gap: 12, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ flex: 1, minWidth: 180 }}>
          <label className="label">{t("form.email", locale)}</label>
          <input className={`input ${errs.email ? "input-error" : ""}`} type="email" placeholder={t("form.placeholderEmail", locale)} value={vals.email} onChange={(e) => set("email", e.target.value)} />
          {errs.email && <div className="error-msg">{errs.email}</div>}
        </div>
        <div style={{ flex: 1, minWidth: 180 }}>
          <label className="label">{t("form.phone", locale)}</label>
          <input className={`input ${errs.phone ? "input-error" : ""}`} placeholder={t("form.placeholderPhone", locale)} value={vals.phone} onChange={(e) => set("phone", e.target.value)} />
          {errs.phone && <div className="error-msg">{errs.phone}</div>}
        </div>
      </div>
      <div className="flex" style={{ gap: 12, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ flex: 1, minWidth: 180 }}>
          <label className="label">{t("form.modality", locale)}</label>
          <select className="select" value={vals.modality} onChange={(e) => set("modality", e.target.value)}>
            <option value="cotas">{t("modalities.cotasTitle", locale)}</option>
            <option value="inteiro">{t("modalities.inteiroTitle", locale)}</option>
          </select>
        </div>
        <div style={{ flex: 1, minWidth: 180 }}>
          <label className="label">{t("form.amount", locale)}</label>
          <input className="input" type="text" placeholder="R$ 10.000" value={vals.amount} onChange={(e) => set("amount", e.target.value)} />
        </div>
      </div>
      <div style={{ marginBottom: 18 }}>
        <label className="label">{t("form.message", locale)}</label>
        <textarea className="textarea" placeholder={t("form.placeholderMessage", locale)} value={vals.message} onChange={(e) => set("message", e.target.value)} />
      </div>
      <button type="submit" className="btn btn-primary btn-lg" style={{ width: "100%" }} disabled={submitting}>
        {submitting && <span className="spinner" />}
        {submitting ? t("form.submitting", locale) : t("form.submit", locale)}
      </button>
    </form>
  );
}

function Modal({ open, onClose, children, title }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Close"><Icon.Close /></button>
        {title && <h2 className="serif" style={{ marginTop: 0, fontSize: 28, marginBottom: 8 }}>{title}</h2>}
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { PropertyCard, InterestForm, Modal });
