/* global React, Arrow, BedIcon, BathIcon, AreaIcon, WhatsAppIcon, PhoneIcon */
// ============================================================
// Espace — forms + cards
// ============================================================

// ── Generic form runner ───────────────────────────────────────
function useForm(initial, validators = {}) {
  const [values, setValues] = React.useState(initial);
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  const set = (k, v) => setValues(prev => ({ ...prev, [k]: v }));

  const validate = () => {
    const errs = {};
    for (const k of Object.keys(validators)) {
      const msg = validators[k](values[k], values);
      if (msg) errs[k] = msg;
    }
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const submit = (e) => {
    e.preventDefault();
    if (validate()) setSubmitted(true);
  };

  return { values, errors, submitted, set, submit };
}

const required = (v) => (!v || (typeof v === "string" && !v.trim())) ? "Required" : "";
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const validEmail = (v) => !v ? "Required" : !emailRe.test(v) ? "Enter a valid email" : "";
const validPhone = (v) => !v ? "Required" : (v.replace(/[^0-9]/g, "").length < 7) ? "Enter a valid phone" : "";

// ── Field ─────────────────────────────────────────────────────
function Field({ label, error, children, full }) {
  return (
    <div className={`field ${error ? "error" : ""} ${full ? "form-full" : ""}`}>
      <label>{label}</label>
      {children}
      {error && <div className="err-msg">{error}</div>}
    </div>
  );
}

// ── Viewing form ──────────────────────────────────────────────
function ViewingForm({ dark, communityId, agentId, listingRef, compact }) {
  const f = useForm(
    { name: "", phone: "", email: "", listingRef: listingRef || "", date: "", time: "", msg: "", _gotcha: "" },
    { name: required, phone: validPhone, email: validEmail }
  );

  if (f.submitted) return <SuccessPanel dark={dark} title="We're on it" body={`Thanks ${f.values.name.split(" ")[0]}. A consultant will confirm your viewing within the hour during office hours (Mon–Fri 9am–6pm).`} whatsapp={f.values} kind="viewing" />;

  return (
    <form className={`form ${dark ? "form-dark" : ""}`} onSubmit={f.submit} noValidate>
      <input type="text" name="_gotcha" tabIndex="-1" autoComplete="off" style={{ position: "absolute", left: "-9999px" }} value={f.values._gotcha} onChange={e => f.set("_gotcha", e.target.value)} />
      <div className="form-row">
        <Field label="Full name *" error={f.errors.name}>
          <input type="text" value={f.values.name} onChange={e => f.set("name", e.target.value)} placeholder="Jane Doe" />
        </Field>
        <Field label="Phone *" error={f.errors.phone}>
          <input type="tel" value={f.values.phone} onChange={e => f.set("phone", e.target.value)} placeholder="+971 …" />
        </Field>
      </div>
      <Field label="Email *" error={f.errors.email} full>
        <input type="email" value={f.values.email} onChange={e => f.set("email", e.target.value)} placeholder="you@example.com" />
      </Field>
      {!compact && (
        <div className="form-row">
          <Field label="Preferred date">
            <input type="date" value={f.values.date} onChange={e => f.set("date", e.target.value)} />
          </Field>
          <Field label="Preferred time">
            <select value={f.values.time} onChange={e => f.set("time", e.target.value)}>
              <option value="">Select…</option>
              <option>Morning (9–12)</option>
              <option>Afternoon (12–4)</option>
              <option>Late afternoon (4–6)</option>
            </select>
          </Field>
        </div>
      )}
      {listingRef && (
        <Field label="Listing reference" full>
          <input type="text" value={f.values.listingRef} onChange={e => f.set("listingRef", e.target.value)} readOnly />
        </Field>
      )}
      <Field label="Anything we should know?" full>
        <textarea rows={2} value={f.values.msg} onChange={e => f.set("msg", e.target.value)} placeholder="Schools, parking, off-plan vs ready — context helps."></textarea>
      </Field>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
        <button type="submit" className={`btn ${dark ? "btn-primary" : "btn-ink"}`}>Book a viewing <Arrow /></button>
        <a className={`btn ${dark ? "btn-ghost-light" : "btn-outline"}`} href="https://wa.me/971568296862" target="_blank" rel="noopener">
          <WhatsAppIcon size={14} /> WhatsApp instead
        </a>
      </div>
      <div className="body-sm" style={{ marginTop: 8, fontSize: 11, color: dark ? "rgba(255,255,255,.5)" : "var(--muted)" }}>
        Leads route to the CRM and your consultant. We never share your details. Fields marked * are required.
      </div>
    </form>
  );
}

// ── Valuation form ────────────────────────────────────────────
function ValuationForm({ dark }) {
  const f = useForm(
    { name: "", phone: "", email: "", type: "Villa", community: "", beds: "", size: "", purpose: "Sell", _gotcha: "" },
    { name: required, phone: validPhone, email: validEmail }
  );

  if (f.submitted) return <SuccessPanel dark={dark} title="Valuation requested" body={`Thanks ${f.values.name.split(" ")[0]} — a consultant who knows ${f.values.community || "your community"} will come back with a realistic range. No bots, no guesswork. Usually within one business day.`} whatsapp={f.values} kind="valuation" />;

  return (
    <form className={`form ${dark ? "form-dark" : ""}`} onSubmit={f.submit} noValidate>
      <div className="form-row">
        <Field label="Full name *" error={f.errors.name}>
          <input type="text" value={f.values.name} onChange={e => f.set("name", e.target.value)} placeholder="Jane Doe" />
        </Field>
        <Field label="Phone *" error={f.errors.phone}>
          <input type="tel" value={f.values.phone} onChange={e => f.set("phone", e.target.value)} placeholder="+971 …" />
        </Field>
      </div>
      <Field label="Email *" error={f.errors.email} full>
        <input type="email" value={f.values.email} onChange={e => f.set("email", e.target.value)} placeholder="you@example.com" />
      </Field>
      <div className="form-row">
        <Field label="Property type">
          <select value={f.values.type} onChange={e => f.set("type", e.target.value)}>
            <option>Villa</option><option>Townhouse</option><option>Apartment</option><option>Penthouse</option><option>Commercial</option>
          </select>
        </Field>
        <Field label="Community / tower">
          <input type="text" value={f.values.community} onChange={e => f.set("community", e.target.value)} placeholder="e.g. Arabian Ranches – Saheel" />
        </Field>
      </div>
      <div className="form-row">
        <Field label="Bedrooms">
          <select value={f.values.beds} onChange={e => f.set("beds", e.target.value)}>
            <option value="">—</option>
            <option>Studio</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6+</option>
          </select>
        </Field>
        <Field label="Approx size (sqft)">
          <input type="text" value={f.values.size} onChange={e => f.set("size", e.target.value)} placeholder="e.g. 4,200" />
        </Field>
      </div>
      <Field label="Purpose" full>
        <select value={f.values.purpose} onChange={e => f.set("purpose", e.target.value)}>
          <option>Sell</option><option>Let</option><option>Just curious</option>
        </select>
      </Field>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
        <button type="submit" className={`btn ${dark ? "btn-primary" : "btn-ink"}`}>Request my valuation <Arrow /></button>
        <a className={`btn ${dark ? "btn-ghost-light" : "btn-outline"}`} href="https://wa.me/971568296862" target="_blank" rel="noopener">
          <WhatsAppIcon size={14} /> WhatsApp
        </a>
      </div>
      <div style={{ marginTop: 8, fontSize: 11, color: dark ? "rgba(255,255,255,.5)" : "var(--muted)", fontStyle: "italic" }}>
        We never compute or display a figure online. A consultant will come back with a realistic range — no bots, no guesswork.
      </div>
    </form>
  );
}

// ── Success panel ─────────────────────────────────────────────
function SuccessPanel({ dark, title, body, whatsapp, kind }) {
  const msg = encodeURIComponent(`Hi Espace, I just requested a ${kind}.`);
  return (
    <div className={`form-success ${dark ? "" : ""}`}>
      <h4>{title}</h4>
      <p>{body}</p>
      <div style={{ display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap" }}>
        <a className={`btn btn-sm ${dark ? "btn-primary" : "btn-ink"}`} href={`https://wa.me/971568296862?text=${msg}`} target="_blank" rel="noopener">
          <WhatsAppIcon size={12} /> Confirm on WhatsApp
        </a>
        <a className={`btn btn-sm ${dark ? "btn-ghost-light" : "btn-outline"}`} href="tel:+97143069999">
          <PhoneIcon /> Call instead
        </a>
      </div>
    </div>
  );
}

// ── Listing card (placeholder feed) ───────────────────────────
function ListingCard({ listing, onBook }) {
  const statusLabel = { sale: "For sale", rent: "For rent", luxury: "Luxury", offplan: "Off-plan" }[listing.status] || listing.status;
  return (
    <article className="listing-card" onClick={() => onBook && onBook(listing)}>
      <div className="media">
        <span className={`tag ${listing.status}`}>{statusLabel}</span>
        <div className="placeholder-label">
          Photo loads from feed
          <span className="hint">Property image · {listing.ref}</span>
        </div>
      </div>
      <div className="body">
        <div className="ref">{listing.ref}</div>
        <h3 className="ttl">{listing.title}</h3>
        <div className="sub">{(window.COMMUNITIES.find(c => c.id === listing.community) || {}).name}</div>
        <div className="specs">
          <span><BedIcon /> {listing.beds} bed</span>
          <span><BathIcon /> {listing.baths} bath</span>
          <span><AreaIcon /> {listing.sizeSqft.toLocaleString()} sqft</span>
        </div>
        <div className={`price ${listing.priceQualifier === "POA" ? "poa" : ""}`}>{listing.price}</div>
      </div>
    </article>
  );
}

// ── Agent card ────────────────────────────────────────────────
function AgentCard({ agent, onOpen }) {
  return (
    <article className="agent-card" onClick={() => onOpen && onOpen(agent.id)}>
      <div className="portrait">
        <img src={agent.img} alt={agent.name} loading="lazy" />
      </div>
      <h3 className="name">{agent.name}</h3>
      <div className="title">{agent.role}</div>
      <div className="langs">{agent.langs}</div>
    </article>
  );
}

// ── Community card ────────────────────────────────────────────
function CommunityCard({ community, span, featured, onOpen }) {
  const className = `community-card ${featured ? "featured" : ""} grid-span-${span}`;
  return (
    <article className={className} onClick={() => onOpen && onOpen(community.id)} role="link" tabIndex={0}
      onKeyDown={(e) => { if (e.key === "Enter") onOpen && onOpen(community.id); }}>
      <img src={community.img} alt={community.name} className="ph" loading="lazy" />
      <div className="overlay"></div>
      <div className="meta">
        <div>
          <div className="name">{community.name}</div>
          <div className="sub">{community.type} · {community.agents} consultants</div>
        </div>
        <div className="arrow-c">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3 11L11 3M11 3H4M11 3v7" stroke="currentColor" strokeWidth="1.4" />
          </svg>
        </div>
      </div>
    </article>
  );
}

// ── Communities grid (editorial bento) ───────────────────────
function CommunitiesGrid({ items, onOpen, layout }) {
  // editorial bento pattern for 22 items
  // 0: 6, 1: 6, 2: 4, 3: 4, 4: 4, 5: 3, 6: 3, 7: 3, 8: 3, then 4s
  if (layout === "uniform") {
    return (
      <div className="communities-grid">
        {items.map(c => (
          <CommunityCard key={c.id} community={c} span={3} onOpen={onOpen} />
        ))}
      </div>
    );
  }
  const spans = [6, 6, 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 6, 6, 4, 4, 4, 4];
  return (
    <div className="communities-grid">
      {items.map((c, i) => (
        <CommunityCard
          key={c.id}
          community={c}
          span={spans[i] || 3}
          featured={(spans[i] || 3) >= 6}
          onOpen={onOpen}
        />
      ))}
    </div>
  );
}

Object.assign(window, {
  useForm, required, validEmail, validPhone, Field,
  ViewingForm, ValuationForm, SuccessPanel,
  ListingCard, AgentCard, CommunityCard, CommunitiesGrid,
});
