﻿// Pattaya rentals â€” main app
const { useState, useEffect, useMemo, useRef } = React;

// Change FEATURED_PROPERTY_ID to swap which listing appears in the hero card.
// Pulls live data from window.LISTINGS so price / specs / image stay in sync with admin edits.
const FEATURED_PROPERTY_ID = "p22";

function FeaturedHeroCard() {
  const listings = (typeof window !== "undefined" && window.LISTINGS) || [];
  const details = (typeof window !== "undefined" && window.PROPERTY_DETAILS) || {};
  const property = listings.find((p) => p.id === FEATURED_PROPERTY_ID) || listings[0];
  if (!property) return null;
  const detail = details[property.id] || {};
  const gallery = Array.isArray(detail.gallery) ? detail.gallery : [];
  const image = gallery[0] || property.image || "";
  const meta = `${property.type || "Property"}${property.area ? " - " + property.area : ""}`;
  const href = window.propertyHref(property);
  return (
    <aside className="hero__preview">
      <div className="hero__preview-label">Letting now</div>
      <div className="hero__preview-card">
        <div className="hero__preview-img">
          {image ? <img src={image} alt={property.title}/> : null}
          <span className="pill pill--gold">Featured</span>
        </div>
        <div className="hero__preview-body">
          <div className="hero__preview-meta">{meta}</div>
          <h3>{property.title}</h3>
          <div className="hero__preview-specs">
            <span>{property.beds || 0} bed</span><i/>
            <span>{property.baths || 0} bath</span><i/>
            <span>{property.sqm || 0} sqm</span>
          </div>
          <div className="hero__preview-foot">
            <span className="hero__preview-price">{fmtTHB(property.price || 0)}<small>/mo</small></span>
            <a href={href} className="link-arrow link-arrow--sm">View <Icon name="arrow" size={12}/></a>
          </div>
          <div className="hero__preview-social" aria-label="Recent activity">
            <span className="hero__preview-social-dot"/>
            <strong>{window.dailyInquiryCount && window.dailyInquiryCount(property.id)}</strong>&nbsp;people inquired in the last 24h
          </div>
        </div>
      </div>
    </aside>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#b8884a",
  "heroVariant": "still",
  "cardStyle": "editorial"
}/*EDITMODE-END*/;

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ small atoms

const CURRENCY_OPTIONS = {
  THB: { label: "THB", symbol: "฿", rate: 1, locale: "th-TH", maxDigits: 0 },
  USD: { label: "USD", symbol: "$", rate: 32.3, locale: "en-US", maxDigits: 0 },
  EUR: { label: "EUR", symbol: "€", rate: 37.8, locale: "de-DE", maxDigits: 0 },
};

function getCurrency() {
  const saved = localStorage.getItem("jsCurrency") || "THB";
  return CURRENCY_OPTIONS[saved] ? saved : "THB";
}

function setCurrency(value) {
  localStorage.setItem("jsCurrency", CURRENCY_OPTIONS[value] ? value : "THB");
}

function convertPrice(n, currency = getCurrency()) {
  const config = CURRENCY_OPTIONS[currency] || CURRENCY_OPTIONS.THB;
  return Number(n || 0) / config.rate;
}

const fmtTHB = (n) => {
  const currency = getCurrency();
  const config = CURRENCY_OPTIONS[currency] || CURRENCY_OPTIONS.THB;
  const value = convertPrice(n, currency);
  return config.symbol + value.toLocaleString(config.locale, { maximumFractionDigits: config.maxDigits });
};
const fmtTHBshort = (n) => {
  const currency = getCurrency();
  const config = CURRENCY_OPTIONS[currency] || CURRENCY_OPTIONS.THB;
  const value = convertPrice(n, currency);
  if (value >= 1000) return config.symbol + (value / 1000).toFixed(value % 1000 === 0 ? 0 : 1) + "k";
  return config.symbol + value.toLocaleString(config.locale, { maximumFractionDigits: config.maxDigits });
};

const Pill = ({ children, tone = "ink" }) => (
  <span className={`pill pill--${tone}`}>{children}</span>
);

const Icon = ({ name, size = 16 }) => {
  if (name === "whatsapp") {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M20.5 3.5A11.8 11.8 0 0 0 12.1 0C5.5 0 .2 5.3.2 11.9c0 2.1.5 4.1 1.6 5.9L.1 24l6.3-1.7a11.9 11.9 0 0 0 5.7 1.4h.1c6.5 0 11.8-5.3 11.8-11.9 0-3.1-1.2-6.1-3.5-8.3Zm-8.4 18.3a9.9 9.9 0 0 1-5-1.4l-.4-.2-3.7 1 1-3.6-.2-.4a9.9 9.9 0 0 1-1.5-5.3c0-5.4 4.4-9.9 9.9-9.9 2.6 0 5.1 1 7 2.9a9.8 9.8 0 0 1 2.9 7c-.1 5.5-4.5 9.9-10 9.9Zm5.4-7.4c-.3-.1-1.8-.9-2-.9-.3-.1-.5-.2-.7.1-.2.3-.8 1-.9 1.2-.2.2-.4.2-.7.1-.3-.2-1.2-.5-2.4-1.5-.9-.8-1.5-1.8-1.6-2.1-.2-.3 0-.5.1-.6l.5-.5c.1-.2.2-.3.3-.5.1-.2.1-.4 0-.5 0-.2-.7-1.7-.9-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.2.2 2.1 3.2 5.1 4.5.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.4.2-.7.2-1.3.2-1.4-.2-.2-.4-.3-.7-.4Z"/>
      </svg>
    );
  }
  const paths = {
    search: <><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></>,
    bed: <><path d="M3 18v-7a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v7"/><path d="M3 14h18"/><path d="M3 18v3"/><path d="M21 18v3"/></>,
    bath: <><path d="M4 12h16v4a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4z"/><path d="M6 12V6a2 2 0 0 1 2-2h2"/><path d="M10 6h4"/><path d="M6 20l-1 2"/><path d="M18 20l1 2"/></>,
    sqm: <><rect x="3" y="3" width="18" height="18"/><path d="M3 9h6"/><path d="M3 15h6"/><path d="M15 3v6"/><path d="M15 15v6"/></>,
    pin: <><path d="M12 22s-7-6.5-7-12a7 7 0 0 1 14 0c0 5.5-7 12-7 12z"/><circle cx="12" cy="10" r="2.5"/></>,
    arrow: <><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></>,
    arrowDown: <><path d="M12 5v14"/><path d="M5 13l7 7 7-7"/></>,
    check: <path d="M5 12l4 4 10-10"/>,
    plus: <><path d="M12 5v14"/><path d="M5 12h14"/></>,
    whatsapp: <><path d="M3 21l1.5-5A8.5 8.5 0 1 1 8 19.5L3 21z"/><path d="M8.5 9.5c.5 2 2 3.5 4 4l1-1c.3-.3.7-.4 1-.2l1.5.6c.4.2.6.6.5 1l-.3 1c-.2.7-.9 1.2-1.6 1.1-2.6-.3-5.5-2.6-6-5.2-.1-.7.4-1.4 1.1-1.6l1-.3c.4-.1.8.1 1 .5l.6 1.5c.2.4.1.7-.2 1z"/></>,
    sparkle: <><path d="M12 3v18"/><path d="M3 12h18"/><path d="M5 5l14 14"/><path d="M19 5L5 19"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {paths[name]}
    </svg>
  );
};

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ header

