// ─────────────────────────────────────────────
// DO_NavBar.jsx — unified nav bar
// Desktop: full controls visible
// Mobile: logo + title + hamburger menu
// Swipe left/right on content for record nav
// ─────────────────────────────────────────────

// ── Responsive hook ───────────────────────────
function useNavWidth() {
  const [width, setWidth] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const h = () => setWidth(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return width;
}

function DONavBar({
  view          = "list",
  allObjects    = [],
  currentTable  = null,
  record        = null,
  foundSet      = [],
  foundTotal    = 0,
  totalRecords  = 0,
  offset        = 0,
  pageSize      = 25,
  isNew         = false,
  loading       = false,
  saveMode      = "manual",
  saving        = false,
  saved         = false,
  dirty         = false,
  hasPrev       = false,
  hasNext       = false,
  onHome,
  onTableSelect,
  onNew,
  onRefresh,
  onSearch,
  onSave,
  onFirst,
  onPrev,
  onNext,
  onLast,
  onDelete,
  onDuplicate,
  theme = {},
  currentUser = null,
  onLogout,
  onProfileOpen,
}) {
  const [tableDropOpen,   setTableDropOpen]   = React.useState(false);
  const [userDropOpen,    setUserDropOpen]    = React.useState(false);
  const [actionsDropOpen, setActionsDropOpen] = React.useState(false);
  const [menuOpen,        setMenuOpen]        = React.useState(false);
  const [savedVisible,    setSavedVisible]    = React.useState(false);

  const winWidth = useNavWidth();
  const isMobile = winWidth < 768;

  // Flash saved ✓ for 2s
  React.useEffect(() => {
    if (saved) {
      setSavedVisible(true);
      const t = setTimeout(() => setSavedVisible(false), 2000);
      return () => clearTimeout(t);
    }
  }, [saved]);

  // Swipe support — attach to window, fires onPrev/onNext
  React.useEffect(() => {
    if (!isMobile || view !== 'detail') return;
    let startX = 0;
    const onStart = e => { startX = e.touches[0].clientX; };
    const onEnd   = e => {
      const dx = e.changedTouches[0].clientX - startX;
      if (Math.abs(dx) < 50) return;           // ignore small swipes
      if (dx < 0 && hasNext && !loading) onNext && onNext();   // swipe left → next
      if (dx > 0 && hasPrev && !loading) onPrev && onPrev();   // swipe right → prev
    };
    window.addEventListener('touchstart', onStart, { passive: true });
    window.addEventListener('touchend',   onEnd,   { passive: true });
    return () => {
      window.removeEventListener('touchstart', onStart);
      window.removeEventListener('touchend',   onEnd);
    };
  }, [isMobile, view, hasPrev, hasNext, loading]);

  const tables = allObjects
    .filter(o => o.group === "schema" && o.type === "table" && o.status === "1")
    .sort((a, b) => (a.name || "").localeCompare(b.name || ""));

  const tableObj   = tables.find(t => t.table === currentTable);
  const tableLabel = cleanName(tableObj?.name) || currentTable || "—";

  const titleObj = allObjects.find(
    o => o.group === "object" && o.type === "text" && o.table === currentTable && o.formula
  );
  const recordTitle = isNew
    ? "New Record"
    : record && titleObj?.formula
      ? titleObj.formula.replace(/\{(\w+)\}/g, (_, f) => record[f] || "")
      : record ? `Record ${record.r_auto}` : "";

  const countDisplay = () => {
    if (view === "detail") {
      if (!record) return "";
      const pos = foundSet?.length > 0 ? foundSet.indexOf(record.r_auto) + 1 : null;
      const tot = foundTotal || totalRecords;
      if (pos && foundTotal && foundTotal < totalRecords) return `${pos} of ${foundTotal} / ${totalRecords}`;
      if (pos && tot) return `${pos} of ${tot}`;
      return tot ? `of ${tot}` : "";
    }
    if (view === "list") {
      const from = offset + 1;
      const to   = Math.min(offset + pageSize, foundTotal || totalRecords);
      const tot  = foundTotal || totalRecords;
      return tot ? `${from}–${to} / ${tot}` : "";
    }
    return "";
  };

  const asi = (() => {
    if (saveMode === "manual") return null;
    if (saving)       return { icon: "⟳", color: "#94a3b8",                    title: "Saving…"       };
    if (savedVisible) return { icon: "✓", color: "#86efac",                    title: "Saved"          };
    return              { icon: "⚡", color: "rgba(255,255,255,0.35)",          title: "Auto Save On"  };
  })();

  const navDisabled = (dir) => {
    if (loading || isNew) return true;
    if (dir === "prev" || dir === "first") return !hasPrev;
    if (dir === "next" || dir === "last")  return !hasNext;
    return false;
  };

  const showNav = view === "list" || view === "detail";
  const closeAll = () => {
    setTableDropOpen(false);
    setUserDropOpen(false);
    setActionsDropOpen(false);
    setMenuOpen(false);
  };

  // ── MOBILE NAV ────────────────────────────────
  if (isMobile) {
    return (
      <>
        {(tableDropOpen || userDropOpen || actionsDropOpen || menuOpen) && (
          <div style={{ position:"fixed", inset:0, zIndex:198 }} onClick={closeAll} />
        )}

        <div style={{ ...SN.nav, background: theme.nav_bg || SN.nav.background, padding:"0 10px" }}>

          {/* LEFT — logo + table + record */}
          <div style={{ ...SN.left, gap:4 }}>
            <button style={SN.logo} onClick={() => { closeAll(); onHome && onHome(); }}>
              {theme.logo_url
                ? <img src={theme.logo_url} alt="Logo" style={{ height:24, width:"auto", display:"block" }} />
                : <span>{theme.logo_text || "DO"}</span>
              }
            </button>
            {view !== "home" && (
              <>
                <span style={{ color:"rgba(255,255,255,0.4)", fontSize:13 }}>
                  {validIcon(tableObj?.icon) || ""} {tableLabel}
                </span>
                {view === "detail" && recordTitle && (
                  <>
                    <span style={SN.breadcrumb}>›</span>
                    <span style={{ ...SN.recordTitle, maxWidth:100 }}>{recordTitle}</span>
                    {isNew && <span style={SN.newBadge}>NEW</span>}
                  </>
                )}
              </>
            )}
          </div>

          {/* RIGHT — save + hamburger */}
          <div style={{ display:"flex", alignItems:"center", gap:6, flexShrink:0 }}>
            {/* Save button — always visible on mobile if dirty */}
            {saveMode === "manual" && dirty && (
              <button
                style={{ ...SN.saveBtn, padding:"5px 10px", fontSize:12 }}
                onClick={onSave}
                disabled={saving}
              >
                {saving ? "⟳" : savedVisible ? "✓" : "Save"}
              </button>
            )}

            {/* Hamburger */}
            <div style={{ position:"relative", zIndex:201 }}>
              <button
                style={{ ...SN.iconBtn, fontSize:18, padding:"5px 10px" }}
                onClick={() => setMenuOpen(!menuOpen)}
                title="Menu"
              >☰</button>

              {menuOpen && (
                <div style={{ ...SN.dropdown, right:0, left:"auto", minWidth:220 }}>

                  {/* Count */}
                  {countDisplay() && (
                    <div style={{ padding:"10px 14px 6px", fontSize:12, color:"#94a3b8", borderBottom:"1px solid #f1f5f9" }}>
                      {countDisplay()}
                    </div>
                  )}

                  {/* Navigation — detail only */}
                  {view === "detail" && (
                    <div style={{ display:"flex", gap:6, padding:"10px 14px", borderBottom:"1px solid #f1f5f9" }}>
                      <MBtn onClick={() => { closeAll(); onFirst && onFirst(); }} disabled={navDisabled("first")}>«</MBtn>
                      <MBtn onClick={() => { closeAll(); onPrev  && onPrev();  }} disabled={navDisabled("prev")} >‹ Prev</MBtn>
                      <MBtn onClick={() => { closeAll(); onNext  && onNext();  }} disabled={navDisabled("next")} >Next ›</MBtn>
                      <MBtn onClick={() => { closeAll(); onLast  && onLast();  }} disabled={navDisabled("last")} >»</MBtn>
                    </div>
                  )}

                  {/* List navigation */}
                  {view === "list" && (
                    <div style={{ display:"flex", gap:6, padding:"10px 14px", borderBottom:"1px solid #f1f5f9" }}>
                      <MBtn onClick={() => { closeAll(); onFirst && onFirst(); }} disabled={navDisabled("first")}>«</MBtn>
                      <MBtn onClick={() => { closeAll(); onPrev  && onPrev();  }} disabled={navDisabled("prev")} >‹</MBtn>
                      <MBtn onClick={() => { closeAll(); onNext  && onNext();  }} disabled={navDisabled("next")} >›</MBtn>
                      <MBtn onClick={() => { closeAll(); onLast  && onLast();  }} disabled={navDisabled("last")} >»</MBtn>
                    </div>
                  )}

                  {/* Actions */}
                  <button style={SN.dropItem} onClick={() => { closeAll(); onSearch && onSearch(); }}>
                    <span style={SN.dropItemName}>🔍 Search</span>
                  </button>
                  <button style={SN.dropItem} onClick={() => { closeAll(); onNew && onNew(); }} disabled={isNew}>
                    <span style={SN.dropItemName}>＋ New Record</span>
                  </button>
                  <button style={SN.dropItem} onClick={() => { closeAll(); onRefresh && onRefresh(); }}>
                    <span style={SN.dropItemName}>↺ Refresh</span>
                  </button>

                  {/* Tables */}
                  {tables.length > 1 && (
                    <>
                      <div style={SN.dropDivider} />
                      {tables.map((t, i) => (
                        <button
                          key={i}
                          style={{ ...SN.dropItem, ...(t.table === currentTable ? SN.dropItemActive : {}) }}
                          onClick={() => { closeAll(); onTableSelect && onTableSelect(t.table); }}
                        >
                          <span style={SN.dropItemName}>
                            {validIcon(t.icon) && <span style={{ marginRight:6 }}>{validIcon(t.icon)}</span>}
                            {cleanName(t.name) || t.table}
                          </span>
                        </button>
                      ))}
                    </>
                  )}

                  {/* Record actions */}
                  {view === "detail" && !isNew && (
                    <>
                      <div style={SN.dropDivider} />
                      <button style={SN.dropItem} onClick={() => { closeAll(); onDuplicate && onDuplicate(); }}>
                        <span style={SN.dropItemName}>⧉ Duplicate</span>
                      </button>
                      <button style={{ ...SN.dropItem }} onClick={() => { closeAll(); onDelete && onDelete(); }}>
                        <span style={{ ...SN.dropItemName, color:"#dc2626" }}>⊗ Delete Record</span>
                      </button>
                    </>
                  )}

                  {/* User */}
                  <div style={SN.dropDivider} />
                  <button style={SN.dropItem} onClick={() => { closeAll(); onProfileOpen && onProfileOpen(); }}>
                    <span style={SN.dropItemName}>👤 Profile</span>
                  </button>
                  <button style={SN.dropItem} onClick={() => { closeAll(); onLogout && onLogout(); }}>
                    <span style={SN.dropItemName}>Log Out</span>
                  </button>

                </div>
              )}
            </div>
          </div>
        </div>
      </>
    );
  }

  // ── DESKTOP NAV ───────────────────────────────
  return (
    <>
      {(tableDropOpen || userDropOpen || actionsDropOpen) && (
        <div style={{ position:"fixed", inset:0, zIndex:198 }} onClick={closeAll} />
      )}

      <div style={{ ...SN.nav,
        background:  theme.nav_bg    || SN.nav.background,
        color:       theme.nav_color || SN.nav.color,
        fontFamily:  theme.font      || SN.nav.fontFamily,
      }}>

        {/* ── LEFT ── */}
        <div style={SN.left}>
          <button style={SN.logo} onClick={() => { closeAll(); onHome && onHome(); }} title="Home">
            {theme.logo_url
              ? <img src={theme.logo_url} alt="Logo" style={{ height:28, width:"auto", display:"block" }} />
              : <span>{theme.logo_text || "DO"}</span>
            }
          </button>

          {view !== "home" && (
            <>
              <div style={{ position:"relative", zIndex:201 }}>
                <button
                  style={SN.iconBtn}
                  onClick={() => { setTableDropOpen(!tableDropOpen); setUserDropOpen(false); }}
                  title="Show Tables"
                >▾</button>
                {tableDropOpen && (
                  <div style={SN.dropdown}>
                    {tables.map((t, i) => {
                      const icon = validIcon(t.icon);
                      const name = cleanName(t.name) || t.table;
                      return (
                        <button
                          key={i}
                          style={{ ...SN.dropItem, ...(t.table === currentTable ? SN.dropItemActive : {}) }}
                          onClick={() => { closeAll(); onTableSelect && onTableSelect(t.table); }}
                        >
                          <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                            {icon && <span style={{ fontSize:15 }}>{icon}</span>}
                            <span style={SN.dropItemName}>{name}</span>
                          </div>
                          {t.desc && <span style={SN.dropItemDesc}>{t.desc}</span>}
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>

              <button
                style={SN.tableNameBtn}
                onClick={() => { closeAll(); onTableSelect && onTableSelect(currentTable); }}
                title={`Go to ${tableLabel} list`}
              >
                {validIcon(tableObj?.icon) && <span style={{ marginRight:5 }}>{validIcon(tableObj.icon)}</span>}
                {tableLabel}
              </button>

              {view === "detail" && recordTitle && (
                <>
                  <span style={SN.breadcrumb}>›</span>
                  <button
                    style={SN.recordTitle}
                    onClick={() => { closeAll(); onRefresh && onRefresh(); }}
                    title="Refresh"
                  >{recordTitle}</button>
                  {isNew && <span style={SN.newBadge}>NEW</span>}
                </>
              )}
            </>
          )}
        </div>

        {/* ── RIGHT ── */}
        <div style={SN.right}>
          {showNav && (
            <>
              {countDisplay() && (
                <button style={SN.countBtn} onClick={onSearch} title="Search">
                  {countDisplay()}
                </button>
              )}

              {asi && (
                <span style={{ ...SN.autoSaveSlot, color: asi.color }} title={asi.title}>
                  {asi.icon}
                </span>
              )}

              {saveMode === "manual" && (
                <button
                  style={{ ...SN.saveBtn, ...(!dirty ? SN.saveBtnOff : savedVisible ? SN.saveBtnSaved : {}) }}
                  onClick={onSave}
                  disabled={!dirty || saving}
                  title="Save"
                >
                  {saving ? "⟳" : savedVisible ? "✓" : "Save"}
                </button>
              )}

              <span style={SN.sep}>|</span>

              <NBtn onClick={onFirst} title="First Record"    disabled={navDisabled("first")}>«</NBtn>
              <NBtn onClick={onPrev}  title="Previous Record" disabled={navDisabled("prev")} >‹</NBtn>
              <NBtn onClick={onNext}  title="Next Record"     disabled={navDisabled("next")} >›</NBtn>
              <NBtn onClick={onLast}  title="Last Record"     disabled={navDisabled("last")} >»</NBtn>

              <span style={SN.sep}>|</span>

              <NBtn onClick={onSearch}  title="Search">🔍</NBtn>
              <NBtn onClick={onNew}     title="Add New Record" disabled={isNew}>+</NBtn>
              <NBtn onClick={onRefresh} title="Refresh" disabled={loading}>↺</NBtn>
            </>
          )}

          {view === "detail" && !isNew && (
            <>
              <span style={SN.sep}>|</span>
              <div style={{ position:"relative", zIndex:201 }}>
                <button
                  style={SN.iconBtn}
                  onClick={() => { setActionsDropOpen(!actionsDropOpen); setTableDropOpen(false); setUserDropOpen(false); }}
                  title="Record Actions"
                >≡</button>
                {actionsDropOpen && (
                  <div style={{ ...SN.dropdown, right:0, left:"auto", minWidth:180 }}>
                    <button style={SN.dropItem} onClick={() => { closeAll(); onDuplicate && onDuplicate(); }}>
                      <span style={SN.dropItemName}>⧉ Duplicate Record</span>
                    </button>
                    <div style={SN.dropDivider} />
                    <button style={{ ...SN.dropItem, ...SN.dropItemDanger }} onClick={() => { closeAll(); onDelete && onDelete(); }}>
                      <span style={{ ...SN.dropItemName, color:"#dc2626" }}>⊗ Delete Record</span>
                    </button>
                  </div>
                )}
              </div>
            </>
          )}

          <span style={SN.sep}>|</span>

          {/* User menu */}
          <div style={{ position:"relative", zIndex:201 }}>
            <button
              style={{ ...SN.iconBtn, padding:'5px 10px', lineHeight:0 }}
              onClick={() => { setUserDropOpen(!userDropOpen); setTableDropOpen(false); setActionsDropOpen(false); }}
              title="Account"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                <circle cx="12" cy="7" r="4"/>
              </svg>
            </button>
            {userDropOpen && (
              <div style={{ ...SN.dropdown, right:0, left:"auto", minWidth:160 }}>
                <button style={SN.dropItem} onClick={() => { closeAll(); onProfileOpen && onProfileOpen(); }}>
                  <span style={SN.dropItemName}>Profile</span>
                </button>
                <div style={SN.dropDivider} />
                <button style={SN.dropItem} onClick={() => { closeAll(); onLogout && onLogout(); }}>
                  <span style={SN.dropItemName}>Log Out</span>
                </button>
              </div>
            )}
          </div>


        </div>
      </div>
    </>
  );
}

// ── Helpers ───────────────────────────────────
function cleanName(name) {
  return (name || "").replace(/^[^A-Za-z0-9]+/, "").trim() || name;
}
function validIcon(icon) {
  if (!icon || !icon.trim() || icon.includes("?") || icon.includes("í")) return null;
  return icon.trim();
}

// ── Desktop nav button ────────────────────────
function NBtn({ onClick, title, disabled, children }) {
  return (
    <button
      style={{ ...SN.iconBtn, opacity: disabled ? 0.3 : 1, cursor: disabled ? "default" : "pointer" }}
      onClick={disabled ? undefined : onClick}
      title={title}
    >{children}</button>
  );
}

// ── Mobile menu button ────────────────────────
function MBtn({ onClick, disabled, children }) {
  return (
    <button
      style={{
        flex: 1, background: disabled ? "#f1f5f9" : "#1a3a5c",
        color: disabled ? "#94a3b8" : "#fff",
        border: "none", borderRadius: 4, padding: "7px 4px",
        fontSize: 13, fontWeight: 600, cursor: disabled ? "default" : "pointer",
        fontFamily: "inherit", textAlign: "center",
      }}
      onClick={disabled ? undefined : onClick}
      disabled={disabled}
    >{children}</button>
  );
}

// ─────────────────────────────────────────────
// STYLES
// ─────────────────────────────────────────────
const SN = {
  nav:           { background:"#0f2744", color:"#fff", display:"flex", alignItems:"center", justifyContent:"space-between", padding:"0 14px", height:50, position:"sticky", top:0, zIndex:200, boxShadow:"0 2px 8px rgba(0,0,0,0.3)", fontFamily:"'Segoe UI',sans-serif", userSelect:"none", overflow:"visible" },
  left:          { display:"flex", alignItems:"center", gap:6, flex:1, minWidth:0 },
  right:         { display:"flex", alignItems:"center", gap:5, flexShrink:0 },
  logo:          { background:"none", border:"none", color:"#fff", fontSize:17, fontWeight:900, cursor:"pointer", padding:"4px 6px", fontFamily:"inherit", letterSpacing:"0.05em" },
  iconBtn:       { background:"rgba(255,255,255,0.1)", border:"1px solid rgba(255,255,255,0.15)", color:"#fff", padding:"5px 11px", borderRadius:4, fontSize:15, cursor:"pointer", fontFamily:"inherit", lineHeight:1 },
  tableNameBtn:  { background:"none", border:"none", color:"#fff", fontSize:15, fontWeight:700, cursor:"pointer", padding:"4px 6px", borderRadius:4, fontFamily:"inherit", whiteSpace:"nowrap" },
  breadcrumb:    { color:"rgba(255,255,255,0.2)", fontSize:16, padding:"0 2px", flexShrink:0 },
  recordTitle:   { background:"none", border:"none", color:"rgba(255,255,255,0.6)", fontSize:14, cursor:"pointer", fontFamily:"inherit", padding:"2px 4px", borderRadius:3, maxWidth:200, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" },
  newBadge:      { fontSize:11, fontWeight:700, background:"#22c55e", color:"#fff", padding:"2px 8px", borderRadius:10, marginLeft:4, flexShrink:0 },
  dropdown:      { position:"absolute", top:"calc(100% + 8px)", left:0, background:"#fff", border:"1px solid #e2e8f0", borderRadius:8, boxShadow:"0 8px 24px rgba(0,0,0,0.15)", zIndex:300, minWidth:200, overflow:"hidden" },
  dropItem:      { display:"flex", flexDirection:"column", alignItems:"flex-start", width:"100%", background:"none", border:"none", padding:"10px 14px", cursor:"pointer", fontFamily:"inherit", borderBottom:"1px solid #f1f5f9" },
  dropItemActive:{ background:"#f0f7ff" },
  dropItemName:  { fontSize:13, fontWeight:600, color:"#1e293b" },
  dropItemDesc:  { fontSize:11, color:"#94a3b8", marginTop:2 },
  sep:           { color:"rgba(255,255,255,0.15)", padding:"0 3px", fontSize:18, flexShrink:0 },
  autoSaveSlot:  { fontSize:16, width:28, textAlign:"center", display:"inline-block", transition:"color 0.4s", flexShrink:0 },
  saveBtn:       { background:"#f59e0b", border:"none", color:"#1a1a1a", padding:"5px 13px", borderRadius:4, cursor:"pointer", fontSize:13, fontWeight:700, fontFamily:"inherit" },
  saveBtnSaved:  { background:"#22c55e", color:"#fff" },
  saveBtnOff:    { background:"rgba(255,255,255,0.1)", color:"rgba(255,255,255,0.3)", cursor:"default" },
  countBtn:      { background:"none", border:"1px solid rgba(255,255,255,0.2)", color:"rgba(255,255,255,0.7)", padding:"4px 10px", borderRadius:10, fontSize:12, cursor:"pointer", fontFamily:"inherit", whiteSpace:"nowrap" },
  dropDivider:   { height:1, background:"#f1f5f9", margin:"4px 0" },
  dropItemDanger:{},
  userBtn:       { width:30, height:30, borderRadius:"50%", background:"#2563a8", border:"2px solid rgba(255,255,255,0.25)", color:"#fff", fontSize:13, fontWeight:700, cursor:"pointer", fontFamily:"inherit" },
  userMenuBtn:   { background:"rgba(255,255,255,0.1)", border:"1px solid rgba(255,255,255,0.2)", color:"#fff", padding:"5px 12px", borderRadius:4, fontSize:13, fontWeight:600, cursor:"pointer", fontFamily:"inherit", whiteSpace:"nowrap" },
};
