50+ open-source generative AI apps you can clone, deploy, and monetize — image generators, video tools, virtual try-ons, AI SaaS templates, and platform integrations. One-click Vercel deploy on every template.
JavaScript ai-appsai-image-generatorai-saasai-toolsai-video-generatorawesomeawesome-listgenerative-aigenerative-ai-appsimage-generationnextjsnextjs-boilerplateopen-sourceopen-source-aisaas-boilerplatesaas-templateseedance2text-to-imagetext-to-videovideo-generation
feat: show only connected channels in composer and provide add channel modal
jaiprasad044f2805700b83
diff --git a/src/app/api/posts/[id]/route.js b/src/app/api/posts/[id]/route.jsindex c1ded39..4a43ffa 100644--- a/src/app/api/posts/[id]/route.js+++ b/src/app/api/posts/[id]/route.js@@ -60,6 +60,105 @@ export async function PATCH(req, { params }) {return NextResponse.json({ error: "Cannot modify a post that is currently uploading." }, { status: 400 });}+ if (body.action === "publish_now") {+ // Resolve real connected account ID if missing or dummy 101+ let targetAccountId = post.accountId;+ const plat = (post.platform || "").toLowerCase().replace("x_twitter", "x").replace("twitter", "x");++ if (!targetAccountId || targetAccountId === 101) {+ try {+ const accRes = await fetch("https://muapi.ai/api/social/accounts", {+ headers: { "x-api-key": config.ai.apiKey }+ });+ if (accRes.ok) {+ const devAccounts = await accRes.json();+ const matched = devAccounts.find(a => (a.platform_name || "").toLowerCase() === plat);+ if (matched) targetAccountId = matched.id;+ }+ } catch (_) {}+ }++ let requestId = null;+ let publishError = null;++ const endpointMap = {+ youtube: "https://api.muapi.ai/api/v1/youtube-publish",+ tiktok: "https://api.muapi.ai/api/v1/tiktok-publish",+ instagram: "https://api.muapi.ai/api/v1/instagram-publish",+ x: "https://api.muapi.ai/api/v1/x-publish",+ facebook: "https://api.muapi.ai/api/v1/facebook-publish",+ linkedin: "https://api.muapi.ai/api/v1/linkedin-publish",+ threads: "https://api.muapi.ai/api/v1/threads-publish",+ pinterest: "https://api.muapi.ai/api/v1/pinterest-publish",+ };+ const endpoint = endpointMap[plat] || endpointMap.youtube;++ const captionText = [+ post.title,+ post.description,+ post.tags ? post.tags.split(",").map(t => t.trim().startsWith("#") ? t.trim() : `#${t.trim()}`).join(" ") : ""+ ].filter(Boolean).join("\n\n");++ const bodyData = {+ account_id: parseInt(targetAccountId) || 101,+ media_url: post.mediaUrl+ };++ if (plat === "youtube") {+ bodyData.title = post.title || "Untitled Video";+ bodyData.description = post.description || "";+ bodyData.tags = post.tags ? post.tags.split(",").map(t => t.trim()) : [];+ bodyData.privacy = post.privacy || "public";+ if (post.categoryId) bodyData.category_id = post.categoryId;+ bodyData.madeForKids = post.madeForKids || false;+ } else if (plat === "x") {+ bodyData.caption = captionText.substring(0, 280);+ bodyData.reply_settings = "everyone";+ } else if (plat === "tiktok") {+ bodyData.title = post.title || captionText;+ bodyData.privacy_level = post.privacy || "PUBLIC_TO_EVERYONE";+ } else if (plat === "instagram" || plat === "facebook" || plat === "threads" || plat === "linkedin") {+ bodyData.caption = captionText;+ bodyData.placement = "timeline";+ } else if (plat === "pinterest") {+ bodyData.title = post.title || "Untitled Pin";+ bodyData.caption = post.description || captionText;+ }++ try {+ const pubRes = await fetch(endpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "x-api-key": config.ai.apiKey+ },+ body: JSON.stringify(bodyData)+ });++ if (!pubRes.ok) {+ const errText = await pubRes.text();+ throw new Error(`MuAPI submission failed: ${errText}`);+ }+ const pubData = await pubRes.json();+ requestId = pubData.request_id || pubData.id;+ } catch (pubErr) {+ console.error(`[PUBLISH_NOW_ERR] Failed for ${plat}:`, pubErr.message);+ publishError = pubErr.message;+ }++ const updatedPost = await prisma.scheduledPost.update({+ where: { id },+ data: {+ accountId: parseInt(targetAccountId) || 101,+ status: publishError ? "failed" : "processing",+ requestId: requestId || ("req_" + Date.now()),+ error: publishError+ }+ });++ return NextResponse.json(updatedPost);+ }+const updateData = {};if (body.scheduledAt) {updateData.scheduledAt = new Date(body.scheduledAt);diff --git a/src/app/api/posts/route.js b/src/app/api/posts/route.jsindex c357ec2..973d643 100644--- a/src/app/api/posts/route.js+++ b/src/app/api/posts/route.js@@ -113,14 +113,33 @@ export async function GET(req) {// 2. Trigger Due Scheduled Postsconst duePosts = posts.filter(p => p.status === "scheduled" && new Date(p.scheduledAt) <= now);++ // Pre-fetch connected accounts if any due post has a dummy or missing accountId+ let devAccounts = null;+ if (duePosts.some(p => !p.accountId || p.accountId === 101) && config.ai.apiKey) {+ try {+ const accRes = await fetch("https://muapi.ai/api/social/accounts", {+ headers: { "x-api-key": config.ai.apiKey }+ });+ if (accRes.ok) devAccounts = await accRes.json();+ } catch (_) {}+ }+for (const post of duePosts) {try {// Deduct 1 credit for publishingawait UserService.deductCredits(userId, config.ai.generationCost);+ let targetAccountId = post.accountId;+ if ((!targetAccountId || targetAccountId === 101) && devAccounts) {+ const normPlat = (post.platform || "").toLowerCase().replace("x_twitter", "x").replace("twitter", "x");+ const matched = devAccounts.find(a => (a.platform_name || "").toLowerCase() === normPlat);+ if (matched) targetAccountId = matched.id;+ }+// Trigger postconst requestId = await triggerMuApiPublish(post.platform, {- accountId: post.accountId,+ accountId: targetAccountId,mediaUrl: post.mediaUrl,title: post.title,description: post.description,@@ -136,6 +155,7 @@ export async function GET(req) {await prisma.scheduledPost.update({where: { id: post.id },data: {+ accountId: targetAccountId,status: "processing",requestId: requestId}@@ -282,10 +302,33 @@ export async function POST(req) {}const createdPosts = [];+ const platformAccountMap = body.platformAccountMap || {};++ let devAccounts = [];+ if (config.ai.apiKey) {+ try {+ const accRes = await fetch("https://muapi.ai/api/social/accounts", {+ headers: { "x-api-key": config.ai.apiKey }+ });+ if (accRes.ok) devAccounts = await accRes.json();+ } catch (_) {}+ }for (const plat of targetPlatforms) {- const platAccountName = accountName || `${plat} Account`;- const platAccountId = parseInt(accountId) || 101;+ const normPlat = plat.toLowerCase().replace("x_twitter", "x").replace("twitter", "x");+ let platAccountId = platformAccountMap[plat] || platformAccountMap[normPlat];+ let platAccountName = accountName;++ if (!platAccountId || platAccountId === 101) {+ const matched = devAccounts.find(a => (a.platform_name || "").toLowerCase() === normPlat);+ if (matched) {+ platAccountId = matched.id;+ platAccountName = matched.account_name || platAccountName;+ }+ }++ platAccountId = parseInt(platAccountId) || 101;+ platAccountName = platAccountName || `${plat} Account`;if (isScheduled) {try {@@ -338,7 +381,9 @@ export async function POST(req) {await UserService.deductCredits(userId, costPerPost);} catch (e) {}- let requestId = "req_" + Date.now() + "_" + Math.random().toString(36).slice(2, 6);+ let requestId = null;+ let publishError = null;+if (config.ai.apiKey && !config.ai.apiKey.includes("your_")) {try {requestId = await triggerMuApiPublish(plat, {@@ -360,10 +405,14 @@ export async function POST(req) {replySettings});} catch (pubErr) {- console.warn(`[IMMEDIATE_PUBLISH_ERR] Failed for ${plat}:`, pubErr.message);+ console.error(`[IMMEDIATE_PUBLISH_ERR] Failed for ${plat}:`, pubErr.message);+ publishError = pubErr.message;}}+ const postStatus = publishError ? "failed" : (requestId ? "processing" : "completed");+ const finalRequestId = requestId || ("req_" + Date.now() + "_" + Math.random().toString(36).slice(2, 6));+try {const post = await prisma.scheduledPost.create({data: {@@ -382,8 +431,9 @@ export async function POST(req) {categoryId: categoryId || null,madeForKids: !!madeForKids,scheduledAt: new Date(),- status: "processing",- requestId: requestId+ status: postStatus,+ requestId: finalRequestId,+ error: publishError}});createdPosts.push(post);@@ -400,8 +450,9 @@ export async function POST(req) {tags: tags || "",privacy: privacy || "public",scheduledAt: new Date().toISOString(),- status: "completed",- requestId: requestId,+ status: postStatus,+ requestId: finalRequestId,+ error: publishError,publishedUrl: `https://${plat}.com/sample_post`});createdPosts.push(post);diff --git a/src/app/api/social/accounts/[id]/route.js b/src/app/api/social/accounts/[id]/route.jsindex af30c02..f5fbe81 100644--- a/src/app/api/social/accounts/[id]/route.js+++ b/src/app/api/social/accounts/[id]/route.js@@ -23,7 +23,7 @@ export async function DELETE(req, { params }) {});if (!res.ok) {- res = await fetch(`https://api.muapi.ai/api/social/accounts/${id}`, {+ res = await fetch(`https://muapi.ai/api/social/accounts/${id}`, {method: "DELETE",headers: { "x-api-key": apiKey }});@@ -68,7 +68,7 @@ export async function PATCH(req, { params }) {});if (!res.ok) {- res = await fetch(`https://api.muapi.ai/api/social/accounts/${id}`, {+ res = await fetch(`https://muapi.ai/api/social/accounts/${id}`, {method: "PATCH",headers: {"Content-Type": "application/json",diff --git a/src/app/api/social/accounts/route.js b/src/app/api/social/accounts/route.jsindex 8ee9451..81ad9f3 100644--- a/src/app/api/social/accounts/route.js+++ b/src/app/api/social/accounts/route.js@@ -63,7 +63,7 @@ export async function GET(req) {// 2. Fetch first-party accounts (connected under the developer's key)try {- const devRes = await fetch("https://api.muapi.ai/api/social/accounts", {+ const devRes = await fetch("https://muapi.ai/api/social/accounts", {headers: { "x-api-key": apiKey }});if (devRes.ok) {diff --git a/src/app/api/social/connect/route.js b/src/app/api/social/connect/route.jsindex db6c797..606d285 100644--- a/src/app/api/social/connect/route.js+++ b/src/app/api/social/connect/route.js@@ -19,9 +19,9 @@ export async function POST(req) {const extUserId = session.user.email;const finalRedirect = redirectUrl || `${config.auth.url}/integrations`;- const plat = (platform || "").toLowerCase().replace("x_twitter", "x");+ const plat = (platform || "").toLowerCase().replace("x_twitter", "x").replace("twitter", "x");- // Check if platform has a dedicated developer connect-url endpoint in MuAPI+ // 1. Check if platform has a dedicated developer connect-url endpoint in MuAPI (e.g. youtube, tiktok, instagram, facebook)const connectUrlPlatforms = ["youtube", "tiktok", "instagram", "facebook"];if (connectUrlPlatforms.includes(plat)) {try {@@ -45,16 +45,50 @@ export async function POST(req) {}}} catch (err) {- console.warn(`[CONNECT_URL_FALLBACK] Failed for ${plat}:`, err.message);+ console.warn(`[CONNECT_URL_FALLBACK] Dedicated endpoint failed for ${plat}:`, err.message);}}- // Direct connect URL route via MuAPI social router+ // 2. For platforms like x, linkedin, threads, pinterest (or fallback for above):+ // Call MuAPI social connect endpoint server-side with the developer x-api-key.+ // MuAPI responds with HTTP 307 redirect whose Location header contains the OAuth URL.const encodedName = encodeURIComponent(accountName || `${plat.toUpperCase()} Account`);const encodedRedirect = encodeURIComponent(finalRedirect);const directUrl = `https://muapi.ai/api/social/${plat}/connect?account_name=${encodedName}&redirect_to=${encodedRedirect}`;- return NextResponse.json({ url: directUrl });+ try {+ const authRes = await fetch(directUrl, {+ method: "GET",+ headers: {+ "x-api-key": apiKey+ },+ redirect: "manual"+ });++ const redirectLocation = authRes.headers.get("location");+ if (redirectLocation) {+ return NextResponse.json({ url: redirectLocation });+ }++ // If status is 200 and has url in json+ if (authRes.ok) {+ const text = await authRes.text();+ try {+ const json = JSON.parse(text);+ if (json.url) return NextResponse.json({ url: json.url });+ } catch (_) {}+ }++ const errText = await authRes.text().catch(() => "");+ console.error(`[CONNECT_ERROR] ${plat} connect returned status ${authRes.status}:`, errText);+ return NextResponse.json(+ { error: `Failed to initiate ${plat} connection (${authRes.status}): ${errText || "Authorization failed"}` },+ { status: authRes.status >= 400 ? authRes.status : 500 }+ );+ } catch (err) {+ console.error(`[CONNECT_ERROR] Error fetching auth url for ${plat}:`, err);+ return NextResponse.json({ error: `Connection failed: ${err.message}` }, { status: 500 });+ }} catch (error) {console.error("[SOCIAL_CONNECT_ERROR]", error);return NextResponse.json({ error: error.message || "Internal Server Error" }, { status: 500 });diff --git a/src/app/integrations/page.js b/src/app/integrations/page.jsindex 172370d..df6a530 100644--- a/src/app/integrations/page.js+++ b/src/app/integrations/page.js@@ -101,7 +101,7 @@ export default function IntegrationsPage() {useEffect(() => {// Fetch interest counts from MuAPI public endpoint- fetch("https://api.muapi.ai/api/social/integration-interest-counts")+ fetch("https://muapi.ai/api/social/integration-interest-counts").then((res) => res.json()).then((data) => setInterestCounts(data || {})).catch(() => {});@@ -273,7 +273,7 @@ export default function IntegrationsPage() {}));// Call MuAPI (ignore errors due to session auth requirement)- await fetch("https://api.muapi.ai/api/social/integration-interest", {+ await fetch("https://muapi.ai/api/social/integration-interest", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ platform_name: platform.name })diff --git a/src/app/page.js b/src/app/page.jsindex 2d4c415..fc9bd70 100644--- a/src/app/page.js+++ b/src/app/page.js@@ -26,6 +26,7 @@ export default function WorkspaceDashboard() {const { data: session, status } = useSession();const [posts, setPosts] = useState([]);const [loading, setLoading] = useState(true);+ const [connectedAccounts, setConnectedAccounts] = useState([]);// Composer Modal Stateconst [composerOpen, setComposerOpen] = useState(false);@@ -53,11 +54,25 @@ export default function WorkspaceDashboard() {}}, []);+ // Fetch real connected accounts+ const fetchAccounts = useCallback(async () => {+ try {+ const res = await fetch("/api/social/accounts");+ if (res.ok) {+ const data = await res.json();+ setConnectedAccounts(Array.isArray(data) ? data : []);+ }+ } catch (err) {+ console.warn("Error fetching accounts:", err);+ }+ }, []);+useEffect(() => {if (status === "authenticated") {fetchPosts();+ fetchAccounts();}- }, [status, fetchPosts]);+ }, [status, fetchPosts, fetchAccounts]);// Handlers for Calendar Actionsconst handleDateClick = (date) => {@@ -112,6 +127,30 @@ export default function WorkspaceDashboard() {}};+ const handlePublishNow = async (postId) => {+ try {+ setActionLoading(true);+ const res = await fetch(`/api/posts/${postId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action: "publish_now" })+ });+ if (res.ok) {+ const updated = await res.json();+ setViewingPost(updated);+ fetchPosts();+ } else {+ const data = await res.json();+ alert(data.error || "Failed to publish post.");+ }+ } catch (err) {+ console.error(err);+ alert("Error publishing post");+ } finally {+ setActionLoading(false);+ }+ };+const handlePostSaved = (savedPost) => {setPosts((prev) => {const idx = prev.findIndex((p) => p.id === savedPost.id);@@ -285,13 +324,25 @@ export default function WorkspaceDashboard() {<span className="text-[11px] font-semibold text-zinc-400 tracking-wider uppercase">CONNECTED CHANNELS</span>- <p className="text-2xl font-bold text-purple-500 font-mono">- {uniqueChannels}- </p>+ <div className="flex items-baseline gap-2">+ <p className="text-2xl font-bold text-purple-500 font-mono">+ {connectedAccounts.length > 0 ? connectedAccounts.length : uniqueChannels}+ </p>+ <Link+ href="/integrations"+ className="text-[11px] font-medium text-purple-400 hover:text-purple-300 hover:underline"+ >+ + Add+ </Link>+ </div></div>- <div className="w-8 h-8 rounded-lg bg-purple-500/15 border border-purple-500/30 text-purple-400 flex items-center justify-center text-xs shadow-sm shadow-purple-500/20">+ <Link+ href="/integrations"+ className="w-8 h-8 rounded-lg bg-purple-500/15 hover:bg-purple-500/25 border border-purple-500/30 text-purple-400 flex items-center justify-center text-xs shadow-sm shadow-purple-500/20 transition-colors"+ title="Manage Connected Channels"+ ><FaShareAlt />- </div>+ </Link></div>{/* Card 4: Credits Balance */}@@ -398,6 +449,14 @@ export default function WorkspaceDashboard() {</span></div>+ {/* Error Banner if any */}+ {viewingPost.error && (+ <div className="p-2.5 rounded-lg bg-red-500/10 border border-red-500/30 text-xs text-red-400 flex items-start gap-2">+ <FaExclamationTriangle className="text-red-400 text-xs shrink-0 mt-0.5" />+ <span className="leading-normal">{viewingPost.error}</span>+ </div>+ )}+{/* Action Buttons */}<div className="flex items-center justify-between pt-1"><button@@ -410,6 +469,17 @@ export default function WorkspaceDashboard() {</button><div className="flex items-center gap-2">+ {viewingPost.status !== "completed" && (+ <button+ type="button"+ disabled={actionLoading}+ onClick={() => handlePublishNow(viewingPost.id)}+ className="px-3.5 py-1.5 rounded-lg text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 transition-colors flex items-center gap-1.5 cursor-pointer shadow-md shadow-blue-600/25 active:scale-95 disabled:opacity-50"+ >+ <FaBolt className="text-[10px]" />+ <span>{actionLoading ? "Publishing..." : "Publish Now"}</span>+ </button>+ )}{viewingPost.publishedUrl && (<ahref={viewingPost.publishedUrl}@@ -423,7 +493,7 @@ export default function WorkspaceDashboard() {<buttontype="button"onClick={() => handleEditPost(viewingPost)}- className="px-3.5 py-1.5 rounded-lg text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-500 transition-colors flex items-center gap-1.5 cursor-pointer shadow-md shadow-indigo-600/25 active:scale-95"+ className="px-3.5 py-1.5 rounded-lg text-xs font-semibold text-zinc-200 bg-zinc-800 hover:bg-zinc-700 transition-colors flex items-center gap-1.5 cursor-pointer active:scale-95"><FiEdit2 /> Edit</button>diff --git a/src/components/composer/PostComposerModal.jsx b/src/components/composer/PostComposerModal.jsxindex 6fc4e72..698bbc0 100644--- a/src/components/composer/PostComposerModal.jsx+++ b/src/components/composer/PostComposerModal.jsx@@ -10,7 +10,8 @@ import {FaChevronDown,FaChevronUp,FaCheck,- FaMagic+ FaMagic,+ FaPlus} from "react-icons/fa";import { FaXTwitter, FaThreads } from "react-icons/fa6";import { SiTiktok } from "react-icons/si";@@ -23,7 +24,10 @@ import {FiSend,FiLink,FiCheckCircle,- FiInfo+ FiInfo,+ FiPlus,+ FiExternalLink,+ FiRefreshCw} from "react-icons/fi";import LiveDevicePreview from "./LiveDevicePreview";import AiPostWriter from "./AiPostWriter";@@ -39,6 +43,28 @@ const PLATFORMS = [{ key: "pinterest", name: "Pinterest", Icon: FaPinterest, color: "text-rose-500", activeStyle: "bg-rose-500/15 border-rose-500/60 text-white shadow-sm shadow-rose-500/20", limit: 500 },];+const getPlatformKey = (acc) => {+ if (!acc) return "";+ const pName = (acc.platform_name || "").toLowerCase();+ if (pName === "x" || pName === "twitter") return "x_twitter";+ if (pName === "youtube") return "youtube";+ if (pName === "tiktok") return "tiktok";+ if (pName === "instagram") return "instagram";+ if (pName === "facebook") return "facebook";+ if (pName === "linkedin") return "linkedin";+ if (pName === "threads") return "threads";+ if (pName === "pinterest") return "pinterest";+ if (acc.platform === 1) return "youtube";+ if (acc.platform === 2) return "tiktok";+ if (acc.platform === 3) return "instagram";+ if (acc.platform === 4) return "x_twitter";+ if (acc.platform === 5) return "facebook";+ if (acc.platform === 6) return "linkedin";+ if (acc.platform === 7) return "threads";+ if (acc.platform === 8) return "pinterest";+ return pName;+};+const YOUTUBE_CATEGORIES = [{ label: "People & Blogs", value: "22" },{ label: "Film & Animation", value: "1" },@@ -63,6 +89,8 @@ export default function PostComposerModal({}) {const [selectedPlatforms, setSelectedPlatforms] = useState(["youtube"]);const [activePreviewPlatform, setActivePreviewPlatform] = useState("youtube");+ const [connectedAccounts, setConnectedAccounts] = useState([]);+ const [platformAccountMap, setPlatformAccountMap] = useState({});const [accountName, setAccountName] = useState("Creator Studio");const [accountId, setAccountId] = useState("101");const [title, setTitle] = useState("");@@ -71,6 +99,13 @@ export default function PostComposerModal({const [mediaUrl, setMediaUrl] = useState("");const [privacy, setPrivacy] = useState("public");+ // Add Channel Modal states+ const [addChannelModalOpen, setAddChannelModalOpen] = useState(false);+ const [connectingPlatform, setConnectingPlatform] = useState(null);+ const [accountNameInput, setAccountNameInput] = useState("");+ const [isConnecting, setIsConnecting] = useState(false);+ const [connectError, setConnectError] = useState("");+const togglePlatform = (key) => {setSelectedPlatforms((prev) => {if (prev.includes(key)) {@@ -88,7 +123,14 @@ export default function PostComposerModal({};const selectAllPlatforms = () => {- setSelectedPlatforms(PLATFORMS.map((p) => p.key));+ const connectedKeys = Array.from(new Set(connectedAccounts.map(getPlatformKey))).filter((k) =>+ PLATFORMS.some((p) => p.key === k)+ );+ if (connectedKeys.length > 0) {+ setSelectedPlatforms(connectedKeys);+ } else {+ setSelectedPlatforms(PLATFORMS.map((p) => p.key));+ }};const selectSinglePlatform = (key) => {@@ -162,10 +204,113 @@ export default function PostComposerModal({tomorrow.setDate(tomorrow.getDate() + 1);setScheduledDate(tomorrow.toISOString().split("T")[0]);setScheduledTime("12:00");- setIsScheduled(true);+ setIsScheduled(false); // Default to Post Now for new posts}}, [initialDate, initialPost, isOpen]);+ // Fetch user's real connected accounts from backend+ const fetchAccounts = () => {+ fetch("/api/social/accounts")+ .then((res) => res.json())+ .then((data) => {+ if (Array.isArray(data)) {+ setConnectedAccounts(data);+ const accMap = {};+ data.forEach((acc) => {+ const key = getPlatformKey(acc);+ if (!accMap[key]) {+ accMap[key] = acc.id;+ }+ });+ setPlatformAccountMap((prev) => ({ ...accMap, ...prev }));++ // Automatically select connected channels if current selection is invalid or new post+ if (!initialPost) {+ const connectedKeys = Array.from(new Set(data.map(getPlatformKey))).filter((k) =>+ PLATFORMS.some((p) => p.key === k)+ );+ if (connectedKeys.length > 0) {+ setSelectedPlatforms((prev) => {+ const valid = prev.filter((k) => connectedKeys.includes(k));+ return valid.length > 0 ? valid : [connectedKeys[0]];+ });+ setActivePreviewPlatform((prev) => (connectedKeys.includes(prev) ? prev : connectedKeys[0]));+ }+ }+ }+ })+ .catch((err) => console.error("Failed to fetch accounts in composer:", err));+ };++ useEffect(() => {+ if (isOpen) {+ fetchAccounts();+ }+ }, [isOpen, initialPost]);++ // Synchronize accountId and accountName for the currently active preview platform+ useEffect(() => {+ const platAccounts = connectedAccounts.filter((a) => {+ const normKey = getPlatformKey(a);+ return normKey === activePreviewPlatform || a.platform === activePreviewPlatform;+ });++ if (platAccounts.length > 0) {+ const selectedId = platformAccountMap[activePreviewPlatform] || platAccounts[0].id;+ const matched = platAccounts.find((a) => a.id === selectedId) || platAccounts[0];+ setAccountId(String(matched.id));+ setAccountName(matched.account_name);+ } else {+ setAccountId("101");+ setAccountName("Creator Studio");+ }+ }, [activePreviewPlatform, connectedAccounts, platformAccountMap]);++ // Connected vs Unconnected platforms+ const connectedPlatformKeys = new Set(connectedAccounts.map(getPlatformKey));+ const connectedPlatforms = PLATFORMS.filter((p) => connectedPlatformKeys.has(p.key));+ const unconnectedPlatforms = PLATFORMS.filter((p) => !connectedPlatformKeys.has(p.key));++ const handleInitiateConnect = (plat) => {+ setConnectingPlatform(plat);+ setAccountNameInput("");+ setConnectError("");+ };++ const handleConfirmConnect = async () => {+ if (!connectingPlatform) return;+ setIsConnecting(true);+ setConnectError("");++ const label = accountNameInput.trim();+ if (connectingPlatform.key === "youtube" && label) {+ localStorage.setItem("pending_youtube_label", label);+ }++ try {+ const res = await fetch("/api/social/connect", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ platform: connectingPlatform.key,+ accountName: label,+ redirectUrl: window.location.href,+ }),+ });++ const data = await res.json();+ if (data.url) {+ window.location.href = data.url;+ } else {+ setConnectError(data.error || "Failed to initiate connection. Please try again.");+ }+ } catch (err) {+ setConnectError(err.message || "Failed to connect to platform.");+ } finally {+ setIsConnecting(false);+ }+ };+const handleApplyAiContent = ({ title: newTitle, description: newDescription, tags: newTags }) => {if (newTitle) setTitle(newTitle);if (newDescription) setDescription(newDescription);@@ -217,7 +362,7 @@ export default function PostComposerModal({}};- const handleSubmit = async (statusOverride = null) => {+ const handleSubmit = async (statusOverride = null, forceImmediate = false) => {if (!mediaUrl) {setErrorMsg("Please upload or provide a media URL for your post.");return;@@ -228,7 +373,8 @@ export default function PostComposerModal({try {let combinedScheduledAt = null;- if (isScheduled && scheduledDate && scheduledTime) {+ const willSchedule = forceImmediate ? false : (statusOverride === "draft" ? false : isScheduled);+ if (willSchedule && scheduledDate && scheduledTime) {combinedScheduledAt = new Date(`${scheduledDate}T${scheduledTime}:00`).toISOString();}@@ -237,6 +383,7 @@ export default function PostComposerModal({platform: activePreviewPlatform,accountId: parseInt(accountId) || 101,accountName,+ platformAccountMap,title,description,tags,@@ -343,8 +490,8 @@ export default function PostComposerModal({</div>)}- {/* 1. Channel Selector with Multi-Select */}- <div className="space-y-2">+ {/* 1. Channel Selector with Multi-Select (Connected Channels Only) */}+ <div className="space-y-2.5"><div className="flex items-center justify-between"><div className="flex items-center gap-2"><label className="text-xs font-bold text-zinc-300 tracking-wider uppercase block">@@ -354,64 +501,161 @@ export default function PostComposerModal({{selectedPlatforms.length} {selectedPlatforms.length === 1 ? "channel" : "channels"} selected</span></div>- <div className="flex items-center gap-1.5 text-[11px]">+ {connectedPlatforms.length > 1 && (+ <div className="flex items-center gap-1.5 text-[11px]">+ <button+ type="button"+ onClick={selectAllPlatforms}+ className="text-blue-400 hover:text-blue-300 font-medium transition-colors cursor-pointer"+ >+ Select All+ </button>+ <span className="text-zinc-600">|</span>+ <button+ type="button"+ onClick={() => selectSinglePlatform(activePreviewPlatform)}+ className="text-zinc-400 hover:text-zinc-200 font-medium transition-colors cursor-pointer"+ >+ Only Current+ </button>+ </div>+ )}+ </div>++ {connectedPlatforms.length === 0 ? (+ /* Empty state when no channels are connected */+ <div className="p-4 rounded-lg border border-dashed border-zinc-800 bg-zinc-900/30 flex flex-col sm:flex-row items-center justify-between gap-3 text-center sm:text-left">+ <div>+ <p className="text-xs font-semibold text-zinc-200">No social channels connected yet</p>+ <p className="text-[11px] text-zinc-500">Connect your accounts to start scheduling and publishing posts.</p>+ </div><buttontype="button"- onClick={selectAllPlatforms}- className="text-blue-400 hover:text-blue-300 font-medium transition-colors cursor-pointer"+ onClick={() => setAddChannelModalOpen(true)}+ className="px-3.5 py-1.5 rounded-md bg-blue-600 hover:bg-blue-500 text-white text-xs font-bold flex items-center gap-1.5 transition-all shadow-md shadow-blue-600/30 shrink-0 cursor-pointer">- Select All+ <FiPlus className="text-xs font-bold" />+ <span>Add Channel</span></button>- <span className="text-zinc-600">|</span>+ </div>+ ) : (+ /* Connected channels grid with + Add Channel button */+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">+ {connectedPlatforms.map((plat) => {+ const Icon = plat.Icon;+ const isSelected = selectedPlatforms.includes(plat.key);+ const isCurrent = activePreviewPlatform === plat.key;++ // Match connected account details for label+ const matchingAccounts = connectedAccounts.filter(a => getPlatformKey(a) === plat.key);+ const accountLabel = matchingAccounts.length > 0 ? matchingAccounts[0].account_name : plat.name;++ return (+ <div+ key={plat.key}+ onClick={() => togglePlatform(plat.key)}+ className={`relative p-2.5 rounded-md border flex items-center justify-between gap-2 transition-all cursor-pointer select-none ${+ isSelected+ ? `${plat.activeStyle} ${isCurrent ? "ring-1 ring-white/30" : ""}`+ : "border-zinc-800/80 bg-zinc-900/40 text-zinc-500 hover:border-zinc-700 hover:text-zinc-300"+ }`}+ >+ <div className="flex items-center gap-2 min-w-0">+ <div className="relative shrink-0">+ <div className={`w-7 h-7 rounded-full flex items-center justify-center ${isSelected ? "bg-white/10" : "bg-zinc-800/80"}`}>+ <Icon className={`text-xs ${isSelected ? "text-current" : plat.color}`} />+ </div>+ <span className="w-2 h-2 rounded-full bg-emerald-400 absolute -bottom-0.5 -right-0.5 ring-2 ring-zinc-950" />+ </div>+ <div className="min-w-0">+ <div className="text-[11px] truncate font-bold text-zinc-100">+ {plat.name}+ </div>+ <div className="text-[10px] truncate text-zinc-400">+ {accountLabel}+ </div>+ </div>+ </div>+ <div className="flex items-center shrink-0">+ {isSelected ? (+ <span className="w-4 h-4 rounded-full bg-white/20 text-white flex items-center justify-center text-[10px] font-bold">+ ✓+ </span>+ ) : (+ <span className="w-4 h-4 rounded-full border border-zinc-700 flex items-center justify-center" />+ )}+ </div>+ </div>+ );+ })}++ {/* + Add Channel Button (Reference App Style) */}<buttontype="button"- onClick={() => selectSinglePlatform(activePreviewPlatform)}- className="text-zinc-400 hover:text-zinc-200 font-medium transition-colors cursor-pointer"+ onClick={() => setAddChannelModalOpen(true)}+ className="p-2.5 rounded-md border border-dashed border-zinc-800 hover:border-zinc-700 bg-zinc-900/30 hover:bg-zinc-900/60 text-zinc-400 hover:text-zinc-200 flex items-center justify-center gap-2 transition-all cursor-pointer group min-h-[50px]">- Only Current+ <div className="w-6 h-6 rounded-full bg-zinc-800 group-hover:bg-zinc-700 flex items-center justify-center text-zinc-300 transition-colors">+ <FiPlus className="text-xs font-bold" />+ </div>+ <span className="text-[11px] font-semibold tracking-wide">+ Add Channel+ </span></button></div>- </div>+ )}- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- {PLATFORMS.map((plat) => {- const Icon = plat.Icon;- const isSelected = selectedPlatforms.includes(plat.key);- const isCurrent = activePreviewPlatform === plat.key;- return (- <div- key={plat.key}- onClick={() => togglePlatform(plat.key)}- className={`relative p-2 rounded-md border flex items-center justify-between gap-1.5 transition-all cursor-pointer select-none ${- isSelected- ? `${plat.activeStyle} ${isCurrent ? "ring-1 ring-white/30" : ""}`- : "border-zinc-800/80 bg-zinc-900/40 text-zinc-500 hover:border-zinc-700 hover:text-zinc-300"- }`}- >- <div className="flex items-center gap-2 min-w-0">- <Icon className={`text-xs shrink-0 ${isSelected ? "text-current" : plat.color}`} />- <span className="text-[11px] truncate font-semibold">- {plat.name}- </span>- </div>- <div className="flex items-center shrink-0">- {isSelected ? (- <span className="w-3.5 h-3.5 rounded-full bg-white/20 text-white flex items-center justify-center text-[9px] font-bold">- ✓- </span>- ) : (- <span className="w-3.5 h-3.5 rounded-full border border-zinc-700 flex items-center justify-center" />- )}- </div>- </div>- );- })}- </div><p className="text-[10px] text-zinc-500">- Click any channel to toggle. Multiple selected channels will be published in a single click.+ Click any connected channel to toggle. Multiple selected channels will be published in a single click.</p></div>+ {/* Connected Account Display & Selector */}+ {(() => {+ const activePlatAccounts = connectedAccounts.filter((a) => {+ const pName = (a.platform_name || "").toLowerCase();+ const normKey = pName === "x" || pName === "twitter" ? "x_twitter" : pName;+ return normKey === activePreviewPlatform || a.platform === activePreviewPlatform;+ });++ return (+ <div className="p-2.5 rounded-md bg-zinc-900/50 border border-zinc-800 flex items-center justify-between gap-3 text-xs">+ <div className="flex items-center gap-2 min-w-0">+ <span className="text-zinc-400 text-[11px] font-medium shrink-0">Posting to {currentPlatformInfo.name} as:</span>+ {activePlatAccounts.length > 0 ? (+ <div className="flex items-center gap-1.5 px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[11px] font-semibold truncate">+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 shrink-0 animate-pulse" />+ <span className="truncate">{accountName}</span>+ </div>+ ) : (+ <span className="text-amber-400/90 text-[11px] font-medium flex items-center gap-1 truncate">+ ⚠️ No account connected in Integrations+ </span>+ )}+ </div>++ {activePlatAccounts.length > 1 && (+ <select+ value={accountId}+ onChange={(e) => {+ const sel = activePlatAccounts.find((a) => String(a.id) === e.target.value);+ if (sel) {+ setAccountId(String(sel.id));+ setAccountName(sel.account_name);+ setPlatformAccountMap((prev) => ({ ...prev, [activePreviewPlatform]: sel.id }));+ }+ }}+ className="bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-[11px] text-zinc-200 outline-none shrink-0"+ >+ {activePlatAccounts.map((a) => (+ <option key={a.id} value={a.id}>{a.account_name}</option>+ ))}+ </select>+ )}+ </div>+ );+ })()}+{/* 2. Post Title */}<div className="space-y-1.5"><label className="text-xs font-bold text-zinc-300 tracking-wider uppercase block">@@ -847,39 +1091,297 @@ export default function PostComposerModal({Save as Draft</button>- <button- type="button"- disabled={submitting}- onClick={() => handleSubmit()}- className="px-4 py-1.5 rounded-md text-xs font-bold text-white bg-blue-600 hover:bg-blue-500 transition-all cursor-pointer flex items-center gap-2 shadow-md shadow-blue-600/30 active:scale-95 disabled:opacity-50"- >- {submitting ? (- <>- <div className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />- <span>- {isScheduled- ? `Scheduling to ${selectedPlatforms.length} ${selectedPlatforms.length === 1 ? "channel" : "channels"}...`- : `Publishing to ${selectedPlatforms.length} ${selectedPlatforms.length === 1 ? "channel" : "channels"}...`}- </span>- </>- ) : (- <>- <FiSend className="text-xs" />- <span>- {isScheduled- ? selectedPlatforms.length > 1- ? `Schedule to ${selectedPlatforms.length} Channels`- : "Schedule Post"- : selectedPlatforms.length > 1+ {isScheduled ? (+ <>+ <button+ type="button"+ disabled={submitting}+ onClick={() => handleSubmit(null, true)}+ className="px-3.5 py-1.5 rounded-md text-xs font-bold text-zinc-200 bg-zinc-900 hover:bg-zinc-800 border border-zinc-700 transition-colors cursor-pointer flex items-center gap-1.5"+ >+ <FiSend className="text-xs text-blue-400" />+ <span>Publish Now Instead</span>+ </button>+ <button+ type="button"+ disabled={submitting}+ onClick={() => handleSubmit()}+ className="px-4 py-1.5 rounded-md text-xs font-bold text-white bg-blue-600 hover:bg-blue-500 transition-all cursor-pointer flex items-center gap-2 shadow-md shadow-blue-600/30 active:scale-95 disabled:opacity-50"+ >+ {submitting ? (+ <>+ <div className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />+ <span>Scheduling...</span>+ </>+ ) : (+ <>+ <FiCalendar className="text-xs" />+ <span>+ {selectedPlatforms.length > 1+ ? `Schedule to ${selectedPlatforms.length} Channels`+ : "Schedule Post"}+ </span>+ </>+ )}+ </button>+ </>+ ) : (+ <button+ type="button"+ disabled={submitting}+ onClick={() => handleSubmit()}+ className="px-4 py-1.5 rounded-md text-xs font-bold text-white bg-blue-600 hover:bg-blue-500 transition-all cursor-pointer flex items-center gap-2 shadow-md shadow-blue-600/30 active:scale-95 disabled:opacity-50"+ >+ {submitting ? (+ <>+ <div className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />+ <span>+ Publishing to {selectedPlatforms.length} {selectedPlatforms.length === 1 ? "channel" : "channels"}...+ </span>+ </>+ ) : (+ <>+ <FiSend className="text-xs" />+ <span>+ {selectedPlatforms.length > 1? `Publish to ${selectedPlatforms.length} Channels Now`: "Publish Now"}+ </span>+ </>+ )}+ </button>+ )}+ </div>+ </div>+ </div>++ {/* Add Channel Modal (Reference App UX & Styling) */}+ {addChannelModalOpen && (+ <div+ className="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-in fade-in duration-200"+ onClick={(e) => {+ e.stopPropagation();+ setAddChannelModalOpen(false);+ setConnectingPlatform(null);+ setConnectError("");+ }}+ >+ <div+ className="relative w-full max-w-xl bg-zinc-950 border border-zinc-800 rounded-xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]"+ onClick={(e) => e.stopPropagation()}+ >+ {/* Header */}+ <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-zinc-900/60">+ <div>+ <h3 className="text-sm font-bold text-white tracking-wide uppercase flex items-center gap-2">+ <span>ADD SOCIAL CHANNEL</span>+ <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-blue-500/15 text-blue-400 border border-blue-500/30">+ OAuth 2.0</span>+ </h3>+ <p className="text-xs text-zinc-400 mt-0.5">+ Connect and authorize platforms to schedule and publish posts+ </p>+ </div>+ <button+ type="button"+ onClick={() => {+ setAddChannelModalOpen(false);+ setConnectingPlatform(null);+ setConnectError("");+ }}+ className="w-7 h-7 rounded-md hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 flex items-center justify-center transition-colors cursor-pointer"+ >+ <FiX className="text-sm" />+ </button>+ </div>++ {/* Body */}+ <div className="p-5 overflow-y-auto space-y-5">+ {connectError && (+ <div className="p-3 bg-red-500/10 border border-red-500/25 rounded-lg text-xs text-red-400 flex items-center gap-2">+ <FiInfo className="text-sm shrink-0" />+ <span>{connectError}</span>+ </div>+ )}++ {connectingPlatform ? (+ /* Connecting Platform Dialog */+ <div className="p-4 rounded-lg bg-zinc-900/70 border border-zinc-800 space-y-4">+ <div className="flex items-center gap-3">+ <div className="w-10 h-10 rounded-lg bg-zinc-800 flex items-center justify-center shadow-inner">+ {(() => {+ const Icon = connectingPlatform.Icon;+ return <Icon className={`text-xl ${connectingPlatform.color}`} />;+ })()}+ </div>+ <div>+ <h4 className="text-sm font-bold text-white">+ Connect {connectingPlatform.name}+ </h4>+ <p className="text-[11px] text-zinc-400">+ You will be redirected to authorize access.+ </p>+ </div>+ </div>++ <div className="space-y-1.5">+ <label className="text-[11px] font-semibold text-zinc-300 uppercase tracking-wider block">+ Account Label / Name (Optional)+ </label>+ <input+ type="text"+ value={accountNameInput}+ onChange={(e) => setAccountNameInput(e.target.value)}+ placeholder={`e.g. My ${connectingPlatform.name} Account`}+ className="w-full bg-zinc-950 border border-zinc-800 rounded-md px-3 py-2 text-xs text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-zinc-600"+ />+ <p className="text-[10px] text-zinc-500">+ Helps identify this account in your workspace dashboard.+ </p>+ </div>++ <div className="flex items-center justify-end gap-2 pt-2 border-t border-zinc-800/80">+ <button+ type="button"+ onClick={() => setConnectingPlatform(null)}+ disabled={isConnecting}+ className="px-3.5 py-1.5 rounded-md border border-zinc-800 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 text-xs font-semibold transition-colors cursor-pointer"+ >+ Back+ </button>+ <button+ type="button"+ onClick={handleConfirmConnect}+ disabled={isConnecting}+ className="px-4 py-1.5 rounded-md bg-blue-600 hover:bg-blue-500 text-white text-xs font-bold transition-all flex items-center gap-1.5 shadow-md shadow-blue-600/30 cursor-pointer disabled:opacity-50"+ >+ {isConnecting ? (+ <>+ <span className="w-3 h-3 border-2 border-white border-t-transparent rounded-full animate-spin" />+ <span>Connecting...</span>+ </>+ ) : (+ <>+ <span>Authorize & Connect</span>+ <FiExternalLink className="text-xs" />+ </>+ )}+ </button>+ </div>+ </div>+ ) : (+ <>+ {/* Unconnected Platforms Grid */}+ <div className="space-y-2.5">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-bold text-zinc-400 uppercase tracking-wider">+ Available Channels to Connect+ </span>+ <span className="text-[10px] text-zinc-500">+ {unconnectedPlatforms.length} available+ </span>+ </div>++ {unconnectedPlatforms.length === 0 ? (+ <div className="p-4 rounded-lg bg-zinc-900/40 border border-zinc-800 text-center text-xs text-zinc-400">+ All supported channels are currently connected!+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5">+ {unconnectedPlatforms.map((plat) => {+ const Icon = plat.Icon;+ return (+ <div+ key={plat.key}+ onClick={() => handleInitiateConnect(plat)}+ className="p-3.5 rounded-lg border border-zinc-800/90 bg-zinc-900/50 hover:bg-zinc-900 hover:border-zinc-700 transition-all cursor-pointer flex flex-col items-center justify-center text-center gap-2.5 group shadow-sm"+ >+ <div className="w-11 h-11 rounded-full bg-zinc-800/80 group-hover:bg-zinc-800 flex items-center justify-center transition-colors">+ <Icon className={`text-xl ${plat.color} group-hover:scale-110 transition-transform`} />+ </div>+ <div>+ <div className="text-xs font-bold text-zinc-200 group-hover:text-white">+ {plat.name}+ </div>+ <span className="text-[10px] text-blue-400 group-hover:text-blue-300 font-medium inline-flex items-center gap-0.5 mt-0.5">+ + Connect+ </span>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Already Connected Platforms */}+ {connectedPlatforms.length > 0 && (+ <div className="space-y-2.5 pt-3 border-t border-zinc-800/80">+ <span className="text-[11px] font-bold text-zinc-400 uppercase tracking-wider block">+ Already Connected Channels+ </span>+ <div className="space-y-2">+ {connectedAccounts.map((acc) => {+ const platKey = getPlatformKey(acc);+ const platInfo = PLATFORMS.find((p) => p.key === platKey) || { name: acc.platform_name || platKey, Icon: FaCheck, color: "text-zinc-400" };+ const Icon = platInfo.Icon;++ return (+ <div+ key={acc.id}+ className="p-2.5 rounded-lg bg-zinc-900/40 border border-zinc-800/80 flex items-center justify-between gap-3 text-xs"+ >+ <div className="flex items-center gap-2.5 min-w-0">+ <div className="w-7 h-7 rounded-full bg-zinc-800 flex items-center justify-center shrink-0">+ <Icon className={`text-xs ${platInfo.color}`} />+ </div>+ <div className="min-w-0">+ <span className="font-semibold text-zinc-200 block truncate">+ {acc.account_name || `${platInfo.name} Account`}+ </span>+ <span className="text-[10px] text-zinc-500 block">+ {platInfo.name}+ </span>+ </div>+ </div>++ <div className="flex items-center gap-2 shrink-0">+ <span className="px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">+ Connected+ </span>+ <button+ type="button"+ onClick={() => handleInitiateConnect(platInfo)}+ className="text-[10px] text-zinc-400 hover:text-zinc-200 underline cursor-pointer"+ >+ + Add another+ </button>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ )}</>)}- </button>+ </div>++ {/* Footer */}+ <div className="px-5 py-3 border-t border-zinc-800 bg-zinc-900/40 flex items-center justify-between text-xs text-zinc-500">+ <span>Need to manage existing accounts?</span>+ <a+ href="/integrations"+ className="text-blue-400 hover:text-blue-300 font-medium inline-flex items-center gap-1"+ >+ <span>Open Integrations Manager</span>+ <FiExternalLink className="text-[10px]" />+ </a>+ </div></div></div>- </div>+ )}</div>);}