/* The Foundry — Slim Public Vacancy List (no admin, no print, no hero) */
/* global React, ReactDOM, FOUNDRY_DATA, FOUNDRY_BACKEND */
const { useState, useMemo, useRef, useEffect } = React;

// ---------- Utilities ------------------------------------------------------
const fmtArea = (n) => n == null ? "—" : Number(n).toLocaleString("en-AU") + " m²";

// Hardstand tenancies are leased on their yard area, so the headline figure
// (hover chip) should be the hardstand m² — not the small internal slab.
const isHardstandTenancy = (t) => /^Hardstand/i.test(t.id);
const headlineArea = (t) =>
  isHardstandTenancy(t) ? (t.hardstand || t.internal) : (t.internal || t.hardstand);

// Merge live Supabase edits onto the seed tenancies.
// Public-safe fields only — area sizes (internal/hardstand) sync from the
// admin so the embed stays in step, but PRICING fields (net/outgoings/
// totals) are intentionally never surfaced on the public embed.
function mergeEdits(seedTenancies, editsById) {
  return seedTenancies.map((t) => {
    const e = editsById[t.id];
    if (!e) return t;
    return {
      ...t,
      status: e.status || t.status,
      description: e.description != null ? e.description : t.description,
      bullets: e.bullets && e.bullets.length ? e.bullets : t.bullets,
      note: e.note != null ? e.note : t.note,
      internal: e.internal != null ? e.internal : t.internal,
      hardstand: e.hardstand != null ? e.hardstand : t.hardstand
    };
  });
}

function tenancyOrder(id) {
  if (/^T\d/i.test(id)) {
    const m = id.match(/^T(\d+)([a-z]?)$/i);
    if (m) return [0, parseInt(m[1], 10), (m[2] || "").toLowerCase()];
  }
  if (/^WH/i.test(id)) {
    const n = parseInt(id.replace(/[^0-9]/g, ""), 10) || 0;
    return [1, n, ""];
  }
  if (/^Hardstand/i.test(id)) {
    const n = parseInt(id.replace(/[^0-9]/g, ""), 10) || 0;
    return [2, n, ""];
  }
  return [9, 0, id];
}
function byTenancyOrder(a, b) {
  const A = tenancyOrder(a.id), B = tenancyOrder(b.id);
  return A[0] - B[0] || A[1] - B[1] || A[2].localeCompare(B[2]);
}

function tenancyFontSize(t) {
  const area = (t.internal || 0) + (t.hardstand || 0);
  if (area > 1500) return 44;
  if (area > 500) return 36;
  if (area > 250) return 28;
  if (area > 150) return 22;
  return 18;
}

// ---------- Icons ----------------------------------------------------------
function Icon({ name }) {
  const paths = {
    "search": "M9 16a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM14 14l5 5",
    "x": "M5 5l10 10M15 5L5 15",
    "mail": "M3 5h14v10H3zM3 5l7 6 7-6",
    "compare": "M3 6h7M3 14h7M14 3v14M11 6l3-3 3 3M17 14l-3 3-3-3"
  };
  return (
    <svg viewBox="0 0 20 20" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d={paths[name] || ""} />
    </svg>
  );
}

// ---------- Header ---------------------------------------------------------
function Header() {
  return (
    <header className="topbar">
      <a href="#" className="brand" onClick={(e) => e.preventDefault()}>
        <img src="foundry-logo.svg" alt="The Foundry" className="brand-logo"/>
      </a>
      <nav className="crumbs">
        <span>Vacancy List</span>
        <span className="sep">/</span>
        <span className="now">63 Currumbin Creek Rd</span>
      </nav>
    </header>
  );
}

