// Contact form, footer, root App
const { useState: useS3, useRef: useR3, useEffect: useE3 } = React;

function Contact({ filters }) {
  const [form, setForm] = useS3({
    name: "",
    email: "",
    contact: "",
    contactMethod: "Line",
    budget: filters.budget !== "Any budget" ? filters.budget : "",
    area: filters.area !== "Any area" ? filters.area : "",
    moveIn: "",
    message: "",
  });
  const [sent, setSent] = useS3(false);
  const [sending, setSending] = useS3(false);
  const [error, setError] = useS3("");
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError("");
    try {
      await window.submitRentalInquiry({
        source: "Homepage shortlist form",
        name: form.name,
        email: form.email,
        contactMethod: form.contactMethod,
        contact: form.contact,
        budget: form.budget,
        area: form.area,
        moveIn: form.moveIn,
        message: form.message,
        userAgent: navigator.userAgent,
      });
      setSent(true);
    } catch (err) {
      setError("Please enter a valid email address before sending.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="contact" className="section contact" data-screen-label="Contact / enquiry">
      <div className="contact__inner">
        <div className="contact__left">
          <div className="eyebrow"><span className="eyebrow__dot"/> Start a rental shortlist</div>
          <h2 className="h2">Tell us what you're looking for. We'll handle the rest.</h2>
          <p className="contact__lede">
            One short brief is all we need. You'll hear back from a real person — usually within a few hours,
            always within one business day.
          </p>

          <div className="contact__channels">
            <a href="https://wa.me/66959920345" className="channel">
              <div className="channel__icon"><Icon name="whatsapp" size={18}/></div>
              <div>
                <div className="channel__label">WhatsApp / Line</div>
                <div className="channel__val">+66 95 992 0345</div>
              </div>
            </a>
            <a href="mailto:centralcityproperty@gmail.com" className="channel">
              <div className="channel__icon">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="5" width="18" height="14"/>
                  <path d="M3 7l9 6 9-6"/>
                </svg>
              </div>
              <div>
                <div className="channel__label">Email</div>
                <div className="channel__val">centralcityproperty@gmail.com</div>
              </div>
            </a>
            <div className="channel">
              <div className="channel__icon"><Icon name="pin" size={18}/></div>
              <div>
                <div className="channel__label">Office</div>
                <div className="channel__val">159 M 12 Nongprue Airfield Road Muang Pattaya, Bang Lamung District, Chon Buri 20150</div>
              </div>
            </div>
          </div>

          <figure className="contact__quote">
            <blockquote>
              "Jumphot handled everything from viewings to setting up our utilities. We moved from
              Berlin without ever flying to Pattaya beforehand — and the place was exactly what
              she described."
            </blockquote>
            <figcaption>
              <span>Marcus &amp; Léa</span> · 2-year lease, Wongamat
            </figcaption>
          </figure>
        </div>

        <form className="contact__form" onSubmit={submit}>
          {!sent ? (
            <>
              <div className="form__head">
                <h3>Request a rental shortlist</h3>
                <span className="form__badge">Free · No obligation</span>
              </div>
              <div className="form__grid">
                <Field label="Full name" required>
                  <input type="text" required value={form.name} onChange={set("name")} placeholder="e.g. Marcus Lindstrom"/>
                </Field>
                <Field label="Email address" required>
                  <input type="email" required value={form.email} onChange={set("email")} placeholder="you@email.com"/>
                </Field>
                <Field label="Contact" required hint="We'll reply on whichever you prefer">
                  <div className="form__contact">
                    <select value={form.contactMethod} onChange={set("contactMethod")} className="form__contact-method">
                      <option>Line</option>
                      <option>WeChat</option>
                      <option>WhatsApp</option>
                      <option>Telegram</option>
                    </select>
                    <input type="text" required value={form.contact} onChange={set("contact")} placeholder={form.contactMethod === "WeChat" ? "WeChat ID" : form.contactMethod === "Telegram" ? "@username" : "+66 ..."}/>
                  </div>
                </Field>
                <Field label="Monthly budget">
                  <select value={form.budget} onChange={set("budget")}>
                    <option value="">Select a range</option>
                    {window.BUDGET_OPTIONS.filter(b => b.label !== "Any budget").map((b) => (
                      <option key={b.label} value={b.label}>{b.label}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Preferred area">
                  <select value={form.area} onChange={set("area")}>
                    <option value="">Open to suggestions</option>
                    {window.AREA_OPTIONS.filter(a => a !== "Any area").map((a) => (
                      <option key={a} value={a}>{a}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Move-in" full>
                  <div className="form__inline">
                    {["This month","Next month","2–3 months","Flexible"].map((opt) => (
                      <label key={opt} className={`pillin ${form.moveIn === opt ? "is-on" : ""}`}>
                        <input type="radio" name="moveIn" value={opt} checked={form.moveIn === opt} onChange={set("moveIn")}/>
                        {opt}
                      </label>
                    ))}
                  </div>
                </Field>
                <Field label="Anything else we should know" full>
                  <textarea rows={3} value={form.message} onChange={set("message")} placeholder="Pets, must-have features, dates, family size, view preference…"/>
                </Field>
              </div>
              {error && <p className="form__error">{error}</p>}
              <div className="form__foot">
                <button type="submit" className="btn btn--primary btn--lg" disabled={sending}>
                  {sending ? "Sending..." : "Request a rental shortlist"} <Icon name="arrow" size={14}/>
                </button>
                <span className="form__legal">
                  By submitting, you agree to be contacted about Pattaya rentals. We never share your details.
                </span>
              </div>
            </>
          ) : (
            <div className="form__success">
              <div className="form__success-mark"><Icon name="check" size={22}/></div>
              <h3>Thanks{form.name ? `, ${form.name.split(" ")[0]}` : ""} — message received.</h3>
              <p>A member of the team will be in touch on <strong>{form.contactMethod}</strong> within 24 hours with a shortlist tailored to your brief.</p>
              <button type="button" className="link-arrow" onClick={() => { setSent(false); }}>Send another enquiry <Icon name="arrow" size={14}/></button>
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

function Field({ label, required, hint, full, children }) {
  return (
    <label className={`field ${full ? "field--full" : ""}`}>
      <span className="field__label">
        {label}{required && <span className="field__req">*</span>}
        {hint && <span className="field__hint">{hint}</span>}
      </span>
      {children}
    </label>
  );
}

const INFO_PAGES = {
  work: {
    eyebrow: "How we work",
    title: "A clear path from shortlist to move-in",
    intro: "Jumphot keeps the rental process personal and practical, with one point of contact from the first brief to handover.",
    points: [
      { title: "Brief", body: "Tell us your budget, preferred area, lease length, and lifestyle needs." },
      { title: "Shortlist", body: "We send suitable condos and villas, including options that may not be public yet." },
      { title: "Viewing", body: "We arrange viewings in person or by video, then help compare the real trade-offs." },
      { title: "Move-in", body: "Lease review, deposits, utilities, check-in inventory, and ongoing local support are coordinated in one place." },
    ],
  },
  tenant: {
    eyebrow: "Tenant guide",
    title: "What to know before renting in Pattaya",
    intro: "A quick guide for long-stay tenants preparing for a smooth rental, handover, and first month.",
    points: [
      { title: "Documents", body: "Prepare passport copy, visa details if available, contact details, and preferred move-in date." },
      { title: "Payments", body: "Most leases require first month rent plus two months security deposit before handover." },
      { title: "Utilities", body: "Electricity, water, internet, and building fees vary by property; we clarify them before you sign." },
      { title: "Handover", body: "Photograph the unit condition, confirm keys/access cards, and agree repair responsibilities in writing." },
    ],
  },
};

function InfoModal({ page, onClose }) {
  useE3(() => {
    if (!page) return;
    const onKey = (event) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [page, onClose]);

  if (!page) return null;

  return (
    <div className="info-modal" role="dialog" aria-modal="true" aria-labelledby="info-modal-title">
      <button className="info-modal__backdrop" type="button" aria-label="Close popup" onClick={onClose}/>
      <article className="info-modal__panel">
        <button className="info-modal__close" type="button" onClick={onClose} aria-label="Close popup">×</button>
        <div className="eyebrow"><span className="eyebrow__dot"/> {page.eyebrow}</div>
        <h2 id="info-modal-title">{page.title}</h2>
        <p className="info-modal__intro">{page.intro}</p>
        <div className="info-modal__grid">
          {page.points.map((point, index) => (
            <div className="info-modal__item" key={point.title}>
              <span>{String(index + 1).padStart(2, "0")}</span>
              <h3>{point.title}</h3>
              <p>{point.body}</p>
            </div>
          ))}
        </div>
      </article>
    </div>
  );
}

function Footer({ onOpenInfo }) {
  return (
    <footer className="ft" data-screen-label="Footer">
      <div className="ft__top">
        <div className="ft__brand">
          <div className="logo logo--light">
            <img className="logo__image logo__image--footer" src="/assets/img/js-crest-white.png" alt="Jumphot Srisomsap Pattaya Villas and Condominiums"/>
            <span className="logo__word">
              <span className="logo__name">Jumphot Srisomsap</span>
              <span className="logo__sub">Villas and Condos</span>
            </span>
          </div>
          <p>A small, independent rental agency. Monthly and long-term leases across Pattaya's best neighbourhoods.</p>
        </div>
        <div className="ft__col">
          <h4>Rentals</h4>
          <a href="/rentals">All listings</a>
          <a href="/rentals?type=Condo">Condos</a>
          <a href="/rentals?type=Villa">Villas</a>
          <a href="/rentals?type=Villa">Pool villas</a>
          <a href="/rentals">New this week</a>
        </div>
        <div className="ft__col">
          <h4>Areas</h4>
          {window.AREAS.map((a) => <a key={a.id} href={`/rentals?area=${encodeURIComponent(a.name)}`}>{a.name}</a>)}
        </div>
        <div className="ft__col">
          <h4>Company</h4>
          {onOpenInfo
            ? <button type="button" onClick={() => onOpenInfo("work")}>How we work</button>
            : <a href="/?info=work">How we work</a>}
          {onOpenInfo
            ? <button type="button" onClick={() => onOpenInfo("tenant")}>Tenant guide</button>
            : <a href="/?info=tenant">Tenant guide</a>}
          <a href="/#contact">Contact</a>
        </div>
        <div className="ft__col ft__col--contact">
          <h4>Get in touch</h4>
          <div className="ft__line"><Icon name="whatsapp" size={14}/> +66 95 992 0345</div>
          <div className="ft__line">centralcityproperty@gmail.com</div>
          <div className="ft__line">3rd Fl., Soi 5, Beach Rd.<br/>Pattaya, Chonburi 20150</div>
        </div>
      </div>
      <div className="ft__bot">
        <span>© 2026 Jumphot Srisomsap™. All rights reserved.</span>
        <span className="ft__legal">
          <span>EN · ไทย · РУС</span>
        </span>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────── Root

function App() {
  const [filters, setFilters] = useS3({
    type: "Any",
    area: "Any area",
    budget: "Any budget",
    beds: "Any",
  });
  const [propertyStats, setPropertyStats] = useS3({});
  const [infoPage, setInfoPage] = useS3(null);
  // Tick increments when /api/properties returns fresh listings — forces a re-render
  // so the homepage shows live data (not just the static fallback in data.jsx).
  const [, setListingsTick] = useS3(0);
  useE3(() => {
    const onListingsUpdated = () => setListingsTick((t) => t + 1);
    window.addEventListener("listings-updated", onListingsUpdated);
    return () => window.removeEventListener("listings-updated", onListingsUpdated);
  }, []);
  // Open an info modal when arriving via /?info=work|tenant (footer links from
  // other pages land here), then strip the param so a refresh doesn't reopen it.
  useE3(() => {
    const params = new URLSearchParams(window.location.search);
    const key = params.get("info");
    if (key && INFO_PAGES[key]) {
      setInfoPage(INFO_PAGES[key]);
      params.delete("info");
      const qs = params.toString();
      window.history.replaceState(null, "", window.location.pathname + (qs ? `?${qs}` : "") + window.location.hash);
    }
  }, []);
  const listingsRef = useR3(null);
  const contactRef = useR3(null);

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView ? window.scrollTo({ top: el.offsetTop - 70, behavior: "smooth" }) : null;
  };

  const handleEnquire = (property) => {
    const el = document.getElementById("contact");
    if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: "smooth" });
  };

  const handleAreaPick = (areaName) => {
    setFilters((f) => ({ ...f, area: areaName }));
    const el = document.getElementById("rentals");
    if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: "smooth" });
  };

  const handleCategorySelect = (cat) => {
    const typeMap = { condo: "Condo", villa: "Villa" };
    setFilters((f) => ({ ...f, type: typeMap[cat.id] || "Any" }));
    const el = document.getElementById("rentals");
    if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: "smooth" });
  };

  const handleSearch = () => {
    const params = new URLSearchParams();
    Object.entries(filters).forEach(([key, value]) => {
      if (value) params.set(key, value);
    });
    window.location.href = `/rentals?${params.toString()}`;
  };

  // Tweaks — useTweaks returns [t, setTweak]
  const [t, setTweak] = window.useTweaks
    ? window.useTweaks(TWEAK_DEFAULTS)
    : [TWEAK_DEFAULTS, () => {}];

  useE3(() => {
    document.documentElement.style.setProperty("--gold", t.accent || "#b8884a");
    document.documentElement.dataset.heroVariant = t.heroVariant || "still";
    document.documentElement.dataset.cardStyle = t.cardStyle || "editorial";
  }, [t.accent, t.heroVariant, t.cardStyle]);

  useE3(() => {
    if (!window.loadPropertyStats) return;
    window.loadPropertyStats().then(setPropertyStats);
  }, []);

  return (
    <div id="top">
      <Header onEnquire={() => handleEnquire()}/>
      <Hero filters={filters} setFilters={setFilters} onSearch={handleSearch}/>
      <window.TrustStrip/>
      <Listings filters={filters} setFilters={setFilters} listings={window.LISTINGS} propertyStats={propertyStats} onEnquire={handleEnquire}/>
      <Categories onSelect={handleCategorySelect}/>
      <AreaGuide onPick={handleAreaPick}/>
      <Process/>
      <Contact filters={filters}/>
      <Footer onOpenInfo={(key) => setInfoPage(INFO_PAGES[key])}/>
      <InfoModal page={infoPage} onClose={() => setInfoPage(null)}/>

      {window.TweaksPanel && (
        <window.TweaksPanel>
          <window.TweakSection label="Accent colour">
            <window.TweakColor
              value={t.accent}
              onChange={(v) => setTweak("accent", v)}
              options={["#b8884a", "#d97757", "#c9a45c", "#1a5577"]}
            />
          </window.TweakSection>
          <window.TweakSection label="Hero treatment">
            <window.TweakRadio
              value={t.heroVariant}
              onChange={(v) => setTweak("heroVariant", v)}
              options={[
                { value: "still", label: "Still" },
                { value: "duotone", label: "Duotone" },
              ]}
            />
          </window.TweakSection>
          <window.TweakSection label="Card style">
            <window.TweakRadio
              value={t.cardStyle}
              onChange={(v) => setTweak("cardStyle", v)}
              options={[
                { value: "editorial", label: "Editorial" },
                { value: "compact", label: "Compact" },
              ]}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

Object.assign(window, { Footer, Contact, Field, InfoModal, App });

if (document.getElementById("root") && document.documentElement.dataset.page !== "property") {
  ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
}
