Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(accounts): split AccountManager into dialog, cards and hooks

spacesdrive3dc72852c23e
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 3d6eebb..fd92fd0 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -58,7 +58,15 @@ frontend/src/
│ │ ├── CategoryYouTubeSection.jsx, CategoryRedditSection.jsx, NumberCell.jsx, OpenLink.jsx
│ │ └── trackedCategoryStats.js <- Pure per-category totals and labels (trackedCategoryStats.test.js)
│ ├── accounts/
-│ │ └── AccountManager.jsx <- Add/remove connected accounts
+│ │ ├── AccountManager.jsx <- Page: connected accounts by platform, refresh and remove
+│ │ ├── AccountSection.jsx, AccountCard.jsx, AccountsEmptyState.jsx
+│ │ ├── AddAccountDialog.jsx <- Platform picker, per-platform fields and footer actions
+│ │ ├── YouTubeAccountFields.jsx, RedditAccountFields.jsx, AddAccountFooter.jsx
+│ │ ├── useAddAccount.js <- Add dialog state; Back keeps typed fields, Cancel clears them
+│ │ ├── useAccountRefresh.js, useAccountDelete.js
+│ │ ├── useInstagramOAuthReturn.js <- Reads ?ig_connected, ?ig_error and ?add once, then clears them
+│ │ ├── platformChoices.js <- Platform choice titles, descriptions and icons
+│ │ └── accountManagerData.js <- Pure OAuth return, error text, card metrics (accountManagerData.test.js)
│ ├── publishing/
│ │ ├── UploadContent.jsx <- Page: tabs, Cloudinary alert, scheduled posts (default export)
│ │ ├── SinglePostTab.jsx <- Single post form or its progress view
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 9f8dd26..a8afbdc 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -107,7 +107,7 @@ frontend/src/
publishing/
UploadContent.jsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
accounts/
- AccountManager.jsx Add/remove/refresh accounts
+ AccountManager.jsx Add/remove/refresh accounts (page; dialog, cards, hooks and helpers beside it)
settings/
Settings.jsx API keys status + GitHub config
```
diff --git a/frontend/src/features/accounts/AccountCard.jsx b/frontend/src/features/accounts/AccountCard.jsx
new file mode 100644
index 0000000..fe810fd
--- /dev/null
+++ b/frontend/src/features/accounts/AccountCard.jsx
@@ -0,0 +1,65 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { ArrowUpRight, Lock, RefreshCw, Trash2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { AccountAvatar } from '@/components/platform';
+import { accountName, accountPath } from '@/lib/accounts';
+import { cn } from '@/lib/utils';
+import { fmtNum, timeAgo } from '../../utils/formatters';
+import { accountCardHandle, accountMetrics } from './accountManagerData';
+
+function CookieStatus({ hasCookie }) {
+ if (hasCookie) {
+ return <span className="flex items-center gap-1 text-success"><Lock className="size-3" />Session cookie stored</span>;
+ }
+ return <span className="flex items-center gap-1 text-danger"><Lock className="size-3" />Error: no session cookie. Remove and add the account again.</span>;
+}
+
+export default function AccountCard({ acct, platform, refreshing, onRefresh, onDelete }) {
+ const metrics = accountMetrics(platform, acct);
+ return (
+ <article className="flex flex-col gap-4 rounded-card border border-line bg-surface-raised p-4">
+ <div className="flex items-center gap-3">
+ <AccountAvatar account={acct} size="lg" showPlatform />
+ <div className="min-w-0 flex-1">
+ <Link to={accountPath(acct)} className="block truncate text-sm font-semibold text-ink hover:underline">{accountName(acct)}</Link>
+ <p className="truncate text-caption text-ink-faint">{accountCardHandle(acct, platform)}</p>
+ </div>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" render={<Link to={accountPath(acct)} aria-label={`Open analytics for ${accountName(acct)}`} />} />}>
+ <ArrowUpRight />
+ </TooltipTrigger>
+ <TooltipContent>Open analytics</TooltipContent>
+ </Tooltip>
+ </div>
+
+ <dl className="grid grid-cols-3 divide-x divide-divider rounded-control bg-surface-sunken/60 py-2.5">
+ {metrics.map(([label, value]) => (
+ <div key={label} className="flex flex-col items-center gap-0.5 px-2 text-center">
+ <dt className="text-caption text-ink-faint">{label}</dt>
+ <dd className="font-heading text-base font-semibold text-ink tabular-nums">{fmtNum(value)}</dd>
+ </div>
+ ))}
+ </dl>
+
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-ink-faint">
+ {platform === 'reddit' && <CookieStatus hasCookie={acct.hasCookie} />}
+ {acct.lastUpdated && <span>Updated {timeAgo(acct.lastUpdated).toLowerCase()}</span>}
+ </div>
+
+ <div className="mt-auto flex gap-2">
+ <Button variant="outline" size="sm" className="flex-1" onClick={onRefresh} disabled={refreshing}>
+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
+ {refreshing ? 'Refreshing' : 'Refresh'}
+ </Button>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label={`Remove ${accountName(acct)}`} className="text-ink-muted hover:bg-danger-soft hover:text-danger" />}>
+ <Trash2 />
+ </TooltipTrigger>
+ <TooltipContent>Remove account</TooltipContent>
+ </Tooltip>
+ </div>
+ </article>
+ );
+}
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index 790599d..415f3c8 100644
--- a/frontend/src/features/accounts/AccountManager.jsx
+++ b/frontend/src/features/accounts/AccountManager.jsx
@@ -1,200 +1,30 @@
-import React, { useEffect, useState } from 'react';
-import { Link, useSearchParams } from 'react-router-dom';
-import {
- Plus, Trash2, RefreshCw, Search, Users, CheckCircle2, Link2, Info, ExternalLink, Lock, ArrowLeft, ArrowUpRight,
-} from 'lucide-react';
+import React from 'react';
+import { Plus, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { Badge } from '@/components/ui/badge';
-import { Alert, AlertDescription } from '@/components/ui/alert';
-import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { Spinner } from '@/components/ui/spinner';
import PageHeader from '@/components/PageHeader';
-import SurfaceBox from '@/components/SurfaceBox';
-import SectionHeader from '@/components/SectionHeader';
-import ChoiceCard from '@/components/ChoiceCard';
-import InstagramTesterNotice from '@/components/InstagramTesterNotice';
-import { ADMIN_EMAIL } from '@/lib/contact';
import ConfirmDialog from '@/components/ConfirmDialog';
-import { FieldRow } from '@/components/DetailPanel';
-import { EmptyState } from '@/components/StateViews';
-import { AccountAvatar, PlatformIcon } from '@/components/platform';
-import { YouTubeIcon, InstagramIcon, RedditIcon } from '@/components/brand/platform-icons';
-import { PLATFORM_META, accountHandle, accountName, accountPath, groupByPlatform, platformSummary } from '@/lib/accounts';
-import { useAppContext } from '../../context/AppContext';
-import { api } from '../../services/api';
-import { fmtNum, timeAgo } from '../../utils/formatters';
+import { accountName, groupByPlatform, platformSummary } from '@/lib/accounts';
import { cn } from '@/lib/utils';
-
-const PLATFORM_CHOICES = [
- { value: 'youtube', title: 'YouTube channel', description: 'Paste a channel link, @handle or channel ID.', icon: <YouTubeIcon /> },
- { value: 'instagram', title: 'Instagram account', description: 'Sign in with Instagram. Business or Creator accounts only.', icon: <InstagramIcon /> },
- { value: 'reddit', title: 'Reddit account', description: 'Add a username and a session cookie from your browser.', icon: <RedditIcon /> },
-];
-
-const TESTER_HINT = `If your account is not an Instagram tester yet, email ${ADMIN_EMAIL} to be added, then accept the invite in Instagram.`;
-
-const IG_ERRORS = {
- already_added: 'This Instagram account is already connected.',
- cancelled: 'Instagram sign-in was cancelled. Try again when you are ready.',
- access_denied: `Instagram did not grant access. Approve every requested permission and try again. ${TESTER_HINT}`,
- invalid_state: 'The Instagram sign-in link expired. Start the connection again.',
-};
-
-const METRICS = {
- youtube: acct => [['Subscribers', acct.subscriberCount], ['Views', acct.viewCount], ['Videos', acct.videoCount]],
- instagram: acct => [['Followers', acct.followersCount], ['Following', acct.followsCount], ['Posts', acct.mediaCount]],
- reddit: acct => [['Karma', acct.totalKarma], ['Post karma', acct.postKarma], ['Comment karma', acct.commentKarma]],
-};
+import { useAppContext } from '../../context/AppContext';
+import { visibleSections } from './accountManagerData';
+import { useAddAccount } from './useAddAccount';
+import { useAccountRefresh } from './useAccountRefresh';
+import { useAccountDelete } from './useAccountDelete';
+import { useInstagramOAuthReturn } from './useInstagramOAuthReturn';
+import AccountsEmptyState from './AccountsEmptyState';
+import AccountSection from './AccountSection';
+import AddAccountDialog from './AddAccountDialog';
export default function AccountManager() {
const { accounts, showToast, loadAccounts } = useAppContext();
- const [searchParams, setSearchParams] = useSearchParams();
-
- const [dialogOpen, setDialogOpen] = useState(false);
- const [platform, setPlatform] = useState(null);
- const [input, setInput] = useState('');
- const [resolving, setResolving] = useState(false);
- const [resolved, setResolved] = useState(null);
- const [adding, setAdding] = useState(false);
- const [connecting, setConnecting] = useState(false);
- const [redditUsername, setRedditUsername] = useState('');
- const [redditCookie, setRedditCookie] = useState('');
- const [addingReddit, setAddingReddit] = useState(false);
- const [refreshingId, setRefreshingId] = useState(null);
- const [pendingDelete, setPendingDelete] = useState(null);
- const [deleting, setDeleting] = useState(false);
-
- // Instagram OAuth returns here with ?ig_connected=true or ?ig_error=...; ?add=1 opens the add flow
- useEffect(() => {
- const connected = searchParams.get('ig_connected');
- const igError = searchParams.get('ig_error');
- const add = searchParams.get('add');
- if (!connected && !igError && !add) return;
-
- if (connected === 'true') {
- showToast('Instagram account connected');
- loadAccounts();
- } else if (igError) {
- showToast(IG_ERRORS[igError] || `Instagram connection failed: ${igError}. ${TESTER_HINT}`, 'error');
- }
- if (add) setDialogOpen(true);
- setSearchParams({}, { replace: true });
- }, [searchParams, setSearchParams, showToast, loadAccounts]);
-
- const closeDialog = () => {
- setDialogOpen(false);
- setPlatform(null);
- setResolved(null);
- setInput('');
- setRedditUsername('');
- setRedditCookie('');
- };
-
- const handleResolve = async () => {
- if (!input.trim()) return;
- setResolving(true);
- setResolved(null);
- try {
- const res = await api.resolveChannel(input.trim());
- setResolved(res.data || res);
- } catch (err) {
- showToast(`Couldn't find that channel. ${err.message}`, 'error');
- } finally {
- setResolving(false);
- }
- };
-
- const handleAdd = async () => {
- if (!input.trim()) return;
- setAdding(true);
- try {
- await api.addAccount(input.trim());
- showToast('YouTube channel added');
- closeDialog();
- loadAccounts();
- } catch (err) {
- showToast(`Couldn't add the channel. ${err.message}`, 'error');
- } finally {
- setAdding(false);
- }
- };
-
- const handleConnectInstagram = async () => {
- setConnecting(true);
- try {
- const { url } = await api.getInstagramAuthUrl();
- // Same tab: Instagram redirects back to /accounts?ig_connected=true
- window.location.href = url;
- } catch (err) {
- showToast(`Couldn't start Instagram sign-in. ${err.message}`, 'error');
- setConnecting(false);
- }
- };
-
- const handleAddReddit = async () => {
- if (!redditUsername.trim() || !redditCookie.trim()) return;
- setAddingReddit(true);
- try {
- await api.addRedditAccount(redditUsername.trim(), redditCookie.trim());
- showToast('Reddit account added');
- closeDialog();
- loadAccounts();
- } catch (err) {
- showToast(`Couldn't add the Reddit account. ${err.message}`, 'error');
- } finally {
- setAddingReddit(false);
- }
- };
-
- const handleDelete = async () => {
- if (!pendingDelete) return;
- setDeleting(true);
- try {
- await api.deleteAccount(pendingDelete.id);
- showToast(`${accountName(pendingDelete)} removed`);
- setPendingDelete(null);
- loadAccounts();
- } catch (err) {
- showToast(`Couldn't remove the account. ${err.message}`, 'error');
- } finally {
- setDeleting(false);
- }
- };
-
- const handleRefreshOne = async id => {
- setRefreshingId(id);
- try {
- await api.refreshAccount(id);
- showToast('Account refreshed');
- loadAccounts();
- } catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
- } finally {
- setRefreshingId(null);
- }
- };
-
- const handleRefreshAll = async () => {
- setRefreshingId('all');
- try {
- await api.refreshAll();
- showToast('All accounts refreshed');
- loadAccounts();
- } catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
- } finally {
- setRefreshingId(null);
- }
- };
+ const addFlow = useAddAccount({ showToast, loadAccounts });
+ const { refreshingId, refreshOne, refreshAll } = useAccountRefresh({ showToast, loadAccounts });
+ const { pendingDelete, setPendingDelete, deleting, handleDelete } = useAccountDelete({ showToast, loadAccounts });
+ useInstagramOAuthReturn({ showToast, loadAccounts, setDialogOpen: addFlow.setDialogOpen });
const groups = groupByPlatform(accounts);
- const sections = [
- { key: 'youtube', title: 'YouTube channels' },
- { key: 'instagram', title: 'Instagram accounts' },
- { key: 'reddit', title: 'Reddit accounts' },
- ].filter(s => groups[s.key].length > 0);
+ const sections = visibleSections(groups);
+ const refreshingAll = refreshingId === 'all';
return (
<div className="flex flex-col gap-8">
@@ -204,12 +34,12 @@ export default function AccountManager() {
actions={
<>
{accounts.length > 0 && (
- <Button variant="outline" onClick={handleRefreshAll} disabled={refreshingId === 'all'}>
- <RefreshCw data-icon="inline-start" className={cn(refreshingId === 'all' && 'animate-spin')} />
- {refreshingId === 'all' ? 'Refreshing' : 'Refresh all'}
+ <Button variant="outline" onClick={refreshAll} disabled={refreshingAll}>
+ <RefreshCw data-icon="inline-start" className={cn(refreshingAll && 'animate-spin')} />
+ {refreshingAll ? 'Refreshing' : 'Refresh all'}
</Button>
)}
- <Button onClick={() => setDialogOpen(true)}>
+ <Button onClick={() => addFlow.setDialogOpen(true)}>
<Plus data-icon="inline-start" />
Add account
</Button>
@@ -218,191 +48,21 @@ export default function AccountManager() {
/>
{accounts.length === 0 ? (
- <div className="flex flex-col gap-4">
- <SectionHeader title="Choose what to connect" />
- <div role="list" className="grid grid-cols-1 gap-x-3 gap-y-5 md:grid-cols-3">
- {PLATFORM_CHOICES.map(choice => (
- <div role="listitem" key={choice.value}>
- <ChoiceCard
- icon={choice.icon}
- title={choice.title}
- description={choice.description}
- onSelect={() => { setPlatform(choice.value); setDialogOpen(true); }}
- className="h-full"
- />
- </div>
- ))}
- </div>
- </div>
+ <AccountsEmptyState onChoose={addFlow.openWithPlatform} />
) : (
sections.map(section => (
- <section key={section.key} className="flex flex-col gap-3">
- <SectionHeader
- title={
- <span className="flex items-center gap-2">
- <PlatformIcon platform={section.key} className="size-4 text-ink-muted" />
- {section.title}
- <Badge variant="secondary">{groups[section.key].length}</Badge>
- </span>
- }
- />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
- {groups[section.key].map(acct => (
- <AccountCard
- key={acct.id}
- acct={acct}
- platform={section.key}
- refreshing={refreshingId === acct.id}
- onRefresh={() => handleRefreshOne(acct.id)}
- onDelete={() => setPendingDelete(acct)}
- />
- ))}
- </div>
- </section>
+ <AccountSection
+ key={section.key}
+ section={section}
+ accounts={groups[section.key]}
+ refreshingId={refreshingId}
+ onRefresh={refreshOne}
+ onDelete={setPendingDelete}
+ />
))
)}
- <Dialog open={dialogOpen} onOpenChange={open => { if (!open) closeDialog(); }}>
- <DialogContent className="sm:max-w-xl">
- <DialogHeader>
- <DialogTitle>{platform ? PLATFORM_CHOICES.find(c => c.value === platform).title : 'Add an account'}</DialogTitle>
- <DialogDescription>
- {platform ? 'Fill in the details, review, then add.' : 'Choose the platform you want to track.'}
- </DialogDescription>
- </DialogHeader>
-
- {!platform && (
- <div role="radiogroup" aria-label="Platform" className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- {PLATFORM_CHOICES.map(choice => (
- <ChoiceCard
- key={choice.value}
- icon={choice.icon}
- title={PLATFORM_META[choice.value].label}
- description={choice.description}
- selected={false}
- onSelect={() => setPlatform(choice.value)}
- />
- ))}
- </div>
- )}
-
- {platform === 'youtube' && (
- <div className="flex flex-col gap-4">
- <FieldRow label="Channel" hint="A channel URL, an @handle or a channel ID that starts with UC." htmlFor="yt-channel">
- <div className="flex gap-2">
- <div className="relative flex-1">
- <Link2 className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-faint" />
- <Input
- id="yt-channel"
- className="h-(--control-h-lg) pl-9"
- value={input}
- onChange={e => { setInput(e.target.value); setResolved(null); }}
- placeholder="youtube.com/@channel"
- onKeyDown={e => e.key === 'Enter' && handleResolve()}
- autoFocus
- />
- </div>
- <Button variant="outline" size="lg" onClick={handleResolve} disabled={resolving || !input.trim()}>
- {resolving ? <Spinner className="size-4" /> : <Search data-icon="inline-start" />}
- Find
- </Button>
- </div>
- </FieldRow>
-
- {resolved && (
- <div className="flex items-center gap-3 rounded-card border border-success/30 bg-success-soft p-3">
- <AccountAvatar account={{ platform: 'youtube', title: resolved.title, thumbnail: resolved.thumbnails?.medium || resolved.thumbnails?.default }} size="lg" />
- <div className="min-w-0 flex-1">
- <p className="flex items-center gap-1.5 text-sm font-semibold text-ink">
- <span className="truncate">{resolved.title}</span>
- <CheckCircle2 className="size-4 shrink-0 text-success" aria-label="Channel found" />
- </p>
- <p className="text-caption text-ink-muted">{resolved.customUrl}</p>
- {resolved.subscriberCount != null && (
- <p className="mt-0.5 text-caption text-ink-muted">
- {fmtNum(resolved.subscriberCount)} subscribers, {fmtNum(resolved.videoCount)} videos
- </p>
- )}
- </div>
- </div>
- )}
- </div>
- )}
-
- {platform === 'instagram' && (
- <div className="flex flex-col gap-4">
- <p className="text-sm text-ink-muted">
- We open Instagram so you can sign in and approve access. When you finish, Instagram sends you back here and the account appears in the list. The account must be an Instagram Business or Creator account; personal accounts cannot be connected.
- </p>
- <InstagramTesterNotice />
- </div>
- )}
-
- {platform === 'reddit' && (
- <div className="flex flex-col gap-4">
- <FieldRow label="Username" htmlFor="reddit-user">
- <div className="relative">
- <span className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm font-medium text-ink-faint">u/</span>
- <Input
- id="reddit-user"
- className="h-(--control-h-lg) pl-8"
- value={redditUsername}
- onChange={e => setRedditUsername(e.target.value)}
- placeholder="username"
- onKeyDown={e => e.key === 'Enter' && handleAddReddit()}
- autoFocus
- />
- </div>
- </FieldRow>
- <FieldRow label="Session cookie" hint="We store it on the server and never show it again." htmlFor="reddit-cookie">
- <Input
- id="reddit-cookie"
- type="password"
- className="h-(--control-h-lg) font-mono"
- value={redditCookie}
- onChange={e => setRedditCookie(e.target.value)}
- placeholder="reddit_session value"
- onKeyDown={e => e.key === 'Enter' && handleAddReddit()}
- />
- </FieldRow>
- <Alert>
- <Info />
- <AlertDescription>
- Sign in to reddit.com in your browser, open DevTools (F12), go to Application, then Cookies, then https://www.reddit.com, and copy the value of <strong className="font-semibold text-ink">reddit_session</strong>.
- </AlertDescription>
- </Alert>
- </div>
- )}
-
- <DialogFooter>
- {platform ? (
- <Button variant="ghost" onClick={() => { setPlatform(null); setResolved(null); }} className="sm:mr-auto">
- <ArrowLeft data-icon="inline-start" />
- Back
- </Button>
- ) : null}
- <Button variant="outline" onClick={closeDialog}>Cancel</Button>
- {platform === 'youtube' && (
- <Button onClick={handleAdd} disabled={!input.trim() || adding}>
- {adding && <Spinner className="size-4" />}
- {adding ? 'Adding channel' : 'Add channel'}
- </Button>
- )}
- {platform === 'instagram' && (
- <Button onClick={handleConnectInstagram} disabled={connecting}>
- {connecting ? <Spinner className="size-4" /> : <ExternalLink data-icon="inline-start" />}
- {connecting ? 'Opening Instagram' : 'Continue to Instagram'}
- </Button>
- )}
- {platform === 'reddit' && (
- <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || !redditCookie.trim() || addingReddit}>
- {addingReddit && <Spinner className="size-4" />}
- {addingReddit ? 'Adding account' : 'Add Reddit account'}
- </Button>
- )}
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <AddAccountDialog flow={addFlow} />
<ConfirmDialog
open={!!pendingDelete}
@@ -417,57 +77,3 @@ export default function AccountManager() {
</div>
);
}
-
-function AccountCard({ acct, platform, refreshing, onRefresh, onDelete }) {
- const metrics = METRICS[platform](acct);
- return (
- <article className="flex flex-col gap-4 rounded-card border border-line bg-surface-raised p-4">
- <div className="flex items-center gap-3">
- <AccountAvatar account={acct} size="lg" showPlatform />
- <div className="min-w-0 flex-1">
- <Link to={accountPath(acct)} className="block truncate text-sm font-semibold text-ink hover:underline">{accountName(acct)}</Link>
- <p className="truncate text-caption text-ink-faint">{platform === 'reddit' ? `u/${acct.username || ''}` : accountHandle(acct)}</p>
- </div>
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-sm" render={<Link to={accountPath(acct)} aria-label={`Open analytics for ${accountName(acct)}`} />} />}>
- <ArrowUpRight />
- </TooltipTrigger>
- <TooltipContent>Open analytics</TooltipContent>
- </Tooltip>
- </div>
-
- <dl className="grid grid-cols-3 divide-x divide-divider rounded-control bg-surface-sunken/60 py-2.5">
- {metrics.map(([label, value]) => (
- <div key={label} className="flex flex-col items-center gap-0.5 px-2 text-center">
- <dt className="text-caption text-ink-faint">{label}</dt>
- <dd className="font-heading text-base font-semibold text-ink tabular-nums">{fmtNum(value)}</dd>
- </div>
- ))}
- </dl>
-
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-ink-faint">
- {platform === 'reddit' && (
- acct.hasCookie ? (
- <span className="flex items-center gap-1 text-success"><Lock className="size-3" />Session cookie stored</span>
- ) : (
- <span className="flex items-center gap-1 text-danger"><Lock className="size-3" />Error: no session cookie. Remove and add the account again.</span>
- )
- )}
- {acct.lastUpdated && <span>Updated {timeAgo(acct.lastUpdated).toLowerCase()}</span>}
- </div>
-
- <div className="mt-auto flex gap-2">
- <Button variant="outline" size="sm" className="flex-1" onClick={onRefresh} disabled={refreshing}>
- <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
- </Button>
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label={`Remove ${accountName(acct)}`} className="text-ink-muted hover:bg-danger-soft hover:text-danger" />}>
- <Trash2 />
- </TooltipTrigger>
- <TooltipContent>Remove account</TooltipContent>
- </Tooltip>
- </div>
- </article>
- );
-}
diff --git a/frontend/src/features/accounts/AccountSection.jsx b/frontend/src/features/accounts/AccountSection.jsx
new file mode 100644
index 0000000..b531c84
--- /dev/null
+++ b/frontend/src/features/accounts/AccountSection.jsx
@@ -0,0 +1,33 @@
+import React from 'react';
+import { Badge } from '@/components/ui/badge';
+import SectionHeader from '@/components/SectionHeader';
+import { PlatformIcon } from '@/components/platform';
+import AccountCard from './AccountCard';
+
+export default function AccountSection({ section, accounts, refreshingId, onRefresh, onDelete }) {
+ return (
+ <section className="flex flex-col gap-3">
+ <SectionHeader
+ title={
+ <span className="flex items-center gap-2">
+ <PlatformIcon platform={section.key} className="size-4 text-ink-muted" />
+ {section.title}
+ <Badge variant="secondary">{accounts.length}</Badge>
+ </span>
+ }
+ />
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {accounts.map(acct => (
+ <AccountCard
+ key={acct.id}
+ acct={acct}
+ platform={section.key}
+ refreshing={refreshingId === acct.id}
+ onRefresh={() => onRefresh(acct.id)}
+ onDelete={() => onDelete(acct)}
+ />
+ ))}
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/src/features/accounts/AccountsEmptyState.jsx b/frontend/src/features/accounts/AccountsEmptyState.jsx
new file mode 100644
index 0000000..c627817
--- /dev/null
+++ b/frontend/src/features/accounts/AccountsEmptyState.jsx
@@ -0,0 +1,25 @@
+import React from 'react';
+import SectionHeader from '@/components/SectionHeader';
+import ChoiceCard from '@/components/ChoiceCard';
+import { PLATFORM_CHOICES } from './platformChoices';
+
+export default function AccountsEmptyState({ onChoose }) {
+ return (
+ <div className="flex flex-col gap-4">
+ <SectionHeader title="Choose what to connect" />
+ <div role="list" className="grid grid-cols-1 gap-x-3 gap-y-5 md:grid-cols-3">
+ {PLATFORM_CHOICES.map(choice => (
+ <div role="listitem" key={choice.value}>
+ <ChoiceCard
+ icon={<choice.Icon />}
+ title={choice.title}
+ description={choice.description}
+ onSelect={() => onChoose(choice.value)}
+ className="h-full"
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/features/accounts/AddAccountDialog.jsx b/frontend/src/features/accounts/AddAccountDialog.jsx
new file mode 100644
index 0000000..f476141
--- /dev/null
+++ b/frontend/src/features/accounts/AddAccountDialog.jsx
@@ -0,0 +1,75 @@
+import React from 'react';
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
+import ChoiceCard from '@/components/ChoiceCard';
+import InstagramTesterNotice from '@/components/InstagramTesterNotice';
+import { PLATFORM_META } from '@/lib/accounts';
+import { PLATFORM_CHOICES, platformChoiceTitle } from './platformChoices';
+import YouTubeAccountFields from './YouTubeAccountFields';
+import RedditAccountFields from './RedditAccountFields';
+import AddAccountFooter from './AddAccountFooter';
+
+function PlatformPicker({ onSelect }) {
+ return (
+ <div role="radiogroup" aria-label="Platform" className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ {PLATFORM_CHOICES.map(choice => (
+ <ChoiceCard
+ key={choice.value}
+ icon={<choice.Icon />}
+ title={PLATFORM_META[choice.value].label}
+ description={choice.description}
+ selected={false}
+ onSelect={() => onSelect(choice.value)}
+ />
+ ))}
+ </div>
+ );
+}
+
+export default function AddAccountDialog({ flow }) {
+ const { platform, channel, reddit } = flow;
+ return (
+ <Dialog open={flow.dialogOpen} onOpenChange={open => { if (!open) flow.closeDialog(); }}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{platform ? platformChoiceTitle(platform) : 'Add an account'}</DialogTitle>
+ <DialogDescription>
+ {platform ? 'Fill in the details, review, then add.' : 'Choose the platform you want to track.'}
+ </DialogDescription>
+ </DialogHeader>
+
+ {!platform && <PlatformPicker onSelect={flow.setPlatform} />}
+
+ {platform === 'youtube' && (
+ <YouTubeAccountFields
+ input={channel.input}
+ onInputChange={channel.changeInput}
+ onResolve={channel.handleResolve}
+ resolving={channel.resolving}
+ resolved={channel.resolved}
+ />
+ )}
+
+ {platform === 'instagram' && (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-ink-muted">
+ We open Instagram so you can sign in and approve access. When you finish, Instagram sends you back here and the account appears in the list. The account must be an Instagram Business or Creator account; personal accounts cannot be connected.
+ </p>
+ <InstagramTesterNotice />
+ </div>
+ )}
+
+ {platform === 'reddit' && (
+ <RedditAccountFields
+ username={reddit.username}
+ cookie={reddit.cookie}
+ onUsernameChange={reddit.setUsername}
+ onCookieChange={reddit.setCookie}
+ onSubmit={flow.redditAdd.handleAddReddit}
+ />
+ )}
+
+ <AddAccountFooter flow={flow} />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/features/accounts/AddAccountFooter.jsx b/frontend/src/features/accounts/AddAccountFooter.jsx
new file mode 100644
index 0000000..61f9fc5
--- /dev/null
+++ b/frontend/src/features/accounts/AddAccountFooter.jsx
@@ -0,0 +1,42 @@
+import React from 'react';
+import { ArrowLeft, ExternalLink } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { DialogFooter } from '@/components/ui/dialog';
+import { Spinner } from '@/components/ui/spinner';
+
+export default function AddAccountFooter({ flow }) {
+ const { platform, channel, reddit, channelAdd, redditAdd, instagram } = flow;
+ const { adding } = channelAdd;
+ const { connecting } = instagram;
+ const { addingReddit } = redditAdd;
+
+ return (
+ <DialogFooter>
+ {platform ? (
+ <Button variant="ghost" onClick={flow.goBack} className="sm:mr-auto">
+ <ArrowLeft data-icon="inline-start" />
+ Back
+ </Button>
+ ) : null}
+ <Button variant="outline" onClick={flow.closeDialog}>Cancel</Button>
+ {platform === 'youtube' && (
+ <Button onClick={channelAdd.handleAdd} disabled={!channel.input.trim() || adding}>
+ {adding && <Spinner className="size-4" />}
+ {adding ? 'Adding channel' : 'Add channel'}
+ </Button>
+ )}
+ {platform === 'instagram' && (
+ <Button onClick={instagram.handleConnectInstagram} disabled={connecting}>
+ {connecting ? <Spinner className="size-4" /> : <ExternalLink data-icon="inline-start" />}
+ {connecting ? 'Opening Instagram' : 'Continue to Instagram'}
+ </Button>
+ )}
+ {platform === 'reddit' && (
+ <Button onClick={redditAdd.handleAddReddit} disabled={!reddit.username.trim() || !reddit.cookie.trim() || addingReddit}>
+ {addingReddit && <Spinner className="size-4" />}
+ {addingReddit ? 'Adding account' : 'Add Reddit account'}
+ </Button>
+ )}
+ </DialogFooter>
+ );
+}
diff --git a/frontend/src/features/accounts/RedditAccountFields.jsx b/frontend/src/features/accounts/RedditAccountFields.jsx
new file mode 100644
index 0000000..e54e214
--- /dev/null
+++ b/frontend/src/features/accounts/RedditAccountFields.jsx
@@ -0,0 +1,43 @@
+import React from 'react';
+import { Info } from 'lucide-react';
+import { Input } from '@/components/ui/input';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { FieldRow } from '@/components/DetailPanel';
+
+export default function RedditAccountFields({ username, cookie, onUsernameChange, onCookieChange, onSubmit }) {
+ return (
+ <div className="flex flex-col gap-4">
+ <FieldRow label="Username" htmlFor="reddit-user">
+ <div className="relative">
+ <span className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm font-medium text-ink-faint">u/</span>
+ <Input
+ id="reddit-user"
+ className="h-(--control-h-lg) pl-8"
+ value={username}
+ onChange={e => onUsernameChange(e.target.value)}
+ placeholder="username"
+ onKeyDown={e => e.key === 'Enter' && onSubmit()}
+ autoFocus
+ />
+ </div>
+ </FieldRow>
+ <FieldRow label="Session cookie" hint="We store it on the server and never show it again." htmlFor="reddit-cookie">
+ <Input
+ id="reddit-cookie"
+ type="password"
+ className="h-(--control-h-lg) font-mono"
+ value={cookie}
+ onChange={e => onCookieChange(e.target.value)}
+ placeholder="reddit_session value"
+ onKeyDown={e => e.key === 'Enter' && onSubmit()}
+ />
+ </FieldRow>
+ <Alert>
+ <Info />
+ <AlertDescription>
+ Sign in to reddit.com in your browser, open DevTools (F12), go to Application, then Cookies, then https://www.reddit.com, and copy the value of <strong className="font-semibold text-ink">reddit_session</strong>.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+}
diff --git a/frontend/src/features/accounts/YouTubeAccountFields.jsx b/frontend/src/features/accounts/YouTubeAccountFields.jsx
new file mode 100644
index 0000000..6932468
--- /dev/null
+++ b/frontend/src/features/accounts/YouTubeAccountFields.jsx
@@ -0,0 +1,57 @@
+import React from 'react';
+import { CheckCircle2, Link2, Search } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { FieldRow } from '@/components/DetailPanel';
+import { AccountAvatar } from '@/components/platform';
+import { fmtNum } from '../../utils/formatters';
+
+function ResolvedChannel({ channel }) {
+ return (
+ <div className="flex items-center gap-3 rounded-card border border-success/30 bg-success-soft p-3">
+ <AccountAvatar account={{ platform: 'youtube', title: channel.title, thumbnail: channel.thumbnails?.medium || channel.thumbnails?.default }} size="lg" />
+ <div className="min-w-0 flex-1">
+ <p className="flex items-center gap-1.5 text-sm font-semibold text-ink">
+ <span className="truncate">{channel.title}</span>
+ <CheckCircle2 className="size-4 shrink-0 text-success" aria-label="Channel found" />
+ </p>
+ <p className="text-caption text-ink-muted">{channel.customUrl}</p>
+ {channel.subscriberCount != null && (
+ <p className="mt-0.5 text-caption text-ink-muted">
+ {fmtNum(channel.subscriberCount)} subscribers, {fmtNum(channel.videoCount)} videos
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default function YouTubeAccountFields({ input, onInputChange, onResolve, resolving, resolved }) {
+ return (
+ <div className="flex flex-col gap-4">
+ <FieldRow label="Channel" hint="A channel URL, an @handle or a channel ID that starts with UC." htmlFor="yt-channel">
+ <div className="flex gap-2">
+ <div className="relative flex-1">
+ <Link2 className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-faint" />
+ <Input
+ id="yt-channel"
+ className="h-(--control-h-lg) pl-9"
+ value={input}
+ onChange={e => onInputChange(e.target.value)}
+ placeholder="youtube.com/@channel"
+ onKeyDown={e => e.key === 'Enter' && onResolve()}
+ autoFocus
+ />
+ </div>
+ <Button variant="outline" size="lg" onClick={onResolve} disabled={resolving || !input.trim()}>
+ {resolving ? <Spinner className="size-4" /> : <Search data-icon="inline-start" />}
+ Find
+ </Button>
+ </div>
+ </FieldRow>
+
+ {resolved && <ResolvedChannel channel={resolved} />}
+ </div>
+ );
+}
diff --git a/frontend/src/features/accounts/accountManagerData.js b/frontend/src/features/accounts/accountManagerData.js
new file mode 100644
index 0000000..a235f1d
--- /dev/null
+++ b/frontend/src/features/accounts/accountManagerData.js
@@ -0,0 +1,54 @@
+import { ADMIN_EMAIL } from '../../lib/contact.js';
+import { accountHandle } from '../../lib/accounts.js';
+
+export const TESTER_HINT = `If your account is not an Instagram tester yet, email ${ADMIN_EMAIL} to be added, then accept the invite in Instagram.`;
+
+const IG_ERRORS = {
+ already_added: 'This Instagram account is already connected.',
+ cancelled: 'Instagram sign-in was cancelled. Try again when you are ready.',
+ access_denied: `Instagram did not grant access. Approve every requested permission and try again. ${TESTER_HINT}`,
+ invalid_state: 'The Instagram sign-in link expired. Start the connection again.',
+};
+
+const METRICS = {
+ youtube: acct => [['Subscribers', acct.subscriberCount], ['Views', acct.viewCount], ['Videos', acct.videoCount]],
+ instagram: acct => [['Followers', acct.followersCount], ['Following', acct.followsCount], ['Posts', acct.mediaCount]],
+ reddit: acct => [['Karma', acct.totalKarma], ['Post karma', acct.postKarma], ['Comment karma', acct.commentKarma]],
+};
+
+const ACCOUNT_SECTIONS = [
+ { key: 'youtube', title: 'YouTube channels' },
+ { key: 'instagram', title: 'Instagram accounts' },
+ { key: 'reddit', title: 'Reddit accounts' },
+];
+
+export function instagramErrorMessage(code) {
+ return IG_ERRORS[code] || `Instagram connection failed: ${code}. ${TESTER_HINT}`;
+}
+
+// instagram oauth returns with ?ig_connected=true or ?ig_error=...; ?add=1 opens the add flow
+export function readOAuthReturn(searchParams) {
+ const connected = searchParams.get('ig_connected');
+ const igError = searchParams.get('ig_error');
+ const add = searchParams.get('add');
+ if (!connected && !igError && !add) return null;
+
+ return {
+ connected: connected === 'true',
+ errorMessage: igError ? instagramErrorMessage(igError) : null,
+ openAdd: Boolean(add),
+ };
+}
+
+export function accountMetrics(platform, account) {
+ return METRICS[platform](account);
+}
+
+export function accountCardHandle(account, platform) {
+ if (platform === 'reddit') return `u/${account.username || ''}`;
+ return accountHandle(account);
+}
+
+export function visibleSections(groups) {
+ return ACCOUNT_SECTIONS.filter(section => groups[section.key].length > 0);
+}
diff --git a/frontend/src/features/accounts/accountManagerData.test.js b/frontend/src/features/accounts/accountManagerData.test.js
new file mode 100644
index 0000000..88c7be2
--- /dev/null
+++ b/frontend/src/features/accounts/accountManagerData.test.js
@@ -0,0 +1,53 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ TESTER_HINT, instagramErrorMessage, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections,
+} from './accountManagerData.js';
+
+const params = query => new URLSearchParams(query);
+
+test('known Instagram errors have their own message', () => {
+ assert.equal(instagramErrorMessage('already_added'), 'This Instagram account is already connected.');
+ assert.ok(instagramErrorMessage('access_denied').endsWith(TESTER_HINT));
+});
+
+test('unknown Instagram errors name the code and add the tester hint', () => {
+ assert.equal(instagramErrorMessage('weird'), `Instagram connection failed: weird. ${TESTER_HINT}`);
+});
+
+test('a return without OAuth or add parameters does nothing', () => {
+ assert.equal(readOAuthReturn(params('')), null);
+ assert.equal(readOAuthReturn(params('ig_error=&add=')), null);
+});
+
+test('a successful connection is reported without an error', () => {
+ assert.deepEqual(readOAuthReturn(params('ig_connected=true')), { connected: true, errorMessage: null, openAdd: false });
+});
+
+test('connected values other than true are dropped silently', () => {
+ assert.deepEqual(readOAuthReturn(params('ig_connected=false')), { connected: false, errorMessage: null, openAdd: false });
+});
+
+test('errors and the add flag are read together', () => {
+ const result = readOAuthReturn(params('ig_error=cancelled&add=1'));
+ assert.equal(result.connected, false);
+ assert.equal(result.errorMessage, 'Instagram sign-in was cancelled. Try again when you are ready.');
+ assert.equal(result.openAdd, true);
+});
+
+test('each platform card shows its own three metrics', () => {
+ assert.deepEqual(accountMetrics('youtube', { subscriberCount: 1, viewCount: 2, videoCount: 3 }), [['Subscribers', 1], ['Views', 2], ['Videos', 3]]);
+ assert.deepEqual(accountMetrics('instagram', { followersCount: 4 }).map(([label]) => label), ['Followers', 'Following', 'Posts']);
+ assert.deepEqual(accountMetrics('reddit', { totalKarma: 9 })[0], ['Karma', 9]);
+});
+
+test('card handles use u/ for Reddit and the platform handle otherwise', () => {
+ assert.equal(accountCardHandle({ username: 'ribbon' }, 'reddit'), 'u/ribbon');
+ assert.equal(accountCardHandle({}, 'reddit'), 'u/');
+ assert.equal(accountCardHandle({ customUrl: '@dusk' }, 'youtube'), '@dusk');
+});
+
+test('only platforms with accounts get a section, in a fixed order', () => {
+ const groups = { youtube: [], instagram: [{ id: 1 }], reddit: [{ id: 2 }] };
+ assert.deepEqual(visibleSections(groups).map(section => section.key), ['instagram', 'reddit']);
+});
diff --git a/frontend/src/features/accounts/platformChoices.js b/frontend/src/features/accounts/platformChoices.js
new file mode 100644
index 0000000..7113103
--- /dev/null
+++ b/frontend/src/features/accounts/platformChoices.js
@@ -0,0 +1,11 @@
+import { YouTubeIcon, InstagramIcon, RedditIcon } from '@/components/brand/platform-icons';
+
+export const PLATFORM_CHOICES = [
+ { value: 'youtube', title: 'YouTube channel', description: 'Paste a channel link, @handle or channel ID.', Icon: YouTubeIcon },
+ { value: 'instagram', title: 'Instagram account', description: 'Sign in with Instagram. Business or Creator accounts only.', Icon: InstagramIcon },
+ { value: 'reddit', title: 'Reddit account', description: 'Add a username and a session cookie from your browser.', Icon: RedditIcon },
+];
+
+export function platformChoiceTitle(value) {
+ return PLATFORM_CHOICES.find(choice => choice.value === value).title;
+}
diff --git a/frontend/src/features/accounts/useAccountDelete.js b/frontend/src/features/accounts/useAccountDelete.js
new file mode 100644
index 0000000..b950492
--- /dev/null
+++ b/frontend/src/features/accounts/useAccountDelete.js
@@ -0,0 +1,25 @@
+import { useState } from 'react';
+import { accountName } from '@/lib/accounts';
+import { api } from '../../services/api';
+
+export function useAccountDelete({ showToast, loadAccounts }) {
+ const [pendingDelete, setPendingDelete] = useState(null);
+ const [deleting, setDeleting] = useState(false);
+
+ const handleDelete = async () => {
+ if (!pendingDelete) return;
+ setDeleting(true);
+ try {
+ await api.deleteAccount(pendingDelete.id);
+ showToast(`${accountName(pendingDelete)} removed`);
+ setPendingDelete(null);
+ loadAccounts();
+ } catch (err) {
+ showToast(`Couldn't remove the account. ${err.message}`, 'error');
+ } finally {
+ setDeleting(false);
+ }
+ };
+
+ return { pendingDelete, setPendingDelete, deleting, handleDelete };
+}
diff --git a/frontend/src/features/accounts/useAccountRefresh.js b/frontend/src/features/accounts/useAccountRefresh.js
new file mode 100644
index 0000000..aa53b85
--- /dev/null
+++ b/frontend/src/features/accounts/useAccountRefresh.js
@@ -0,0 +1,35 @@
+import { useState } from 'react';
+import { api } from '../../services/api';
+
+// one id for both buttons: 'all' while refreshing every account, else the account id
+export function useAccountRefresh({ showToast, loadAccounts }) {
+ const [refreshingId, setRefreshingId] = useState(null);
+
+ const refreshOne = async id => {
+ setRefreshingId(id);
+ try {
+ await api.refreshAccount(id);
+ showToast('Account refreshed');
+ loadAccounts();
+ } catch (err) {
+ showToast(`Refresh failed. ${err.message}`, 'error');
+ } finally {
+ setRefreshingId(null);
+ }
+ };
+
+ const refreshAll = async () => {
+ setRefreshingId('all');
+ try {
+ await api.refreshAll();
+ showToast('All accounts refreshed');
+ loadAccounts();
+ } catch (err) {
+ showToast(`Refresh failed. ${err.message}`, 'error');
+ } finally {
+ setRefreshingId(null);
+ }
+ };
+
+ return { refreshingId, refreshOne, refreshAll };
+}
diff --git a/frontend/src/features/accounts/useAddAccount.js b/frontend/src/features/accounts/useAddAccount.js
new file mode 100644
index 0000000..f1cc72b
--- /dev/null
+++ b/frontend/src/features/accounts/useAddAccount.js
@@ -0,0 +1,144 @@
+import { useState } from 'react';
+import { api } from '../../services/api';
+
+function useChannelLookup(showToast) {
+ const [input, setInput] = useState('');
+ const [resolving, setResolving] = useState(false);
+ const [resolved, setResolved] = useState(null);
+
+ const changeInput = value => {
+ setInput(value);
+ setResolved(null);
+ };
+
+ const handleResolve = async () => {
+ if (!input.trim()) return;
+ setResolving(true);
+ setResolved(null);
+ try {
+ const res = await api.resolveChannel(input.trim());
+ setResolved(res.data || res);
+ } catch (err) {
+ showToast(`Couldn't find that channel. ${err.message}`, 'error');
+ } finally {
+ setResolving(false);
+ }
+ };
+
+ const clearResolved = () => setResolved(null);
+ const reset = () => {
+ setResolved(null);
+ setInput('');
+ };
+
+ return { input, resolving, resolved, changeInput, handleResolve, clearResolved, reset };
+}
+
+function useRedditFields() {
+ const [username, setUsername] = useState('');
+ const [cookie, setCookie] = useState('');
+
+ const reset = () => {
+ setUsername('');
+ setCookie('');
+ };
+
+ return { username, cookie, setUsername, setCookie, reset };
+}
+
+function useChannelAdd({ input, showToast, finishAdding }) {
+ const [adding, setAdding] = useState(false);
+
+ const handleAdd = async () => {
+ if (!input.trim()) return;
+ setAdding(true);
+ try {
+ await api.addAccount(input.trim());
+ showToast('YouTube channel added');
+ finishAdding();
+ } catch (err) {
+ showToast(`Couldn't add the channel. ${err.message}`, 'error');
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ return { adding, handleAdd };
+}
+
+function useRedditAdd({ username, cookie, showToast, finishAdding }) {
+ const [addingReddit, setAddingReddit] = useState(false);
+
+ const handleAddReddit = async () => {
+ if (!username.trim() || !cookie.trim()) return;
+ setAddingReddit(true);
+ try {
+ await api.addRedditAccount(username.trim(), cookie.trim());
+ showToast('Reddit account added');
+ finishAdding();
+ } catch (err) {
+ showToast(`Couldn't add the Reddit account. ${err.message}`, 'error');
+ } finally {
+ setAddingReddit(false);
+ }
+ };
+
+ return { addingReddit, handleAddReddit };
+}
+
+function useInstagramConnect(showToast) {
+ const [connecting, setConnecting] = useState(false);
+
+ const handleConnectInstagram = async () => {
+ setConnecting(true);
+ try {
+ const { url } = await api.getInstagramAuthUrl();
+ // same tab: instagram redirects back to /accounts?ig_connected=true
+ window.location.href = url;
+ } catch (err) {
+ showToast(`Couldn't start Instagram sign-in. ${err.message}`, 'error');
+ setConnecting(false);
+ }
+ };
+
+ return { connecting, handleConnectInstagram };
+}
+
+export function useAddAccount({ showToast, loadAccounts }) {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [platform, setPlatform] = useState(null);
+ const channel = useChannelLookup(showToast);
+ const reddit = useRedditFields();
+
+ const closeDialog = () => {
+ setDialogOpen(false);
+ setPlatform(null);
+ channel.reset();
+ reddit.reset();
+ };
+
+ const finishAdding = () => {
+ closeDialog();
+ loadAccounts();
+ };
+
+ // back keeps the typed channel and reddit fields; only the platform and lookup result reset
+ const goBack = () => {
+ setPlatform(null);
+ channel.clearResolved();
+ };
+
+ const openWithPlatform = value => {
+ setPlatform(value);
+ setDialogOpen(true);
+ };
+
+ const channelAdd = useChannelAdd({ input: channel.input, showToast, finishAdding });
+ const redditAdd = useRedditAdd({ username: reddit.username, cookie: reddit.cookie, showToast, finishAdding });
+ const instagram = useInstagramConnect(showToast);
+
+ return {
+ dialogOpen, setDialogOpen, platform, setPlatform, closeDialog, goBack, openWithPlatform,
+ channel, reddit, channelAdd, redditAdd, instagram,
+ };
+}
diff --git a/frontend/src/features/accounts/useInstagramOAuthReturn.js b/frontend/src/features/accounts/useInstagramOAuthReturn.js
new file mode 100644
index 0000000..249d38e
--- /dev/null
+++ b/frontend/src/features/accounts/useInstagramOAuthReturn.js
@@ -0,0 +1,21 @@
+import { useEffect } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { readOAuthReturn } from './accountManagerData';
+
+export function useInstagramOAuthReturn({ showToast, loadAccounts, setDialogOpen }) {
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ useEffect(() => {
+ const result = readOAuthReturn(searchParams);
+ if (!result) return;
+
+ if (result.connected) {
+ showToast('Instagram account connected');
+ loadAccounts();
+ } else if (result.errorMessage) {
+ showToast(result.errorMessage, 'error');
+ }
+ if (result.openAdd) setDialogOpen(true);
+ setSearchParams({}, { replace: true });
+ }, [searchParams, setSearchParams, showToast, loadAccounts, setDialogOpen]);
+}