// ---------- Site Map -------------------------------------------------------
function SiteMap({ tenancies, selectedId, hoverId, setHoverId, onSelect, accent, density, multiSelect }) {
  const { ANCILLARY, LABELS, VIEW, SURVEY } = FOUNDRY_DATA;
  const showLabels = density !== "minimal";
  const showAncillary = density !== "minimal";

  const labelInkColor = "#1a1612";
  const leasedTextColor = "#1a1612";
  const leasedStroke = "#b13838";

  return (
    <svg
      className="map"
      viewBox={`0 0 ${VIEW.w} ${VIEW.h}`}
      preserveAspectRatio="xMidYMid meet"
      role="img"
      aria-label="Site map of 63 Currumbin Creek Road">
      <defs>
        <pattern id="leased-hatch" patternUnits="userSpaceOnUse" width="14" height="14" patternTransform="rotate(45)">
          <rect width="14" height="14" fill="#f3dada" />
          <line x1="0" y1="0" x2="0" y2="14" stroke={leasedStroke} strokeWidth="3" />
        </pattern>
      </defs>

      <image
        className="survey-bg"
        href={SURVEY.src}
        x="0" y="0"
        width={VIEW.w} height={VIEW.h}
        preserveAspectRatio="xMidYMid meet"
      />

      {LABELS.map((l, i) => {
        const transform = l.rotate ? `rotate(${l.rotate} ${l.x} ${l.y})` : undefined;
        return (
          <g key={i}>
            <text
              x={l.x}
              y={l.y}
              transform={transform}
              className={l.road ? "road-label" : "zone-label"}
              fontSize={l.font || 18}
              textAnchor="middle">
              {l.text}
            </text>
            {l.sub && !l.road &&
              <text
                x={l.x}
                y={l.y + (l.font || 18) * 1.2}
                className="zone-sub"
                fontSize={(l.font || 18) * 0.65}
                textAnchor="middle">
                {l.sub}
              </text>
            }
          </g>
        );
      })}

      {showAncillary && ANCILLARY.map((a) => (
        <g key={a.id} className="ancillary" pointerEvents="none">
          <path d={a.d} fill="#5a5240" stroke="#8e7048" strokeWidth="1" opacity="0.7" />
          {density === "detailed" && (
            <text x={a.cx} y={a.cy} className="ancillary-label" textAnchor="middle" dominantBaseline="middle" fontSize="12" fill="#f3ece0">{a.id}</text>
          )}
        </g>
      ))}

      {tenancies.map((t) => {
        const inCompare = multiSelect && multiSelect.includes(t.id);
        const isActive = selectedId === t.id;
        const isSel = isActive || inCompare;
        const isHover = hoverId === t.id;
        const leased = t.status === "leased";

        const fillOpacity = isActive || isHover ? 0.85 : (inCompare ? 0.18 : 0);
        const dashStroke = inCompare && !isActive && !isHover;
        const baseFill = leased
          ? "url(#leased-hatch)"
          : (isActive || isHover || inCompare ? accent : "transparent");
        const baseStroke = isActive
          ? accent
          : (leased ? leasedStroke : (isHover || inCompare ? accent : "transparent"));
        const sw = isActive ? 4 : (inCompare ? 2 : 1.5);

        return (
          <g
            key={t.id}
            className={`tenancy ${leased ? "is-leased" : "is-available"} ${isSel ? "is-selected" : ""} ${isHover ? "is-hover" : ""}`}
            onClick={() => onSelect(t.id)}
            onMouseEnter={() => setHoverId(t.id)}
            onMouseLeave={() => setHoverId(null)}>

            {t.extras && t.extras.filter((e) => e.kind === "yard").map((e, i) => (
              <path key={"y" + i}
                d={e.d}
                fill={leased ? "url(#leased-hatch)" : (isActive || isHover ? accent : "transparent")}
                stroke={baseStroke}
                strokeWidth={sw}
                strokeDasharray={dashStroke ? "8 4" : (isHover || isActive ? "6 4" : "0")}
                fillOpacity={leased ? 1 : fillOpacity}
                opacity={isActive || isHover ? 0.5 : 1} />
            ))}

            <path
              d={t.d}
              fill={baseFill}
              stroke={baseStroke}
              strokeWidth={sw}
              strokeDasharray={dashStroke ? "8 4" : "0"}
              fillOpacity={leased ? 1 : fillOpacity}
              opacity={leased ? 0.95 : 1} />

            {t.extras && t.extras.filter((e) => e.kind !== "yard").map((e, i) => (
              <path key={"o" + i}
                d={e.d}
                fill={baseFill}
                stroke={baseStroke}
                strokeWidth={sw}
                strokeDasharray={dashStroke ? "8 4" : "0"}
                fillOpacity={leased ? 1 : fillOpacity}
                opacity={leased ? 0.95 : 1} />
            ))}

            {/* Yard labels — e.g. "WH2 Hardstand" so the yard reads as
                belonging to its tenancy directly on the map. */}
            {showLabels && t.extras && t.extras.filter((e) => e.kind === "yard" && e.label && e.lx != null).map((e, i) => (
              <text key={"yl" + i}
                x={e.lx}
                y={e.ly}
                className="yard-label"
                textAnchor="middle"
                dominantBaseline="middle"
                fontSize="30"
                pointerEvents="none"
                fill={leased ? leasedTextColor : labelInkColor}>
                {e.label}
              </text>
            ))}

            {showLabels && (
              <g pointerEvents="none">
                <text
                  x={t.cx}
                  y={t.cy}
                  className="tenancy-id"
                  textAnchor="middle"
                  dominantBaseline="middle"
                  fontSize={tenancyFontSize(t)}
                  fill={leased ? leasedTextColor : labelInkColor}>
                  {t.id.replace("Hardstand ", "H")}
                </text>
              </g>
            )}
          </g>
        );
      })}

      <text x="40" y={VIEW.h - 30} className="yards-disclaimer" fontSize="13" fill="#7d745f">
        Yards (shaded on hover) are shared common areas; boundaries indicative only.
      </text>
    </svg>
  );
}