function Header({ onEnquire }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [currencyOpen, setCurrencyOpen] = useState(false);
  const [currency, setCurrencyState] = useState(getCurrency());
  const isHome = !document.documentElement.dataset.page;
  const forceSolid = true;
  const hrefFor = (hash) => isHome ? hash : `/${hash}`;
  const changeCurrency = (value) => {
    setCurrency(value);
    setCurrencyState(value);
    window.location.reload();
  };
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className={`hdr ${scrolled || forceSolid ? "hdr--scrolled" : ""}`} data-screen-label="Header">
      <div className="hdr__topbar" role="note" aria-label="Reputation">
        <div className="hdr__topbar-inner">
          <span className="hdr__topbar-stars" aria-hidden="true">
            {[1,2,3,4,5].map((i) => (
              <svg key={i} width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 .6-5.3 4.6 1.6 7-6.3-3.8L5.7 21l1.6-7L2 9.6 9 9z"/></svg>
            ))}
          </span>
          <span className="hdr__topbar-text">
            Trusted by <strong>200+ expats</strong> in Pattaya
          </span>
          <span className="hdr__topbar-dot" aria-hidden="true"/>
          <span className="hdr__topbar-meta">DBD-licensed · 12 years on the ground</span>
        </div>
      </div>
      <div className="hdr__inner">
        <a href={isHome ? "#top" : "/"} className="logo" aria-label="Jumphot Srisomsap Pattaya villas and condominiums, home">
          <img className="logo__image" src="/assets/img/js-crest.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>
        </a>
        <nav className="nav" aria-label="Primary">
          <a href="/rentals">Rentals</a>
          <a href={hrefFor("#areas")}>Areas</a>
          <a href={hrefFor("#services")}>Services</a>
          <a href={hrefFor("#contact")}>Contact</a>
        </nav>
        <div className="hdr__cta">
          <CurrencyMenu currency={currency} open={currencyOpen} setOpen={setCurrencyOpen} onChange={changeCurrency}/>
          <span className="hdr__phone">
            <Icon name="whatsapp" size={14}/> +66 95 992 0345
          </span>
          <button className="btn btn--primary btn--sm" onClick={onEnquire}>
            Enquire <Icon name="arrow" size={14}/>
          </button>
        </div>
        <button className="hdr__burger" onClick={() => setOpen(!open)} aria-label="Menu">
          <span/><span/><span/>
        </button>
      </div>
      {open && (
        <div className="hdr__mobile">
          <a href="/rentals" onClick={() => setOpen(false)}>Rentals</a>
          <a href={hrefFor("#areas")} onClick={() => setOpen(false)}>Areas</a>
          <a href={hrefFor("#services")} onClick={() => setOpen(false)}>Services</a>
          <a href={hrefFor("#contact")} onClick={() => setOpen(false)}>Contact</a>
          <CurrencyMenu currency={currency} open={currencyOpen} setOpen={setCurrencyOpen} onChange={changeCurrency} mobile/>
          <button className="btn btn--primary" onClick={() => { setOpen(false); onEnquire(); }}>
            Enquire <Icon name="arrow" size={14}/>
          </button>
        </div>
      )}
    </header>
  );
}

