/* eslint-disable */
// Mobile overflow sheet — phone-only "More" button + full-screen overlay.
//
// Companion to bottom-tab-bar.jsx. The bottom tab bar exposes 4 primary
// destinations (Praxia / Chairside / Lead / Roles); this sheet exposes
// everything else in SUITE_PRODUCTS that isn't in the tab bar (My Practice,
// Patterns, Difficult, Friday, Handoffs).
//
// Self-mounting IIFE matching the bottom-tab-bar.jsx pattern. Creates its
// own container under documentElement (immune to React mount wipes) and
// renders both the floating MoreButton (visible only at <640px via CSS)
// and the overlay component into it.
//
// Visibility is controlled entirely by CSS in styles/tokens.css. JS does
// not gate on viewport width, so it works regardless of resize timing.

(function () {
  const { useEffect, useState } = React;

  // The 4 destinations that ARE in the bottom tab bar; everything else in
  // SUITE_PRODUCTS shows up in the More overlay.
  const TAB_BAR_IDS = new Set(["praxia", "course", "lead", "roles"]);

  // ─── Icons ─────────────────────────────────────────────────────────────
  function MoreIcon({ color, size }) {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M4 7h16M4 12h16M4 17h16" stroke={color} strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    );
  }

  // ─── Overflow item flatten ─────────────────────────────────────────────
  function getOverflowItems() {
    const products = window.SUITE_PRODUCTS;
    if (!Array.isArray(products)) return [];
    const out = [];
    for (const group of products) {
      const items = Array.isArray(group?.items) ? group.items : (Array.isArray(group) ? group : null);
      if (!items) continue;
      for (const p of items) {
        if (!p || typeof p.id !== "string") continue;
        if (TAB_BAR_IDS.has(p.id)) continue;
        out.push(p);
      }
    }
    return out;
  }

  // ─── Component (renders both button and overlay) ───────────────────────
  function MoreSheet() {
    const [open, setOpen] = useState(false);

    // Expose a global toggle so other code (e.g. integration tests) can drive it.
    useEffect(() => {
      window.toggleMoreSheet = () => setOpen((prev) => !prev);
      return () => { delete window.toggleMoreSheet; };
    }, []);

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

    const items = open ? getOverflowItems() : [];

    return (
      <>
        {/* Floating MoreButton — visible only at <640px via .more-button-floating CSS */}
        <button
          type="button"
          onClick={() => setOpen(true)}
          aria-label="More navigation"
          aria-haspopup="dialog"
          aria-expanded={open}
          className="more-button-floating"
          style={{
            position:       "fixed",
            top:            "max(var(--space-3, 12px), env(safe-area-inset-top))",
            right:          "var(--space-3, 12px)",
            zIndex:         "var(--z-sticky, 100)",
            background:     "color-mix(in srgb, var(--color-bg, #0E0D0B) 82%, transparent)",
            backdropFilter: "blur(10px) saturate(140%)",
            WebkitBackdropFilter: "blur(10px) saturate(140%)",
            border:         "1px solid var(--color-hairline, rgba(201,166,90,0.3))",
            borderRadius:   "var(--touch-target-min, 44px)",
            padding:        0,
            minWidth:       "var(--touch-target-min, 44px)",
            minHeight:      "var(--touch-target-min, 44px)",
            color:          "var(--color-text-primary, #E8DCC0)",
            cursor:         "pointer",
            alignItems:     "center",
            justifyContent: "center",
          }}
        >
          <MoreIcon color="currentColor" size={22} />
        </button>

        {/* Full-screen overlay — only mounted while open */}
        {open && (
          <div
            role="dialog"
            aria-modal="true"
            aria-label="More navigation"
            onClick={() => setOpen(false)}
            style={{
              position:       "fixed",
              inset:          0,
              zIndex:         "var(--z-modal, 1000)",
              background:     "var(--color-bg, #0E0D0B)",
              color:          "var(--color-text-primary, #E8DCC0)",
              display:        "flex",
              flexDirection:  "column",
              paddingTop:     "max(var(--space-6, 24px), env(safe-area-inset-top))",
              paddingBottom:  "max(var(--space-6, 24px), env(safe-area-inset-bottom))",
              fontFamily:     "var(--font-ui, system-ui, sans-serif)",
            }}
          >
            <div
              style={{
                display:        "flex",
                justifyContent: "space-between",
                alignItems:     "center",
                padding:        "0 var(--space-4, 16px) var(--space-4, 16px)",
                borderBottom:   "1px solid var(--color-hairline, rgba(201,166,90,0.3))",
              }}
            >
              <span style={{
                fontSize:   "var(--type-h2, 20px)",
                fontFamily: "var(--font-display, serif)",
                letterSpacing: "0.02em",
              }}>More</span>
              <button
                type="button"
                onClick={() => setOpen(false)}
                aria-label="Close"
                style={{
                  background:     "transparent",
                  border:         "none",
                  color:          "var(--color-text-primary, #E8DCC0)",
                  minHeight:      "var(--touch-target-min, 44px)",
                  minWidth:       "var(--touch-target-min, 44px)",
                  cursor:         "pointer",
                  fontSize:       28,
                  lineHeight:     1,
                  padding:        0,
                }}
              >×</button>
            </div>

            <ul
              style={{
                listStyle: "none",
                margin:    0,
                padding:   "var(--space-2, 8px) var(--space-4, 16px)",
                overflowY: "auto",
                flex:      1,
              }}
            >
              {items.length === 0 ? (
                <li style={{
                  color: "var(--color-text-muted, rgba(232,220,192,0.6))",
                  padding: "var(--space-4, 16px) 0",
                  fontSize: "var(--type-body, 16px)",
                }}>
                  No additional surfaces.
                </li>
              ) : items.map((p) => (
                <li key={p.id}>
                  <a
                    href={p.href}
                    onClick={() => setOpen(false)}
                    style={{
                      display:         "flex",
                      flexDirection:   "column",
                      gap:             "var(--space-1, 4px)",
                      padding:         "var(--space-3, 12px) var(--space-2, 8px)",
                      textDecoration:  "none",
                      color:           "var(--color-text-primary, #E8DCC0)",
                      minHeight:       "var(--touch-target-comfortable, 48px)",
                      fontSize:        "var(--type-body, 16px)",
                      fontFamily:      "var(--font-body, serif)",
                      borderBottom:    "1px solid var(--color-hairline, rgba(201,166,90,0.3))",
                    }}
                  >
                    <span style={{ fontWeight: 500 }}>{p.name}</span>
                    {p.sub && (
                      <span style={{
                        color: "var(--color-text-muted, rgba(232,220,192,0.6))",
                        fontSize: "var(--type-small, 14px)",
                      }}>{p.sub}</span>
                    )}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        )}
      </>
    );
  }

  // ─── Self-mount under documentElement ──────────────────────────────────
  // Anchored above body so destructive React mounts (if any) leave it intact.
  function mount() {
    if (document.getElementById("more-sheet-root")) return;
    const container = document.createElement("div");
    container.id = "more-sheet-root";
    document.documentElement.appendChild(container);
    if (typeof ReactDOM !== "undefined" && ReactDOM.createRoot) {
      ReactDOM.createRoot(container).render(React.createElement(MoreSheet));
    }
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mount);
  } else {
    mount();
  }

  // Export for potential programmatic use
  window.MoreSheet = MoreSheet;
})();
