const { useMemo: useMemoDetail, useState: useStateDetail, useEffect: useEffectDetail } = React;

function absoluteAssetUrl(value) {
  if (!value) return "";
  try {
    return new URL(value, window.location.href).href;
  } catch (e) {
    return value;
  }
}

function setMetaTag(selector, attr, value) {
  if (!value) return;
  const node = document.querySelector(selector);
  if (node) node.setAttribute(attr, value);
}

function requestedListingSlug() {
  const params = new URLSearchParams(window.location.search);
  const fromQuery = params.get("listing") || params.get("id") || params.get("slug");
  if (fromQuery) return fromQuery;
  const parts = window.location.pathname.split("/").filter(Boolean);
  const listingIndex = parts.indexOf("listings");
  if (listingIndex >= 0 && parts[listingIndex + 1]) return decodeURIComponent(parts[listingIndex + 1]);
  return "";
}

function siteUrl(path) {
  return new URL(path.replace(/^\//, ""), `${window.location.origin}/`).href;
}

function canonicalListingUrl(listing) {
  const slug = listing.slug || listing.id || listing.n;
  if (String(listing.id || "").startsWith("default-")) return siteUrl(`listings/${slug}/`);
  const url = new URL("listing.html", `${window.location.origin}/`);
  url.searchParams.set("listing", slug);
  return url.href;
}

function DetailMetric({ label, value }) {
  return (
    <div className="detail-metric">
      <span>{label}</span>
      <strong>{value || "Ask Noey"}</strong>
    </div>
  );
}

function ListingDetailApp() {
  const requested = requestedListingSlug();
  const listing = useMemoDetail(() => {
    const found = window.HONListingStore.find(requested);
    return found || window.HONListingStore.all()[0];
  }, [requested]);
  const [currency, setCurrency] = useStateDetail("THB");
  const [activeImage, setActiveImage] = useStateDetail(listing?.heroImage || listing?.img || "");
  const contact = window.HON_CONTACT || {};

  useEffectDetail(() => {
    document.body.classList.add("listing-detail-page");
    return () => document.body.classList.remove("listing-detail-page");
  }, []);

  useEffectDetail(() => {
    if (!listing) return;
    const listingUrl = canonicalListingUrl(listing);
    const description = listing.desc || listing.story || "Bangkok property listing by House of Noey.";
    const image = absoluteAssetUrl((listing.gallery && listing.gallery[0]) || listing.heroImage || listing.img);
    document.title = `${listing.title} | House of Noey`;
    setMetaTag("meta[name='description']", "content", description);
    setMetaTag("meta[property='og:title']", "content", `${listing.title} | House of Noey`);
    setMetaTag("meta[property='og:description']", "content", description);
    setMetaTag("meta[property='og:image']", "content", image);
    setMetaTag("meta[property='og:url']", "content", listingUrl);
    setMetaTag("link[rel='canonical']", "href", listingUrl);
    const json = [
      {
        "@context": "https://schema.org",
        "@type": "Product",
        name: listing.title,
        description,
        image: (listing.gallery || [listing.img]).filter(Boolean).map(absoluteAssetUrl),
        brand: { "@type": "Brand", name: "House of Noey" },
        category: "Bangkok residential real estate",
        offers: {
          "@type": "Offer",
          priceCurrency: "THB",
          price: listing.price || undefined,
          availability: "https://schema.org/InStock",
          url: listingUrl,
          areaServed: listing.district || "Bangkok"
        },
        additionalProperty: [
          { "@type": "PropertyValue", name: "District", value: listing.district || "Bangkok" },
          { "@type": "PropertyValue", name: "Size", value: listing.sqm ? `${listing.sqm} sqm` : "" },
          { "@type": "PropertyValue", name: "Bedrooms", value: listing.beds || "" },
          { "@type": "PropertyValue", name: "Bathrooms", value: listing.baths || "" },
          { "@type": "PropertyValue", name: "Ownership", value: listing.ownership || listing.quota || "" }
        ].filter((prop) => prop.value)
      },
      {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "House of Noey", item: siteUrl("index.html") },
          { "@type": "ListItem", position: 2, name: "Listings", item: siteUrl("index.html#listings") },
          { "@type": "ListItem", position: 3, name: listing.title, item: listingUrl }
        ]
      }
    ];
    let node = document.getElementById("listing-jsonld");
    if (!node) {
      node = document.createElement("script");
      node.type = "application/ld+json";
      node.id = "listing-jsonld";
      document.head.appendChild(node);
    }
    node.textContent = JSON.stringify(json);
  }, [listing]);

  if (!listing) {
    return (
      <>
        <Header lang="en" setLang={() => {}} t={window.I18N.en} />
        <main className="detail-empty shell">
          <h1>Listing not found.</h1>
          <a className="btn" href="index.html#listings"><span>Back to listings</span><span>-></span></a>
        </main>
      </>
    );
  }

  const gallery = listing.gallery && listing.gallery.length ? listing.gallery : [listing.heroImage || listing.img].filter(Boolean);
  const message = encodeURIComponent(window.HON_makeContactText ? window.HON_makeContactText({ listingTitle: listing.title }) : `House of Noey enquiry: ${listing.title}`);

  return (
    <>
      <ScrollProgress />
      <Header lang="en" setLang={() => {}} t={window.I18N.en} onBook={() => document.getElementById("detail-contact")?.scrollIntoView({behavior:"smooth"})} />
      <main>
        <section className="detail-hero">
          <div className="shell detail-hero__grid">
            <div className="detail-hero__copy glass">
              <a className="detail-back" href="index.html#listings">Back to current listings</a>
              <div className="listing__num">{listing.tag}</div>
              <h1 className="detail-title">{listing.title}</h1>
              <p className="detail-lede">{listing.story || listing.desc}</p>
              <div className="detail-price">{fmtMoney(listing.price, currency)} <small>asking</small></div>
              <div className="currency detail-currency">
                {Object.keys(CURRENCIES).map((c) => (
                  <button key={c} data-active={currency === c} onClick={() => setCurrency(c)}>{c}</button>
                ))}
              </div>
            </div>
            <figure className="detail-hero__image">
              {activeImage ? <img src={activeImage} alt={listing.title} /> : <div className="placeholder">Listing image</div>}
              <figcaption>{listing.neighborhood || listing.district} · {listing.status}</figcaption>
            </figure>
          </div>
        </section>

        <section className="section section--surface">
          <div className="shell detail-layout">
            <div>
              <div className="detail-gallery">
                {gallery.map((img, i) => (
                  <button key={`${img}-${i}`} onClick={() => setActiveImage(img)} data-active={activeImage === img}>
                    <img src={img} alt={`${listing.title} image ${i + 1}`} />
                  </button>
                ))}
              </div>
              <article className="detail-copy">
                <div className="section__num">Noey's file note</div>
                <h2>{listing.district}, without the brochure voice.</h2>
                <p>{listing.desc}</p>
                <p>{listing.mapHint}</p>
              </article>
            </div>

            <aside className="detail-panel">
              <DetailMetric label="Price / sqm" value={listing.sqm ? fmtMoney(listing.price / listing.sqm, currency) : "Ask Noey"} />
              <DetailMetric label="Size" value={`${listing.sqm} sqm`} />
              <DetailMetric label="Bedrooms" value={listing.beds} />
              <DetailMetric label="Bathrooms" value={listing.baths} />
              <DetailMetric label="BTS" value={`${listing.bts} min`} />
              <DetailMetric label="Aspect" value={listing.aspect} />
              <DetailMetric label="Built" value={listing.year} />
              <DetailMetric label="Ownership" value={listing.ownership || listing.quota} />
              <DetailMetric label="Common fee" value={listing.fee} />
              <DetailMetric label="Parking" value={listing.parking} />
            </aside>
          </div>
        </section>

        <section className="section" id="detail-contact">
          <div className="shell detail-contact">
            <div>
              <div className="section__num">Private walk</div>
              <h2 className="section__title">Ask Noey, Natcha Wiriyaporn, for the real file.</h2>
              <p className="section__intro">Request the floor plan, juristic notes, quota position, and a thirty-minute walk with Natcha if the listing fits your brief.</p>
            </div>
            <div className="detail-contact__actions">
              <a className="btn" href={`${contact.lineUrl || "https://line.me/R/ti/p/@noeyrealestate"}?text=${message}`} target="_blank" rel="noopener"><span>Message on LINE</span><span>-></span></a>
              <a className="btn btn--ghost" href={`mailto:${contact.email || "noey@houseofnoey.com"}?subject=${encodeURIComponent(listing.title)}&body=${message}`}><span>Email the file</span><span>-></span></a>
            </div>
          </div>
        </section>
      </main>
      <Footer t={window.I18N.en} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ListingDetailApp />);