function CurrencyMenu({ currency, open, setOpen, onChange, mobile }) {
  const selected = CURRENCY_OPTIONS[currency] || CURRENCY_OPTIONS.THB;
  return (
    <div className={`currency-menu ${mobile ? "currency-menu--mobile" : ""}`}>
      <button
        type="button"
        className="currency-menu__trigger"
        onClick={() => setOpen(!open)}
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <span>{currency}</span>
        <small>{selected.symbol}</small>
        <Icon name="arrowDown" size={14}/>
      </button>
      {open && (
        <div className="currency-menu__list" role="listbox" aria-label="Choose currency">
          {Object.entries(CURRENCY_OPTIONS).map(([key, item]) => (
            <button
              type="button"
              key={key}
              className={key === currency ? "is-active" : ""}
              onClick={() => onChange(key)}
              role="option"
              aria-selected={key === currency}
            >
              <span>{key}</span>
              <em>{item.symbol}</em>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ hero + search

function Hero({ filters, setFilters, onSearch }) {
  const setF = (k, v) => setFilters((f) => ({ ...f, [k]: v }));
  return (
    <section className="hero" data-screen-label="Hero">
      <div className="hero__media">
        <img src="https://images.unsplash.com/photo-1582719508461-905c673771fd?w=2200&auto=format&fit=crop" alt="" />
        <div className="hero__scrim"/>
      </div>
      <div className="hero__inner">
        <div className="hero__grid">
          <div className="hero__text">
            <div className="eyebrow eyebrow--light">
              <span className="eyebrow__dot"/> Est. 2014 - Pattaya, Thailand
            </div>
            <h1 className="display">
              Pattaya rentals,<br/>
              <em>curated for the way<br/>you live.</em>
            </h1>
            <p className="hero__lede">
              Beachfront condos, hillside pool villas, and family homes - let by a small team
              who actually live here. Monthly and long-term leases, no listing-site noise.
            </p>
            <div className="hero__credentials">
              <div className="cred">
                <span className="cred__stars" aria-label="4.9 stars">
                  {[1,2,3,4,5].map((i) => (
                    <svg key={i} width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 .6-5.3 4.6 1.6 7-6.3-3.8L5.7 21l1.6-7L2 9.6 9 9z"/></svg>
                  ))}
                </span>
                <span><strong>4.9</strong> - 184 Google reviews</span>
              </div>
              <div className="cred">
                <span className="cred__line"/>
                <span>DBD-licensed property agent</span>
              </div>
            </div>
          </div>

          <FeaturedHeroCard/>
        </div>

        <SearchPanel filters={filters} setFilters={setF} onSearch={onSearch}/>
      </div>

      <div className="hero__stats">
        <div><strong>240<span>+</span></strong><span>properties</span></div>
        <div><strong>5</strong><span>areas covered</span></div>
        <div><strong>11<span>yrs</span></strong><span>on the ground</span></div>
        <div><strong>24<span>hr</span></strong><span>shortlist turnaround</span></div>
        <div><strong>98<span>%</span></strong><span>tenant retention</span></div>
      </div>
    </section>
  );
}

const PROPERTY_TYPES = ["Any", "Condo", "Villa"];
const AREA_OPTIONS = ["Any area", "Wongamat", "Pratumnak", "Jomtien", "Central Pattaya", "East Pattaya"];
const BUDGET_OPTIONS = [
  { label: "Any budget", min: 0, max: Infinity },
  { label: `Under ${fmtTHBshort(40000)}`, min: 0, max: 40000 },
  { label: `${fmtTHBshort(40000)} - ${fmtTHBshort(80000)}`, min: 40000, max: 80000 },
  { label: `${fmtTHBshort(80000)} - ${fmtTHBshort(150000)}`, min: 80000, max: 150000 },
  { label: `${fmtTHBshort(150000)}+`, min: 150000, max: Infinity },
];
const BED_OPTIONS = ["Any", "1", "2", "3", "4+"];

function SearchPanel({ filters, setFilters, onSearch }) {
  return (
    <form className="search" onSubmit={(e) => { e.preventDefault(); onSearch(); }}>
      <div className="search__row">
        <SearchField label="Property type" value={filters.type} options={PROPERTY_TYPES} onChange={(v) => setFilters("type", v)}/>
        <SearchField label="Area" value={filters.area} options={AREA_OPTIONS} onChange={(v) => setFilters("area", v)}/>
        <SearchField label="Monthly budget" value={filters.budget} options={BUDGET_OPTIONS.map(b => b.label)} onChange={(v) => setFilters("budget", v)}/>
        <SearchField label="Bedrooms" value={filters.beds} options={BED_OPTIONS} onChange={(v) => setFilters("beds", v)}/>
        <button type="submit" className="btn btn--primary btn--lg search__submit">
          <Icon name="search" size={16}/>
          <span>Search rentals</span>
        </button>
      </div>
      <div className="search__chips">
        <span className="search__chiplabel">Popular:</span>
        <button type="button" className="chip" onClick={() => { setFilters("type","Villa"); setFilters("area","Pratumnak"); }}>
          Villas in Pratumnak
        </button>
        <button type="button" className="chip" onClick={() => { setFilters("type","Condo"); setFilters("area","Wongamat"); setFilters("budget", BUDGET_OPTIONS[3].label); }}>
          Beachfront condos, Wongamat
        </button>
        <button type="button" className="chip" onClick={() => { setFilters("type","Villa"); setFilters("area","East Pattaya"); setFilters("beds","3"); }}>
          Family villas, East Pattaya
        </button>
      </div>
    </form>
  );
}

function SearchField({ label, value, options, onChange }) {
  const selectedValue = options.includes(value) ? value : options[0];
  return (
    <label className="sf">
      <span className="sf__label">{label}</span>
      <div className="sf__control">
        <span className="sf__value">{selectedValue}</span>
        <Icon name="arrowDown" size={14}/>
      </div>
      <select className="sf__select" value={selectedValue} onChange={(e) => onChange(e.target.value)} aria-label={label}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

function TrustStrip() {
  const items = [
    { name: "Bangkok Post", kind: "press" },
    { name: "Sansiri Living", kind: "partner" },
    { name: "Coldwell Banker", kind: "partner" },
    { name: "DDProperty Verified", kind: "cert" },
    { name: "Hipflat Top 10", kind: "press" },
    { name: "Thai Tatler Homes", kind: "press" },
  ];
  return (
    <section className="trust" aria-label="Press and partners" data-screen-label="Trust strip">
      <div className="trust__inner">
        <div className="trust__label">
          <span className="trust__line"/>
          Featured in &amp; partnered with
          <span className="trust__line"/>
        </div>
        <ul className="trust__row">
          {items.map((it) => (
            <li key={it.name}>
              <span className="trust__name">{it.name}</span>
              {it.kind === "cert" && (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <circle cx="12" cy="12" r="9"/><path d="M8 12l3 3 5-6"/>
                </svg>
              )}
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, SearchPanel, Icon, fmtTHB, fmtTHBshort, getCurrency, setCurrency, CURRENCY_OPTIONS, PROPERTY_TYPES, AREA_OPTIONS, BUDGET_OPTIONS, BED_OPTIONS, TrustStrip });