// ---------- Filters --------------------------------------------------------
// Slider top end follows the largest unit so no tenancy is hidden by default.
// A null max in filters means "no upper limit".
const areaOf = (t) => t.internal != null ? t.internal : (t.hardstand || 0);
function sliderCap(values, floor, step) {
  const m = Math.max(0, ...values.filter((v) => v != null));
  return Math.max(floor, Math.ceil(m / step) * step);
}

function Filters({ filters, setFilters, count, total, areaCap }) {
  return (
    <div className="filters">
      <div className="filter-row">
        <div className="seg">
          <button className={filters.status === "all" ? "on" : ""} onClick={() => setFilters({ ...filters, status: "all" })}>All <span className="seg-n">{total}</span></button>
          <button className={filters.status === "available" ? "on" : ""} onClick={() => setFilters({ ...filters, status: "available" })}>Available</button>
          <button className={filters.status === "leased" ? "on" : ""} onClick={() => setFilters({ ...filters, status: "leased" })}>Leased</button>
        </div>
        <div className="count">{count} shown</div>
      </div>

      <div className="filter-row">
        <RangeRow
          label="Floor area"
          unit="m²"
          min={0} max={areaCap} step={50}
          lo={filters.minArea} hi={filters.maxArea ?? areaCap}
          onChange={(lo, hi) => setFilters({ ...filters, minArea: lo, maxArea: hi >= areaCap ? null : hi })} />
      </div>
    </div>
  );
}

function RangeRow({ label, unit, min, max, step, lo, hi, onChange }) {
  const display = (v) => v.toLocaleString("en-AU") + (unit ? " " + unit : "");
  const loPct = ((lo - min) / (max - min)) * 100;
  const hiPct = ((hi - min) / (max - min)) * 100;
  return (
    <div className="range">
      <div className="range-head">
        <span>{label}</span>
        <span className="mono">{display(lo)} — {display(hi)}</span>
      </div>
      <div className="dual-range">
        <div className="dr-track">
          <div className="dr-fill" style={{ left: loPct + "%", right: (100 - hiPct) + "%" }} />
        </div>
        <input
          type="range" min={min} max={max} step={step} value={lo}
          className="dr-input dr-input-lo"
          onChange={(e) => onChange(Math.min(Number(e.target.value), hi - step), hi)}
        />
        <input
          type="range" min={min} max={max} step={step} value={hi}
          className="dr-input dr-input-hi"
          onChange={(e) => onChange(lo, Math.max(Number(e.target.value), lo + step))}
        />
      </div>
    </div>
  );
}

