// Listings grid, categories, area guide, process, contact
const { useState: useState2, useMemo: useMemo2, useRef: useRef2, useEffect: useEffect2 } = React;

// ─────────────────────────────────────────────────── Listings

function Listings({ filters, setFilters, listings, propertyStats = {}, onEnquire }) {
  const [sort, setSort] = useState2("featured");
  const filtered = useMemo2(() => {
    let list = listings.filter((p) => {
      if (filters.type && filters.type !== "Any" && p.type !== filters.type) return false;
      if (filters.area && filters.area !== "Any area" && p.area !== filters.area) return false;
      if (filters.beds && filters.beds !== "Any") {
        const need = filters.beds === "4+" ? 4 : parseInt(filters.beds, 10);
        if (filters.beds === "4+" ? p.beds < 4 : p.beds !== need) return false;
      }
      if (filters.budget && filters.budget !== "Any budget") {
        const b = window.BUDGET_OPTIONS.find((o) => o.label === filters.budget);
        if (b && (p.price < b.min || p.price > b.max)) return false;
      }
      return true;
    });
    if (sort === "featured") list = window.sortListingsByEngagement ? window.sortListingsByEngagement(list, propertyStats) : list;
    if (sort === "low") list = [...list].sort((a,b) => a.price - b.price);
    if (sort === "high") list = [...list].sort((a,b) => b.price - a.price);
    if (sort === "size") list = [...list].sort((a,b) => b.sqm - a.sqm);
    return list;
  }, [filters, listings, propertyStats, sort]);

  const activeFilters = [
    filters.type !== "Any" && { key: "type", label: filters.type, reset: "Any" },
    filters.area !== "Any area" && { key: "area", label: filters.area, reset: "Any area" },
    filters.budget !== "Any budget" && { key: "budget", label: filters.budget, reset: "Any budget" },
    filters.beds !== "Any" && { key: "beds", label: `${filters.beds} bed${filters.beds === "1" ? "" : "s"}`, reset: "Any" },
  ].filter(Boolean);

  const clearAll = () => setFilters({ type: "Any", area: "Any area", budget: "Any budget", beds: "Any" });
  const clearOne = (key, reset) => setFilters((f) => ({ ...f, [key]: reset }));

  // The homepage only previews the top matches; the full set lives on /rentals.
  const MAX_FEATURED = 11;
  const visible = filtered.slice(0, MAX_FEATURED);
  const moreHref = (() => {
    const params = new URLSearchParams();
    Object.entries(filters).forEach(([k, v]) => { if (v) params.set(k, v); });
    const qs = params.toString();
    return qs ? `/rentals?${qs}` : "/rentals";
  })();

  return (
    <section id="rentals" className="section listings" data-screen-label="Featured rentals">
      <div className="section__head">
        <div>
          <div className="eyebrow"><span className="eyebrow__dot"/> Currently letting</div>
          <h2 className="h2">Featured rentals this month</h2>
        </div>
        <div className="section__head-meta">
          <span className="count">
            <strong>{filtered.length}</strong> {filtered.length === 1 ? "property" : "properties"} match
          </span>
          <label className="sort">
            <span>Sort</span>
            <div className="sort__ctrl">
              <select value={sort} onChange={(e) => setSort(e.target.value)}>
                <option value="featured">Recommended</option>
                <option value="low">Price: low to high</option>
                <option value="high">Price: high to low</option>
                <option value="size">Size: largest first</option>
              </select>
              <Icon name="arrowDown" size={12}/>
            </div>
          </label>
        </div>
      </div>

      {activeFilters.length > 0 && (
        <div className="active-filters">
          <span className="active-filters__label">Filtering by</span>
          <div className="active-filters__chips">
            {activeFilters.map((f) => (
              <button key={f.key} className="afilter" onClick={() => clearOne(f.key, f.reset)}>
                {f.label}
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
                  <path d="M6 6l12 12M18 6L6 18"/>
                </svg>
              </button>
            ))}
            <button className="afilter__clear" onClick={clearAll}>Clear all</button>
          </div>
        </div>
      )}

      {filtered.length === 0 ? (
        <div className="empty">
          <div className="empty__title">No matches with these filters.</div>
          <div className="empty__body">We have ~240 properties off-platform. Tell us your brief and we'll send a tailored shortlist within 24 hours.</div>
          <button className="btn btn--primary" onClick={onEnquire}>Request a shortlist <Icon name="arrow" size={14}/></button>
        </div>
      ) : (
        <div className="grid grid--cards">
          {visible.map((p, i) => (
            <ListingCard
              key={p.id}
              p={p}
              wide={i === 0 && visible.length >= 3 && sort === "featured"}
              onEnquire={onEnquire}
            />
          ))}
        </div>
      )}

      <div className="section__foot">
        {filtered.length > MAX_FEATURED ? (
          <a href={moreHref} className="btn btn--primary">
            See all {filtered.length} properties <Icon name="arrow" size={14}/>
          </a>
        ) : (
          <a href="/rentals" className="link-arrow">
            Browse the full portfolio <Icon name="arrow" size={14}/>
          </a>
        )}
      </div>
    </section>
  );
}

