// =============================================================
// Sidebar
// =============================================================
function Sidebar({ page, onNavigate, theme, setTheme, onOpenProject, recentsKey, user, authReady }) {
  const [logoMenu, setLogoMenu] = useState(false);
  const [signingIn, setSigningIn] = useState(false);
  const avatarUrl = user?.user_metadata?.avatar_url || user?.user_metadata?.picture || null;

  const signIn = async () => {
    if (signingIn) return;
    setSigningIn(true);
    try {
      await Auth.signInWithGoogle();
      // Success navigates away via the OAuth redirect — stay in the
      // loading state rather than resetting (a `finally` here would reset
      // it the instant the promise resolves, which happens well before
      // the redirect actually navigates away, so the spinner would never
      // be visible).
    } catch (e) {
      setSigningIn(false);
    }
  };
  const nav = [
    { id: "home", path: "/", label: "Home", icon: Icons.Home },
    { id: "brand", path: "/brand", label: "Brand Foundations", icon: Icons.Palette },
    { id: "templates", path: "/templates", label: "Templates", icon: Icons.Grid },
    { id: "generate", path: "/generate", label: "Generate from scratch", icon: Icons.Sparkle },
  ];

  const go = (path) => { setLogoMenu(false); onNavigate(path); };

  return (
    <aside className="sidebar">
      <button
        className="sidebar-brand"
        onClick={() => setLogoMenu(true)}
        title="Flexxi menu"
        style={{ border: "none", background: "transparent", cursor: "pointer", width: "100%" }}
      >
        <img
          src="assets/logo-stacked.svg"
          alt="Flexxi"
          className="sidebar-brand-logo sidebar-brand-logo--light"
        />
        <img
          src="assets/logo-stacked-white.svg"
          alt="Flexxi"
          className="sidebar-brand-logo sidebar-brand-logo--dark"
        />
      </button>

      {/* LOGO MENU — modal with quick options */}
      {logoMenu && (
        <div
          style={{ position: "fixed", inset: 0, zIndex: 120, background: "rgba(7,7,7,0.55)", display: "grid", placeItems: "center", padding: 24 }}
          onClick={() => setLogoMenu(false)}
        >
          <div
            className="card fade-in"
            style={{ width: 340, maxWidth: "100%", padding: 22 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <div>
                <div className="eyebrow">FLEXXI</div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 19, letterSpacing: "-0.02em", marginTop: 2 }}>
                  {user ? (user.name || user.email) : "Marketing Studio"}
                </div>
              </div>
              <button className="btn btn-sm btn-ghost" style={{ padding: "5px 8px" }} onClick={() => setLogoMenu(false)}>
                <Icons.X size={14} />
              </button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {user ? (
                <button className="logo-menu-item" onClick={() => go("/profile")}>
                  <span className="logo-menu-avatar">
                    {avatarUrl ? (
                      <img src={avatarUrl} alt="" style={{ width: "100%", height: "100%", borderRadius: "50%", objectFit: "cover" }} />
                    ) : (
                      (user.name || user.email || "U").slice(0, 2).toUpperCase()
                    )}
                  </span>
                  <span style={{ flex: 1, textAlign: "left" }}>
                    <span style={{ display: "block", fontWeight: 600 }}>Go to profile</span>
                    <span style={{ display: "block", fontSize: 11.5, color: "var(--ink-3)" }}>Saved items · design history · account</span>
                  </span>
                  <Icons.ArrowRight size={14} />
                </button>
              ) : (
                <button className="logo-menu-item" onClick={() => { setLogoMenu(false); Auth.signInWithGoogle(); }}>
                  <span className="logo-menu-avatar">FX</span>
                  <span style={{ flex: 1, textAlign: "left" }}>
                    <span style={{ display: "block", fontWeight: 600 }}>Sign in with Google</span>
                    <span style={{ display: "block", fontSize: 11.5, color: "var(--ink-3)" }}>Required to save, generate, and export</span>
                  </span>
                  <Icons.ArrowRight size={14} />
                </button>
              )}
              <button className="logo-menu-item" onClick={() => go("/")}>
                <Icons.Home size={16} /> Home
              </button>
              <button className="logo-menu-item" onClick={() => go("/brand")}>
                <Icons.Palette size={16} /> Brand Foundations
              </button>
              <button className="logo-menu-item" onClick={() => go("/templates")}>
                <Icons.Grid size={16} /> Templates
              </button>
              <div style={{ height: 1, background: "var(--line)", margin: "8px 0" }} />
              {user ? (
                <button className="logo-menu-item" onClick={() => Auth.signOut()}>
                  <Icons.ArrowRight size={16} /> Sign out
                </button>
              ) : (
                <button
                  className="logo-menu-item"
                  onClick={async () => { try { await API.gateLock(); } catch (e) {} window.location.reload(); }}
                >
                  <Icons.Lock size={16} /> Lock workspace
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      <div className="sidebar-section-label">Workspace</div>
      {nav.map((n) => (
        <button
          key={n.id}
          className={`nav-item ${page === n.id ? "active" : ""}`}
          onClick={() => onNavigate(n.path)}
        >
          <n.icon size={18} />
          {n.label}
        </button>
      ))}

      <div className="sidebar-section-label">Recent</div>
      <Recents onOpenProject={onOpenProject} refreshKey={recentsKey} userId={user?.id} authReady={authReady} />

      <div style={{ flex: 1 }}></div>

      {/* HELP CARD */}
      <div
        className="promo-invert"
        style={{
          padding: 14,
          borderRadius: 14,
          marginBottom: 12,
          position: "relative",
          overflow: "hidden",
        }}
      >
        <div style={{ fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 4 }}>
          Generate with AI
        </div>
        <div style={{ fontSize: 11.5, color: "#9A9A9A", marginBottom: 10, lineHeight: 1.4 }}>
          Paste a brief, get a carousel.
        </div>
        <button
          className="btn btn-yellow btn-sm"
          style={{ width: "100%", justifyContent: "center" }}
          onClick={() => onNavigate("/generate")}
        >
          Try it
        </button>
      </div>

      {/* THEME TOGGLE */}
      <div className="theme-toggle" style={{ marginBottom: 12 }}>
        <button className={theme === "light" ? "active" : ""} onClick={() => setTheme("light")}>
          <Icons.Sun size={14} /> Light
        </button>
        <button className={theme === "dark" ? "active" : ""} onClick={() => setTheme("dark")}>
          <Icons.Moon size={14} /> Dark
        </button>
      </div>

      {!user ? (
        // Past the password gate but not signed in — sign-in is required to
        // use any feature (save, generate, export, brand kit, profile).
        <button
          className="btn btn-surface btn-sm"
          style={{ width: "100%", justifyContent: "center" }}
          onClick={signIn}
          disabled={signingIn}
          title="Sign in with Google"
        >
          {signingIn ? <span className="spinner" style={{ width: 13, height: 13 }} /> : <Icons.Sparkle size={13} />} Sign in
        </button>
      ) : (
        <div
          className="sidebar-user"
          onClick={() => onNavigate("/profile")}
          title="Go to profile"
          style={{ cursor: "pointer" }}
        >
          <div className="sidebar-user-avatar">
            {avatarUrl ? (
              <img src={avatarUrl} alt="" style={{ width: "100%", height: "100%", borderRadius: "50%", objectFit: "cover" }} />
            ) : (
              (user.email || "U").slice(0, 2).toUpperCase()
            )}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="sidebar-user-name">
              {user.name || user.user_metadata?.full_name || user.email}
            </div>
            <div className="sidebar-user-org">Flexxi</div>
          </div>
          <button
            onClick={(e) => { e.stopPropagation(); Auth.signOut(); }}
            title="Sign out"
            style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--ink-3)", display: "grid", placeItems: "center" }}
          >
            <Icons.ArrowRight size={14} />
          </button>
        </div>
      )}
    </aside>
  );
}

// =============================================================
// Recents — saved projects pulled from the backend
// =============================================================
function Recents({ onOpenProject, refreshKey, userId, authReady }) {
  const [projects, setProjects] = useState(null);
  useEffect(() => {
    // listProjects() requires sign-in, and Auth.init() resolves
    // asynchronously alongside this component's mount — fetching before
    // that finishes would just throw and get stuck showing "Nothing here
    // yet" until the next manual refresh. Keep showing "Loading…" (projects
    // stays null) until we actually know whether there's a signed-in user.
    if (!authReady) return;
    if (!userId) {
      setProjects([]);
      return;
    }
    let alive = true;
    API.listProjects()
      .then(({ projects }) => { if (alive) setProjects(projects); })
      .catch(() => { if (alive) setProjects([]); });
    return () => { alive = false; };
  }, [refreshKey, userId, authReady]);

  if (projects === null) {
    return (
      <div style={{ padding: "0 4px 8px", display: "flex", flexDirection: "column", gap: 6 }}>
        {[0, 1, 2].map((i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 12px" }}>
            <div className="skeleton-bar" style={{ width: 15, height: 15, borderRadius: 4, flexShrink: 0 }}></div>
            <div className="skeleton-bar" style={{ width: `${70 - i * 12}%`, height: 11 }}></div>
          </div>
        ))}
      </div>
    );
  }
  if (projects.length === 0) {
    return <div style={{ fontSize: 12, color: "var(--ink-3)", padding: "8px 12px" }}>Nothing here yet.</div>;
  }
  return (
    <div style={{ padding: "0 4px 8px", display: "flex", flexDirection: "column", gap: 2 }}>
      {projects.slice(0, 8).map((p) => (
        <button
          key={p.id}
          className="nav-item"
          onClick={() => onOpenProject?.(p.id)}
          style={{ fontSize: 12.5 }}
          title={p.name}
        >
          <Icons.Grid size={15} />
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</span>
        </button>
      ))}
    </div>
  );
}