// ---------- 360 Panorama Tour (read-only) ---------------------------------
let __pnlmPromise = null;
function ensurePannellum() {
  if (window.pannellum) return Promise.resolve();
  if (__pnlmPromise) return __pnlmPromise;
  __pnlmPromise = new Promise((resolve, reject) => {
    const css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = "https://cdn.jsdelivr.net/npm/pannellum@2.5.6/build/pannellum.css";
    document.head.appendChild(css);
    const s = document.createElement("script");
    s.src = "https://cdn.jsdelivr.net/npm/pannellum@2.5.6/build/pannellum.js";
    s.onload = () => resolve();
    s.onerror = () => reject(new Error("Failed to load the 360 viewer"));
    document.head.appendChild(s);
  });
  return __pnlmPromise;
}

function PanoTour({ tenancyId, pano }) {
  return null; // 360 tour feature disabled (per Angus, 2026-07)
  // eslint-disable-next-line no-unreachable
  const [open, setOpen] = useState(false);
  const [viewerErr, setViewerErr] = useState(null);
  const viewerRef = useRef(null);
  const instanceRef = useRef(null);

  useEffect(() => {
    if (!open || !pano) return;
    let cancelled = false;
    setViewerErr(null);
    ensurePannellum().then(() => {
      if (cancelled || !viewerRef.current) return;
      instanceRef.current = window.pannellum.viewer(viewerRef.current, {
        type: "equirectangular",
        panorama: pano,
        autoLoad: true,
        autoRotate: -2,
        showZoomCtrl: true,
        showFullscreenCtrl: true,
        compass: false,
        hfov: 100,
        friction: 0.15
      });
    }).catch((e) => { if (!cancelled) setViewerErr(e.message || "Could not load 360 viewer"); });
    return () => {
      cancelled = true;
      if (instanceRef.current) { try { instanceRef.current.destroy(); } catch (e) {} instanceRef.current = null; }
    };
  }, [open, pano]);

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

  if (!pano) return null;

  return (
    <div className="pano-tour">
      <div className="pt-head">
        <span className="pt-title">360° Virtual Tour</span>
      </div>
      <button className="pt-btn" onClick={() => setOpen(true)}>
        <span className="pt-launch-ico">▸</span> Launch 360 tour
      </button>
      {open && (
        <div className="pt-modal" onClick={() => setOpen(false)}>
          <button className="pg-lightbox-close" onClick={(e) => { e.stopPropagation(); setOpen(false); }}><Icon name="x" /></button>
          <div className="pt-viewer-wrap" onClick={(e) => e.stopPropagation()}>
            <div ref={viewerRef} className="pt-viewer" />
            {viewerErr && <div className="pt-err">{viewerErr}</div>}
          </div>
          <div className="pt-hint mono">{tenancyId} · Drag to look around · scroll to zoom</div>
        </div>
      )}
    </div>
  );
}