function ListingCard({ p, wide, onEnquire }) {
  const [saved, setSaved] = useState2(false);
  const href = window.propertyHref(p);
  const trackClick = () => window.trackPropertyEvent && window.trackPropertyEvent(p.id, "click");
  return (
    <article className={`card ${wide ? "card--wide" : ""}`}>
      <a href={href} className="card__media" aria-label={`View ${p.title}`} onClick={trackClick}>
        <img src={p.image} alt={p.title} loading="lazy"/>
        <div className="card__tags">
          <Pill tone="ink">{p.type}</Pill>
          {p.badge && <Pill tone="gold">{p.badge}</Pill>}
        </div>
        <button
          className={`card__save ${saved ? "is-saved" : ""}`}
          onClick={(e) => { e.preventDefault(); e.stopPropagation(); setSaved(!saved); if (!saved && window.trackPropertyEvent) window.trackPropertyEvent(p.id, "save"); }}
          aria-label={saved ? "Unsave" : "Save"}
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill={saved ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round">
            <path d="M6 4h12v17l-6-4-6 4z"/>
          </svg>
        </button>
        {wide && (
          <div className="card__gallery-hint">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="14" height="14"/><path d="M7 7h14v14H7z"/></svg>
            <span>12 photos</span>
          </div>
        )}
      </a>
      <div className="card__body">
        <div className="card__loc">
          <Icon name="pin" size={12}/> {p.area} · {p.floor}
        </div>
        <a href={href} className="card__title-link" onClick={trackClick}>
          <h3 className="card__title">{p.title}</h3>
        </a>
        {wide && (
          <p className="card__desc">
            A high-floor residence with framed views over the Wongamat coastline. Recently
            refurbished by a Bangkok-based studio, with white-oak floors, a marble galley
            kitchen, and a sheltered north-facing balcony.
          </p>
        )}
        <ul className="card__features">
          {p.features.map((f) => <li key={f}>{f}</li>)}
        </ul>
        <div className="card__specs">
          <span><Icon name="bed" size={14}/> {p.beds} bed</span>
          <span><Icon name="bath" size={14}/> {p.baths} bath</span>
          <span><Icon name="sqm" size={14}/> {p.sqm} m²</span>
          {wide && <span><Icon name="check" size={14}/> Furnished</span>}
        </div>
        <div className="card__foot">
          <div className="card__price">
            <span className="card__price-amt">{fmtTHB(p.price)}</span>
            <span className="card__price-unit">/ month · {p.lease}</span>
          </div>
          <a href={href} className="btn btn--outline btn--sm" onClick={trackClick}>
            {wide ? "View villa" : "View"} <Icon name="arrow" size={12}/>
          </a>
        </div>
        <div className="card__social-proof" aria-label="Recent activity">
          <span className="card__social-proof-dot"/>
          <strong>{window.dailyInquiryCount && window.dailyInquiryCount(p.id)}</strong>&nbsp;people inquired in the last 24h
        </div>
      </div>
    </article>
  );
}

// ─────────────────────────────────────────────────── Categories

function Categories({ onSelect }) {
  return (
    <section id="services" className="section section--alt categories" data-screen-label="Rental categories">
      <div className="section__head">
        <div>
          <div className="eyebrow"><span className="eyebrow__dot"/> What we let</div>
          <h2 className="h2">Two ways to live in Pattaya</h2>
        </div>
        <p className="section__lede">
          Choose between lock-up-and-leave condos and private villas — we work across both
          rental styles, but only with stock we'd actually recommend.
        </p>
      </div>
      <div className="grid grid--cats">
        {window.CATEGORIES.map((c, i) => (
          <button key={c.id} className="cat" style={{"--i": i}} onClick={() => onSelect(c)}>
            <div className="cat__media">
              <img src={c.image} alt=""/>
              <div className="cat__num">{String(i+1).padStart(2,"0")}</div>
            </div>
            <div className="cat__body">
              <div className="cat__head">
                <h3 className="cat__name">{c.name}</h3>
                <span className="cat__count">{c.count} available</span>
              </div>
              <p className="cat__blurb">{c.blurb}</p>
              <ul className="cat__perks">
                {c.perks.map((p) => <li key={p}><Icon name="check" size={12}/> {p}</li>)}
              </ul>
              <div className="cat__foot">
                <span className="cat__from">From <strong>{fmtTHBshort(c.fromPrice)}</strong> / month</span>
                <span className="cat__cta">Browse {c.name.toLowerCase()} <Icon name="arrow" size={14}/></span>
              </div>
            </div>
          </button>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────── Area guide (map style)

const SERVICES = [
  {
    number: "01",
    title: "Housekeeping",
    body: "Professional cleaning, linen changes, and scheduled maintenance for long stays.",
    image: "/assets/img/service-housekeeping.png",
  },
  {
    number: "02",
    title: "Relocation Support",
    body: "Move-in assistance, area guidance, SIM cards, transport setup, and local onboarding.",
    image: "/assets/img/service-relocation.png",
  },
  {
    number: "03",
    title: "AC Cleaning & Maintenance",
    body: "Routine air-conditioning cleaning and preventive maintenance for comfortable living.",
    image: "/assets/img/service-ac-maintenance.png",
  },
  {
    number: "04",
    title: "Airport Transfers",
    body: "Private pickup and drop-off services for seamless arrivals and departures.",
    image: "/assets/img/service-airport-transfers.png",
  },
];

Categories = function Categories() {
  return (
    <section id="services" className="section section--alt services" data-screen-label="Services">
      <div className="section__head">
        <div>
          <div className="eyebrow"><span className="eyebrow__dot"/> Services</div>
          <h2 className="h2">Support for every part of your stay</h2>
        </div>
        <p className="section__lede">
          From arrival to long-stay upkeep, Jumphot can arrange the practical details that make
          living in Pattaya easier.
        </p>
      </div>
      <div className="services__grid">
        {SERVICES.map((service) => (
          <article key={service.number} className="service-card">
            <div className="service-card__media">
              <img src={service.image} alt="" loading="lazy"/>
              <div className="service-card__num">{service.number}</div>
            </div>
            <div className="service-card__body">
              <h3>{service.title}</h3>
              <p>{service.body}</p>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
};

function AreaGuide({ onPick }) {
  const [active, setActive] = useState2("wongamat");
  const current = window.AREAS.find((a) => a.id === active);
  return (
    <section id="areas" className="section areas" data-screen-label="Pattaya area guide">
      <div className="section__head">
        <div>
          <div className="eyebrow"><span className="eyebrow__dot"/> Pattaya, neighbourhood by neighbourhood</div>
          <h2 className="h2">Five areas. Five different lives.</h2>
        </div>
        <p className="section__lede">
          Pattaya isn't one place. Choose the coast, the hill, or the suburbs — each suits a different kind of stay.
        </p>
      </div>

      <div className="areas__layout">
        <div className="areas__map" role="group" aria-label="Pattaya map">
          <svg className="areas__svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice">
            <defs>
              <pattern id="sea" width="4" height="4" patternUnits="userSpaceOnUse">
                <path d="M0 2 q1 -1 2 0 t2 0" fill="none" stroke="rgba(255,255,255,.10)" strokeWidth="0.3"/>
              </pattern>
              <radialGradient id="land" cx="60%" cy="40%" r="80%">
                <stop offset="0" stopColor="#ece3cf"/>
                <stop offset="0.6" stopColor="#ddd0b1"/>
                <stop offset="1" stopColor="#c4b48d"/>
              </radialGradient>
              <filter id="grain" x="0" y="0" width="100%" height="100%">
                <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2"/>
                <feColorMatrix values="0 0 0 0 0.4  0 0 0 0 0.3  0 0 0 0 0.1  0 0 0 0.05 0"/>
              </filter>
            </defs>

            {/* sea */}
            <rect x="0" y="0" width="100" height="100" fill="#0e3e3c"/>
            <rect x="0" y="0" width="100" height="100" fill="url(#sea)"/>

            {/* depth shading */}
            <ellipse cx="10" cy="50" rx="40" ry="60" fill="#072422" opacity="0.5"/>

            {/* coastline shape — Pattaya bay curls */}
            <path
              d="M 100 0
                 L 22 0
                 Q 28 8 24 14
                 Q 18 22 26 28
                 Q 34 32 30 40
                 Q 24 48 32 54
                 Q 38 56 36 62
                 Q 30 70 38 76
                 Q 46 82 40 90
                 Q 36 96 44 100
                 L 100 100 Z"
              fill="url(#land)"
              stroke="rgba(255,255,255,.5)"
              strokeWidth="0.4"
            />

            {/* subtle elevation lines on land */}
            <g opacity="0.18" fill="none" stroke="#7a6638" strokeWidth="0.2">
              <path d="M 60 30 Q 50 36 55 46 Q 60 56 50 62"/>
              <path d="M 70 22 Q 60 30 64 42 Q 68 54 58 60"/>
              <path d="M 82 18 Q 72 28 76 42 Q 80 56 70 64"/>
            </g>

            {/* Pratumnak hill marker */}
            <g opacity="0.6">
              <path d="M 36 54 l 4 -7 l 4 7 z" fill="#a89055" stroke="#5b4b2c" strokeWidth="0.2"/>
              <text x="46" y="52" fontSize="2.2" fill="#5b4b2c" fontFamily="Instrument Serif" fontStyle="italic">Pratumnak</text>
            </g>

            {/* beach line decorations */}
            <g stroke="rgba(255,255,255,.4)" strokeWidth="0.15" fill="none">
              <path d="M 24 16 Q 23 18 25 22"/>
              <path d="M 26 30 Q 25 34 28 38"/>
              <path d="M 32 52 Q 30 56 33 60"/>
              <path d="M 38 76 Q 36 80 40 84"/>
            </g>

            {/* sea label */}
            <text x="6" y="38" fontSize="2.2" fill="rgba(255,255,255,.45)" fontFamily="Instrument Serif" fontStyle="italic" letterSpacing="2">GULF OF THAILAND</text>
            <text x="6" y="42" fontSize="1.4" fill="rgba(255,255,255,.3)" letterSpacing="3">12°57′N · 100°53′E</text>

            {/* roads */}
            <path d="M 30 14 Q 36 40 50 100" stroke="rgba(255,255,255,.18)" strokeWidth="0.3" strokeDasharray="0.8 0.8" fill="none"/>
            <path d="M 50 0 Q 56 30 64 60 Q 70 80 78 100" stroke="rgba(255,255,255,.12)" strokeWidth="0.25" strokeDasharray="0.6 0.6" fill="none"/>
          </svg>

          {window.AREAS.map((a) => (
            <button
              key={a.id}
              className={`pin ${active === a.id ? "is-active" : ""}`}
              style={{ left: `${a.coord.x}%`, top: `${a.coord.y}%` }}
              onMouseEnter={() => setActive(a.id)}
              onFocus={() => setActive(a.id)}
              onClick={() => setActive(a.id)}
              aria-label={a.name}
            >
              <span className="pin__dot"/>
              <span className="pin__pulse"/>
              <span className="pin__label">{a.name}</span>
            </button>
          ))}

          <div className="areas__compass" aria-hidden="true">
            <div className="areas__compass-n">N</div>
            <svg viewBox="0 0 40 40"><path d="M20 4 L24 20 L20 36 L16 20 Z" fill="#0e3e3c" opacity="0.7"/></svg>
          </div>

          <div className="areas__legend">
            <div className="areas__legend-row">
              <span className="areas__legend-dot"/> Currently letting
            </div>
            <div className="areas__legend-scale">
              <span>0</span>
              <span className="areas__legend-bar"/>
              <span>2 km</span>
            </div>
          </div>
        </div>

        <aside className="areas__panel">
          <div className="areas__list">
            {window.AREAS.map((a) => (
              <button
                key={a.id}
                className={`arow ${active === a.id ? "is-active" : ""}`}
                onMouseEnter={() => setActive(a.id)}
                onFocus={() => setActive(a.id)}
                onClick={() => onPick(a.name)}
              >
                <span className="arow__name">{a.name}</span>
                <span className="arow__tag">{a.tag}</span>
                <span className="arow__count">{a.properties}</span>
              </button>
            ))}
          </div>
          <div className="areas__detail">
            <img src={current.image} alt="" className="areas__img"/>
            <div className="areas__detail-body">
              <div className="areas__detail-head">
                <h3>{current.name}</h3>
                <span className="areas__detail-tag">{current.tag}</span>
              </div>
              <p>{current.blurb}</p>
              <div className="areas__detail-stats">
                <div>
                  <span>Available</span>
                  <strong>{current.properties} properties</strong>
                </div>
                <div>
                  <span>Avg. rent</span>
                  <strong>{fmtTHB(current.avg)}/mo</strong>
                </div>
              </div>
              <button className="link-arrow" onClick={() => onPick(current.name)}>
                See {current.name} rentals <Icon name="arrow" size={14}/>
              </button>
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────── Process

function Process() {
  return (
    <section className="section section--ink process" data-screen-label="Service process">
      <div className="section__head">
        <div>
          <div className="eyebrow eyebrow--light"><span className="eyebrow__dot"/> How we work</div>
          <h2 className="h2 h2--light">Four steps. One contact. No surprises.</h2>
        </div>
        <p className="section__lede section__lede--light">
          We've shortened the rental process to what actually matters. You'll deal with one
          person from first message to move-in day.
        </p>
      </div>
      <ol className="steps">
        {window.PROCESS.map((s, i) => (
          <li key={s.n} className="step">
            <div className="step__head">
              <span className="step__n">{s.n}</span>
              <span className="step__line"/>
            </div>
            <h3 className="step__title">{s.title}</h3>
            <p className="step__body">{s.body}</p>
            {i === 0 && <span className="step__time">Avg. 5 min</span>}
            {i === 1 && <span className="step__time">Within 24 hr</span>}
            {i === 2 && <span className="step__time">Same-day viewing</span>}
            {i === 3 && <span className="step__time">Ongoing</span>}
          </li>
        ))}
      </ol>
    </section>
  );
}

Object.assign(window, { Listings, ListingCard, Categories, AreaGuide, Process });
