// Floating contact widget. Bottom-right circle that fans out WhatsApp + Email
// when clicked. Default message is auto-generated based on the current page.

const { useState: useSF, useMemo: useMF, useEffect: useEF } = React;

const CONTACT_WHATSAPP = "66959920345";              // digits only, no '+'
const CONTACT_EMAIL    = "contact@centralcityproperty.com";

function buildDefaultMessage() {
  const path = window.location.pathname || "";
  // Property detail page — include the listing title + ref.
  if (path.startsWith("/properties/") || path.endsWith("/property.html")) {
    try {
      const id = (function () {
        const m = path.match(/-(p\d+)$/i) || path.match(/^\/?p(\d+)$/i);
        if (m) return m[1];
        const q = new URLSearchParams(window.location.search);
        return q.get("id") || "";
      })();
      const property = (window.LISTINGS || []).find((p) => p.id === id);
      if (property) {
        return `Hi! I'm interested in ${property.title} (Ref ANT-${property.id.toUpperCase()}). I'd like to arrange a viewing.`;
      }
    } catch (_) {}
    return "Hi! I'd like to enquire about a property on your site.";
  }
  if (path.startsWith("/rentals")) {
    return "Hi! I'm browsing rentals on your site and would like to discuss options.";
  }
  return "Hi! I'd like to know more about your Pattaya rentals.";
}

function ContactIcon({ name }) {
  const props = { width: 22, height: 22, viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true" };
  if (name === "whatsapp") return (
    <svg width="24" height="24" viewBox="0 0 32 32" aria-hidden="true">
      <path fill="currentColor" d="M16.001 0C7.165 0 .002 7.163.002 16c0 2.824.738 5.583 2.142 8.013L0 32l8.184-2.137A15.93 15.93 0 0 0 16 32C24.836 32 32 24.837 32 16 32 7.163 24.837 0 16 0zm9.27 22.594c-.394 1.108-2.286 2.117-3.197 2.252-.816.122-1.85.173-2.984-.187-.687-.218-1.57-.51-2.7-.999-4.75-2.05-7.853-6.83-8.09-7.146-.236-.315-1.936-2.572-1.936-4.908 0-2.337 1.227-3.485 1.663-3.96.394-.43.86-.538 1.146-.538l.825.014c.265.012.62-.1.969.74.394.951 1.339 3.288 1.456 3.524.119.237.197.514.04.829-.158.315-.236.512-.473.788-.236.276-.494.617-.706.829-.236.236-.482.49-.207.96.276.473 1.226 2.024 2.633 3.279 1.81 1.613 3.336 2.114 3.81 2.35.473.237.748.197 1.024-.118.276-.316 1.18-1.38 1.495-1.853.314-.473.629-.394 1.062-.236.434.158 2.76 1.303 3.234 1.54.473.236.788.354.906.552.119.198.119 1.144-.275 2.252z"/>
    </svg>
  );
  if (name === "email") return (
    <svg {...props}><path d="M1.5 4A1.5 1.5 0 0 0 0 5.5v13A1.5 1.5 0 0 0 1.5 20h21a1.5 1.5 0 0 0 1.5-1.5v-13A1.5 1.5 0 0 0 22.5 4h-21zm.31 1.43h20.38l-10.19 7.65L1.81 5.43zM1.5 6.75l10.18 7.64a.6.6 0 0 0 .64 0L22.5 6.75v11.83H1.5V6.75z"/></svg>
  );
  if (name === "chat") return (
    <svg {...props}><path d="M12 2C6.48 2 2 6.04 2 11c0 2.5 1.13 4.78 2.97 6.42-.07 1.04-.34 2.4-1 3.58 0 0 2.84-.34 5.04-1.55C10.02 19.79 11 20 12 20c5.52 0 10-4.04 10-9s-4.48-9-10-9z"/></svg>
  );
  if (name === "close") return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
  );
  return null;
}

function ContactFab() {
  const [open, setOpen] = useSF(false);
  const message = useMF(buildDefaultMessage, [open]);

  useEF(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") { setOpen(false); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const enc = (s) => encodeURIComponent(s);
  const channels = [
    {
      name: "WhatsApp",
      icon: "whatsapp",
      color: "#25D366",
      href: `https://wa.me/${CONTACT_WHATSAPP}?text=${enc(message)}`,
      target: "_blank",
    },
    {
      name: "Email",
      icon: "email",
      color: "#0e3e3c",
      href: `mailto:${CONTACT_EMAIL}?subject=${enc("Pattaya rental enquiry")}&body=${enc(message)}`,
    },
  ];

  return (
    <div className={`cfab ${open ? "cfab--open" : ""}`} aria-live="polite">
      <ul className="cfab__list" role="menu" aria-label="Contact methods" aria-hidden={!open}>
        {channels.map((c, i) => (
          <li key={c.name} className="cfab__item" style={{ "--i": i }} role="none">
            <span className="cfab__label" aria-hidden="true">{c.name}</span>
            <a
              className="cfab__btn"
              role="menuitem"
              href={c.href || "#"}
              target={c.target}
              rel={c.target === "_blank" ? "noopener noreferrer" : undefined}
              onClick={(e) => {
                if (c.onClick) { e.preventDefault(); c.onClick(); }
                if (window.trackPropertyEvent) {
                  window.trackPropertyEvent("contact", "click");
                }
              }}
              style={{ background: c.color }}
              aria-label={`Contact via ${c.name}`}
              tabIndex={open ? 0 : -1}
            >
              <ContactIcon name={c.icon}/>
            </a>
          </li>
        ))}
      </ul>

      <button
        type="button"
        className="cfab__trigger"
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        aria-label={open ? "Close contact menu" : "Open contact menu"}
      >
        <span className="cfab__trigger-icon cfab__trigger-icon--chat"><ContactIcon name="chat"/></span>
        <span className="cfab__trigger-icon cfab__trigger-icon--close"><ContactIcon name="close"/></span>
      </button>
    </div>
  );
}

// Mount into its own root so it doesn't conflict with the existing #root React tree.
(function mountContactFab() {
  if (document.documentElement.dataset.page === "admin") return;
  let host = document.getElementById("cfab-root");
  if (!host) {
    host = document.createElement("div");
    host.id = "cfab-root";
    document.body.appendChild(host);
  }
  ReactDOM.createRoot(host).render(<ContactFab/>);
})();