// ---------- Photo Gallery (read-only) -------------------------------------
function PhotoGallery({ tenancyId, photos }) {
  const [lightbox, setLightbox] = useState(null);
  const list = photos || [];

  useEffect(() => {
    if (lightbox == null) return;
    function onKey(e) {
      if (e.key === "Escape") setLightbox(null);
      else if (e.key === "ArrowRight") setLightbox((i) => (i + 1) % list.length);
      else if (e.key === "ArrowLeft") setLightbox((i) => (i - 1 + list.length) % list.length);
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [lightbox, list.length]);

  if (list.length === 0) return null;

  return (
    <div className="photo-gallery">
      <div className="pg-head">
        <span className="pg-title">Photos {list.length > 1 && <span className="pg-count">{list.length}</span>}</span>
      </div>
      <div className={`pg-grid pg-grid-${Math.min(list.length, 4)}`}>
        {list.map((src, i) => (
          <div key={i} className="pg-cell" onClick={() => setLightbox(i)}>
            <img src={src} alt={`${tenancyId} photo ${i + 1}`} />
          </div>
        ))}
      </div>
      {lightbox != null && list[lightbox] && (
        <div className="pg-lightbox" onClick={() => setLightbox(null)}>
          <button className="pg-lightbox-close" onClick={(e) => { e.stopPropagation(); setLightbox(null); }}><Icon name="x"/></button>
          {list.length > 1 && (
            <button className="pg-nav prev" onClick={(e) => { e.stopPropagation(); setLightbox((i) => (i - 1 + list.length) % list.length); }} title="Previous (←)">‹</button>
          )}
          <div className="pg-lightbox-stage" onClick={(e) => e.stopPropagation()}>
            <img src={list[lightbox]} alt={`${tenancyId} photo ${lightbox + 1}`} />
          </div>
          {list.length > 1 && (
            <button className="pg-nav next" onClick={(e) => { e.stopPropagation(); setLightbox((i) => (i + 1) % list.length); }} title="Next (→)">›</button>
          )}
          {list.length > 1 && (
            <div className="pg-counter" onClick={(e) => e.stopPropagation()}>
              <span>{lightbox + 1} / {list.length}</span>
              <span className="pg-dots">
                {list.map((_, i) => (
                  <button key={i} className={`pg-dot ${i === lightbox ? "active" : ""}`} onClick={() => setLightbox(i)} title={`Photo ${i + 1}`} />
                ))}
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ---------- Tenancy Description (read-only) -------------------------------
function TenancyDescription({ tenancy: t }) {
  const bullets = Array.isArray(t.bullets) ? t.bullets : [];
  const hasContent = t.description || bullets.length > 0;
  if (!hasContent) return null;

  return (
    <div className="tenancy-desc">
      <div className="td-head">
        <span className="td-title">About this {t.id.startsWith("WH") ? "warehouse" : t.id.startsWith("Hardstand") ? "hardstand" : "tenancy"}</span>
      </div>
      {t.description && <p className="td-body">{t.description}</p>}
      {bullets.length > 0 && (
        <ul className="td-bullets">
          {bullets.map((b, i) => <li key={i}><span>{b}</span></li>)}
        </ul>
      )}
    </div>
  );
}

// ---------- Compare Drawer (slides up from the bottom) --------------------
function CompareDrawer({ tenancies, ids, removeCompare, clear, onOpen, onClose, open }) {
  const items = ids.map((id) => tenancies.find((t) => t.id === id)).filter(Boolean);

  // Lock body scroll while the drawer is open (mobile)
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  // Escape to dismiss
  useEffect(() => {
    if (!open) return;
    function onKey(e) { if (e.key === "Escape") onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <>
      <div className="compare-overlay" onClick={onClose} />
      <div className="compare-drawer" role="dialog" aria-label="Compare tenancies">
        <div className="compare-drawer-head">
          <div>
            <div className="panel-title">Comparing {items.length} {items.length === 1 ? "tenancy" : "tenancies"}</div>
            <div className="panel-sub">Side-by-side overview · tap a card to view full details.</div>
          </div>
          <div className="cd-actions">
            {items.length > 0 && (
              <button className="ghost-sm" onClick={clear}>Clear all</button>
            )}
            <button className="iconbtn" onClick={onClose} title="Close compare"><Icon name="x" /></button>
          </div>
        </div>
        <div className="compare-drawer-body">
          {items.length === 0 ? (
            <div className="list-empty">
              Nothing in compare yet. Open a tenancy and tap <strong>Compare</strong> to add it.
            </div>
          ) : (
            <div className="compare-grid">
              {items.map((t) => {
                const bullets = Array.isArray(t.bullets) ? t.bullets : [];
                return (
                  <div key={t.id} className="cmp-card">
                    <div className="cmp-head">
                      <div className="cmp-id">{t.id}</div>
                      <div className={`cmp-status ${t.status}`}>{t.status}</div>
                      <button className="cmp-close" onClick={() => removeCompare(t.id)} title="Remove">×</button>
                    </div>

                    <div className="cmp-section-label">Sizing</div>
                    <div className="cmp-sizing">
                      <div className="cmp-size-row">
                        <span>Internal</span>
                        <span className="mono">{fmtArea(t.internal)}</span>
                      </div>
                      <div className="cmp-size-row">
                        <span>Hardstand</span>
                        <span className="mono">{t.hardstand ? fmtArea(t.hardstand) : "—"}</span>
                      </div>
                      <div className="cmp-size-row">
                        <span>Total</span>
                        <span className="mono">{fmtArea((t.internal || 0) + (t.hardstand || 0))}</span>
                      </div>
                    </div>

                    <div className="cmp-section-label">Description</div>
                    {t.description
                      ? <p className="cmp-desc">{t.description}</p>
                      : <p className="cmp-empty">No description.</p>}

                    <div className="cmp-section-label">Features &amp; parking</div>
                    {bullets.length > 0 ? (
                      <ul className="cmp-bullets">
                        {bullets.map((b, i) => <li key={i}><span>{b}</span></li>)}
                      </ul>
                    ) : (
                      <p className="cmp-empty">No features listed.</p>
                    )}

                    <button className="ghost-sm" style={{ alignSelf: "flex-start", marginTop: "auto" }} onClick={() => onOpen(t.id)}>View details</button>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

// ---------- Details Panel --------------------------------------------------
function DetailsPanel({ tenancy: t, onClose, photos, pano, onCompare, canCompare, inCompare }) {
  const enquireBody = encodeURIComponent(
    `Hi,\n\nI'm interested in tenancy ${t.id} at 63 Currumbin Creek Road, Currumbin Waters.\n\n` +
    `Internal floor area: ${fmtArea(t.internal)}\n` +
    (t.hardstand ? `Hardstand: ${t.hardstand} m²\n` : "") +
    `\nPlease send me the latest pricing and availability.\n\nRegards,`
  );
  const mailto = `mailto:joe@pcrew.com.au?subject=${encodeURIComponent("Enquiry — " + t.id + " — 63 Currumbin Creek Rd")}&body=${enquireBody}`;

  // Prefer handing the enquiry to the host page's contact form (single inbox).
  // Falls back to mailto when the embed is opened standalone (not in an iframe).
  const inFrame = typeof window !== "undefined" && window.parent !== window;

  function sendToHostForm(e, kind) {
    if (!inFrame) return; // let the mailto href do its thing
    e.preventDefault();
    const subject = kind === "register"
      ? `Register interest ${t.id}`
      : `Enquiry ${t.id}`;
    const message = kind === "register"
      ? `Hi,\n\nPlease notify me when tenancy ${t.id} at 63 Currumbin Creek Road, Currumbin Waters becomes available.\n\nRegards,`
      : `Hi,\n\nI'm interested in tenancy ${t.id} at 63 Currumbin Creek Road, Currumbin Waters.\n\n` +
        `Internal floor area: ${fmtArea(t.internal)}\n` +
        (t.hardstand ? `Hardstand: ${fmtArea(t.hardstand)}\n` : "") +
        `\nPlease send me the latest pricing and availability.\n\nRegards,`;
    window.parent.postMessage({
      type: "foundry-enquire",
      tenancy: t.id,
      subject: subject,
      message: message
    }, "*");
  }

  return (
    <div className="panel details">
      <div className="details-head">
        <button className="back" onClick={onClose}>← Back</button>
        <button className="iconbtn" onClick={onClose} title="Close"><Icon name="x" /></button>
      </div>

      <div className="details-id">
        <div className="details-id-mark">{t.id}</div>
        <div className={`status-pill ${t.status}`}>
          <span className="dot" /> {t.status === "leased" ? "Leased" : "Available now"}
        </div>
        {t.note && <div className="details-note">{t.note}</div>}
      </div>

      <div className="details-areas">
        <div className="area-card">
          <div className="card-label">Internal floor area</div>
          <div className="card-value mono">{fmtArea(t.internal)}</div>
        </div>
        {t.hardstand && (
          <div className="area-card">
            <div className="card-label">Hardstand</div>
            <div className="card-value mono">{fmtArea(t.hardstand)}</div>
          </div>
        )}
      </div>

      <PanoTour tenancyId={t.id} pano={pano} />

      <PhotoGallery tenancyId={t.id} photos={photos} />

      <TenancyDescription tenancy={t} />

      {t.status === "available" ? (
        <div className="cta-row">
          <a className="btn primary" href={mailto} onClick={(e) => sendToHostForm(e, "enquire")}><Icon name="mail" /> Enquire about {t.id}</a>
          <button className="btn ghost" onClick={onCompare} disabled={!canCompare} title={inCompare ? "Already in compare" : (canCompare ? "Add to compare" : "Compare full (3/3)")}>
            <Icon name="compare" /> {inCompare ? "In compare" : "Compare"}
          </button>
        </div>
      ) : (
        <div className="leased-state">
          <div className="leased-big">LEASED</div>
          <div className="leased-sub">This {t.id.startsWith("WH") ? "warehouse" : t.id.startsWith("Hardstand") ? "hardstand" : "unit"} is currently let. Register your interest to be notified when the lease expires.</div>
          <a className="btn ghost" href={`mailto:joe@pcrew.com.au?subject=${encodeURIComponent("Register interest — " + t.id)}`} onClick={(e) => sendToHostForm(e, "register")}><Icon name="mail" /> Register interest</a>
        </div>
      )}
    </div>
  );
}

// ---------- Command Panel --------------------------------------------------
function CommandPanel({ tenancies, selected, setSelected, query, setQuery, filters, setFilters, photos, panos, compareList, addCompare, removeCompare, openCompare }) {
  const filtered = useMemo(() => {
    return tenancies.slice().sort(byTenancyOrder).filter((t) => {
      if (filters.status !== "all" && t.status !== filters.status) return false;
      if (query) {
        const q = query.toLowerCase();
        if (!t.id.toLowerCase().includes(q)) return false;
      }
      const area = areaOf(t);
      if (area < filters.minArea || (filters.maxArea != null && area > filters.maxArea)) return false;
      return true;
    });
  }, [tenancies, query, filters]);
  const areaCap = useMemo(() => sliderCap(tenancies.map(areaOf), 2500, 50), [tenancies]);

  if (selected) {
    const inCompare = compareList.includes(selected.id);
    return (
      <DetailsPanel
        tenancy={selected}
        onClose={() => setSelected(null)}
        photos={photos[selected.id] || []}
        pano={panos[selected.id] || null}
        onCompare={() => {
          if (inCompare) removeCompare(selected.id);
          else addCompare(selected.id);
        }}
        canCompare={inCompare || compareList.length < 3}
        inCompare={inCompare} />
    );
  }

  return (
    <div className="panel">
      <div className="panel-head panel-head-row">
        <div>
          <div className="panel-title">Vacancy directory</div>
          <div className="panel-sub">Click a unit on the map, or pick below.</div>
        </div>
        {compareList.length > 0 && (
          <button
            className="compare-chip"
            onClick={openCompare}
            title="View comparison">
            <Icon name="compare" />
            <span>Compare</span>
            <span className="compare-chip-count">{compareList.length}</span>
          </button>
        )}
      </div>

      <div className="search-row">
        <div className="search-wrap">
          <Icon name="search" />
          <input
            type="search"
            placeholder="Search T1, WH2, Hardstand…"
            value={query}
            onChange={(e) => setQuery(e.target.value)} />
        </div>
      </div>

      <Filters filters={filters} setFilters={setFilters} count={filtered.length} total={tenancies.length} areaCap={areaCap} />

      <div className="list-wrap">
        <div className="list-head">
          <div>Unit</div>
          <div>Area</div>
          <div className="right">Status</div>
        </div>
        <div className="list">
          {filtered.length === 0 && <div className="list-empty">No matches — adjust filters.</div>}
          {filtered.map((t) => {
            const inCompare = compareList.includes(t.id);
            return (
              <div key={t.id} className={`list-row ${t.status}`} onClick={() => setSelected(t.id)}>
                <div className="row-id">
                  <span className={`dot ${t.status}`} />
                  {t.id}
                </div>
                <div className="row-area mono">
                  {fmtArea(t.internal)}
                  {t.hardstand && <span className="hs"> + {t.hardstand}m² HS</span>}
                </div>
                <div className="row-right">
                  <span className="mono">
                    {t.status === "leased"
                      ? <span className="leased-tag">LEASED</span>
                      : <span className="avail-tag">Available</span>}
                  </span>
                  <button
                    className={`compare-pill ${inCompare ? "in" : ""}`}
                    onClick={(e) => { e.stopPropagation(); inCompare ? removeCompare(t.id) : addCompare(t.id); }}
                    disabled={!inCompare && compareList.length >= 3}
                    title={inCompare ? "Remove from compare" : "Add to compare"}>
                    {inCompare ? "✓" : "+"}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- App ------------------------------------------------------------
function App() {
  // Start with seed data (renders instantly), then hydrate from Supabase.
  const [tenancies, setTenancies] = useState(FOUNDRY_DATA.TENANCIES);
  const [photos, setPhotos] = useState({});
  const [panos, setPanos] = useState({});
  const accent = "#b89055";
  const density = "labels";

  // Pull live edits from Supabase on mount, and subscribe to changes.
  useEffect(() => {
    let cancelled = false;
    const backend = window.FOUNDRY_BACKEND;
    if (!backend) return; // SDK failed to load — fall back to seed-only view

    async function refresh() {
      const edits = await backend.loadEdits();
      if (cancelled) return;
      setTenancies(mergeEdits(FOUNDRY_DATA.TENANCIES, edits));
      const ph = {};
      const pn = {};
      for (const [id, e] of Object.entries(edits)) {
        if (e.photos && e.photos.length) ph[id] = e.photos;
        if (e.pano) pn[id] = e.pano;
      }
      setPhotos(ph);
      setPanos(pn);
    }
    refresh();

    // Realtime: re-pull on any change so the iframe stays fresh without reload
    const unsubscribe = backend.subscribeEdits(() => refresh());
    return () => { cancelled = true; unsubscribe && unsubscribe(); };
  }, []);

  const [hoverId, setHoverId] = useState(null);
  const [selectedId, setSelectedId] = useState(null);
  const [query, setQuery] = useState("");
  const [filters, setFilters] = useState({
    status: "all",
    minArea: 0, maxArea: null
  });
  const [compareList, setCompareList] = useState([]);
  const [compareView, setCompareView] = useState(false);

  function addCompare(id) {
    // On mobile, cap at 2 (2-up grid fits cleanly); desktop allows 3
    const cap = (typeof window !== "undefined" && window.matchMedia("(max-width: 900px)").matches) ? 2 : 3;
    setCompareList((cl) => cl.includes(id) ? cl : cl.length >= cap ? cl : [...cl, id]);
  }
  function removeCompare(id) { setCompareList((cl) => cl.filter((x) => x !== id)); }
  function clearCompare() { setCompareList([]); }

  const selected = selectedId ? tenancies.find((t) => t.id === selectedId) : null;

  return (
    <div className="app">
      <main className="main">
        <section className={`workspace ${compareView ? "compare-open" : ""}`}>
          <div className="map-wrap">
            <div className="map-toolbar">
              <div className="legend">
                <span className="lg-item"><span className="sw available"></span>Available</span>
                <span className="lg-item"><span className="sw leased"></span>Leased</span>
              </div>
              {hoverId && (
                <HoverChip tenancy={tenancies.find((t) => t.id === hoverId)} />
              )}
            </div>
            <SiteMap
              tenancies={tenancies}
              selectedId={selectedId}
              hoverId={hoverId}
              setHoverId={setHoverId}
              onSelect={(id) => setSelectedId(id)}
              accent={accent}
              density={density}
              multiSelect={compareList} />
          </div>
          <CommandPanel
            tenancies={tenancies}
            selected={selected}
            setSelected={setSelectedId}
            query={query}
            setQuery={setQuery}
            filters={filters}
            setFilters={setFilters}
            photos={photos}
            panos={panos}
            compareList={compareList}
            addCompare={addCompare}
            removeCompare={removeCompare}
            openCompare={() => setCompareView(true)} />
        </section>
      </main>

      <CompareDrawer
        tenancies={tenancies}
        ids={compareList}
        removeCompare={removeCompare}
        clear={() => { clearCompare(); setCompareView(false); }}
        onOpen={(id) => { setSelectedId(id); setCompareView(false); }}
        onClose={() => setCompareView(false)}
        open={compareView} />
    </div>
  );
}

function HoverChip({ tenancy: t }) {
  if (!t) return null;
  return (
    <div className="hover-chip">
      <div className="hc-id">{t.id}</div>
      <div className="hc-area mono">{fmtArea(headlineArea(t))}</div>
      <div className="hc-price mono">
        {t.status === "leased" ? "LEASED" : "AVAILABLE"}
      </div>
    </div>
  );
}

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