// app.jsx - product shell for the live preference-card approval surface.

function useViewportIsMobile() {
  const [mobile, setMobile] = React.useState(() => window.innerWidth <= 720);

  React.useEffect(() => {
    const media = window.matchMedia("(max-width: 720px)");
    const update = () => setMobile(media.matches);
    update();
    media.addEventListener?.("change", update);
    window.addEventListener("resize", update);
    return () => {
      media.removeEventListener?.("change", update);
      window.removeEventListener("resize", update);
    };
  }, []);

  return mobile;
}

function currentPrefcardView() {
  const params = new URLSearchParams(window.location.search);
  return params.get("view") === "layout" ? "layout" : "gudid";
}

function setPrefcardViewParam(view) {
  const url = new URL(window.location.href);
  if (view === "layout") url.searchParams.set("view", "layout");
  else url.searchParams.delete("view");
  window.history.pushState({ prefcardView: view }, "", url);
}

function PrefcardViewTabs({ activeView, onViewChange, mobile }) {
  const tabs = [
    { id: "gudid", label: "GUDID Match Review" },
    { id: "layout", label: "Room Layout" },
  ];
  return (
    <div style={{
      padding: mobile ? "0 16px 12px" : "0 32px 16px",
      borderBottom: "1px solid var(--ss-line)",
      background: "var(--ss-cream)",
    }}>
      <div role="tablist" aria-label="Preference card views" style={{
        display: "inline-flex",
        gap: 4,
        padding: 4,
        border: "1px solid var(--ss-line)",
        borderRadius: 6,
        background: "var(--ss-warm-white)",
        maxWidth: "100%",
        overflowX: "auto",
      }}>
        {tabs.map((tab) => {
          const active = activeView === tab.id;
          return (
            <button
              key={tab.id}
              role="tab"
              aria-selected={active}
              onClick={() => onViewChange(tab.id)}
              style={{
                border: "1px solid " + (active ? "var(--ss-ink)" : "transparent"),
                background: active ? "var(--ss-ink)" : "transparent",
                color: active ? "var(--ss-cream)" : "var(--ss-gray-900)",
                borderRadius: 4,
                padding: mobile ? "7px 9px" : "8px 12px",
                fontFamily: "var(--ss-sans)",
                fontSize: mobile ? 12.5 : 13,
                fontWeight: 600,
                whiteSpace: "nowrap",
                cursor: "pointer",
              }}
            >
              {tab.label}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function App() {
  const mobile = useViewportIsMobile();
  const [activeView, setActiveView] = React.useState(currentPrefcardView);

  React.useEffect(() => {
    const handlePop = () => setActiveView(currentPrefcardView());
    window.addEventListener("popstate", handlePop);
    return () => window.removeEventListener("popstate", handlePop);
  }, []);

  function changeView(view) {
    setActiveView(view);
    setPrefcardViewParam(view);
  }

  const viewTabs = (
    <PrefcardViewTabs
      activeView={activeView}
      onViewChange={changeView}
      mobile={mobile}
    />
  );

  if (activeView === "layout" && window.RoomLayoutView) {
    return <window.RoomLayoutView mobile={mobile} viewTabs={viewTabs} />;
  }

  return <window.GudidMatchApprovalView mobile={mobile} viewTabs={viewTabs} />;
}

// Defer render until window.PREFCARD is populated from /api/cards.
// Falls back gracefully if window.PREFCARD_READY is absent (synthetic-only mode).
(window.PREFCARD_READY || Promise.resolve()).then(() => {
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
});
