/* shell.jsx — Shared Sidebar + Topbar + Router context (replaces shell pieces in screen-brand-dashboard) */
/* global React, Icon, Avatar, useT, LanguageSwitcher, Popover, Pill */

// Route IDs map. Each "screen" in the app's top-level switcher corresponds to a route here.
const RouterCtx = React.createContext({ route: 'landing', go: () => {}, locale: 'en' });

function useRouter() { return React.useContext(RouterCtx); }

// ── Notifications data (mock) ─────────────────────────────────────────────
const NOTIFS_BRAND = [
  { id: 'b1', group: 'Today', icon: '📺', kind: 'mention', title: 'Linh Châu submitted D2 for review', body: 'Vitamin C Skin Glow · 30s TikTok cut', when: '12 min ago', route: 'brand-campaign-detail', unread: true },
  { id: 'b2', group: 'Today', icon: '✨', kind: 'system',  title: '12 creators applied to Vitamin C campaign', body: '4 are 90%+ match · review queue', when: '1h ago', route: 'brand-campaign-detail', unread: true },
  { id: 'b3', group: 'Today', icon: '💸', kind: 'system',  title: 'Monthly invoice INV-2026-051 ready', body: '$8,420 · due Jun 1', when: '3h ago', route: 'brand-reports', unread: false },
  { id: 'b4', group: 'This week', icon: '🌟', kind: 'system', title: 'New high-match creator: Mai T.', body: '94% fit · SPF + Niacinamide niche', when: 'Yesterday', route: 'brand-discovery', unread: false },
  { id: 'b5', group: 'This week', icon: '📊', kind: 'system', title: 'Coffee morning drop wrapped', body: 'Total reach 4.2M · +18% vs target', when: '3 days ago', route: 'brand-reports', unread: false },
];
const NOTIFS_CREATOR = [
  { id: 'c1', group: 'Today', icon: '✅', kind: 'mention', title: 'Trang Lê approved your D2 video', body: 'Coolmate · ready to schedule publish', when: '6 min ago', route: 'creator-campaign-publish', unread: true },
  { id: 'c2', group: 'Today', icon: '💰', kind: 'system',  title: 'Payment $720 sent to Vietcombank', body: 'Vitamin C Skin Glow · D2', when: '38 min ago', route: 'creator-earnings', unread: true },
  { id: 'c3', group: 'Today', icon: '🔥', kind: 'system',  title: 'Your Vit-C reel hit 1M views', body: '7.4% ER · top 5% of skincare posts', when: '2h ago', route: 'creator-campaign-detail', unread: true },
  { id: 'c4', group: 'This week', icon: '📩', kind: 'mention', title: 'New brief from Skinfolk matches you 94%', body: 'SPF for Gen-Z launch · $2-2.6K', when: 'Yesterday', route: 'creator-discover', unread: false },
  { id: 'c5', group: 'This week', icon: '⏰', kind: 'system', title: 'D3 reel due in 6 days', body: 'Vitamin C Skin Glow · Jun 04', when: '2 days ago', route: 'creator-campaign-upload', unread: false },
  { id: 'c6', group: 'Earlier', icon: '🎉', kind: 'system', title: 'You hit $25K all-time earnings', body: 'Up 62% YoY · keep it up', when: 'Last week', route: 'creator-earnings', unread: false },
];

function NotificationsPanel({ portal, onClose }) {
  const { go } = useRouter();
  const initial = portal === 'brand' ? NOTIFS_BRAND : NOTIFS_CREATOR;
  const [tab, setTab] = React.useState('all');
  const [items, setItems] = React.useState(initial);
  const filtered = items.filter(n => tab === 'all' || (tab === 'mentions' && n.kind === 'mention') || (tab === 'system' && n.kind === 'system'));
  const groups = [...new Set(filtered.map(n => n.group))];
  const unreadCount = items.filter(n => n.unread).length;
  const markAllRead = () => setItems(items.map(n => ({ ...n, unread: false })));
  const click = (n) => { setItems(items.map(x => x.id === n.id ? { ...x, unread: false } : x)); go(n.route); onClose(); };

  return (
    <div>
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
        <div className="row items-center justify-between mb-3">
          <div className="row items-center gap-8">
            <span className="title-md" style={{ fontSize: 16 }}>Notifications</span>
            {unreadCount > 0 && <Pill variant="pink">{unreadCount} new</Pill>}
          </div>
          <button onClick={markAllRead} disabled={!unreadCount} style={{
            background: 'transparent', border: 0, cursor: unreadCount ? 'pointer' : 'not-allowed',
            fontFamily: 'inherit', fontSize: 11, fontWeight: 700,
            color: unreadCount ? 'var(--cyan-dark)' : 'var(--ink-soft)'
          }}>Mark all read</button>
        </div>
        <div className="row gap-4" style={{ padding: 3, background: 'var(--bg-soft)', borderRadius: 999 }}>
          {[['all', 'All'], ['mentions', 'Mentions'], ['system', 'System']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              flex: 1, padding: '6px 10px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
              background: tab === k ? 'white' : 'transparent',
              color: tab === k ? 'var(--ink)' : 'var(--ink-soft)',
              fontWeight: 700, fontSize: 11,
              boxShadow: tab === k ? '0 1px 3px rgba(0,43,80,0.1)' : 'none'
            }}>{l}</button>
          ))}
        </div>
      </div>
      <div style={{ maxHeight: 480, overflowY: 'auto' }}>
        {filtered.length === 0 ? (
          <div className="text-center muted" style={{ padding: 40, fontSize: 12 }}>You're all caught up 🎉</div>
        ) : groups.map(g => (
          <div key={g}>
            <div style={{ padding: '10px 16px 6px', fontSize: 9, fontWeight: 800, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>{g}</div>
            {filtered.filter(n => n.group === g).map(n => (
              <button key={n.id} onClick={() => click(n)} className="row items-start gap-10" style={{
                width: '100%', padding: '10px 16px', border: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                background: n.unread ? 'rgba(0,156,255,0.04)' : 'transparent', borderLeft: '3px solid ' + (n.unread ? 'var(--cyan)' : 'transparent'),
                transition: 'background .15s'
              }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                onMouseLeave={e => e.currentTarget.style.background = n.unread ? 'rgba(0,156,255,0.04)' : 'transparent'}>
                <div style={{ fontSize: 18, lineHeight: 1.2 }}>{n.icon}</div>
                <div className="flex-1" style={{ minWidth: 0 }}>
                  <div className="bold" style={{ fontSize: 12.5, lineHeight: 1.4 }}>{n.title}</div>
                  <div className="muted" style={{ fontSize: 11, lineHeight: 1.4 }}>{n.body}</div>
                  <div className="muted" style={{ fontSize: 10, marginTop: 2 }}>{n.when}</div>
                </div>
                {n.unread && <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--cyan)', marginTop: 5 }} />}
              </button>
            ))}
          </div>
        ))}
      </div>
      <div className="row items-center justify-between" style={{ padding: '10px 16px', borderTop: '1px solid var(--line)' }}>
        <button onClick={onClose} style={{ background: 'transparent', border: 0, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 700, color: 'var(--ink-soft)' }}>Notification settings</button>
        <span className="muted" style={{ fontSize: 10 }}>Updated just now</span>
      </div>
    </div>
  );
}

function WorkspacePanel({ portal, onClose }) {
  const { go } = useRouter();
  const isBrand = portal === 'brand';
  return (
    <div>
      <div style={{
        padding: '16px 16px 14px',
        background: isBrand ? 'linear-gradient(135deg, #002B50, #1C1CC9)' : 'linear-gradient(135deg, #79FEE7, #EAC2FB)',
        color: isBrand ? 'white' : 'var(--ink)'
      }}>
        <div className="row items-center gap-10 mb-3">
          <Avatar name={isBrand ? 'Coolmate VN' : 'Linh Châu'} size={42} />
          <div className="flex-1">
            <div className="bold" style={{ fontSize: 14 }}>{isBrand ? 'Coolmate VN' : 'Linh Châu'}</div>
            <div style={{ fontSize: 11, opacity: 0.85 }}>{isBrand ? 'Brand workspace · Pro plan' : '@linhchau · Skincare · HCM'}</div>
          </div>
          {!isBrand && <span style={{ background: 'rgba(255,255,255,0.6)', borderRadius: 999, padding: '2px 8px', fontSize: 9, fontWeight: 800, letterSpacing: '0.1em' }}>VERIFIED</span>}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
          {(isBrand ? [
            ['Active', '3', 'campaigns'],
            ['Q2 spend', '$72K', 'of $100K'],
            ['Avg ROI', '3.4x', 'last 30d'],
          ] : [
            ['Followers', '482K', '+8.2K mo'],
            ['ER', '6.2%', 'top 5%'],
            ['Q2 earned', '$4.7K', 'of $6.5K goal'],
          ]).map(([l, v, sub], i) => (
            <div key={i} style={{
              padding: '8px 10px', borderRadius: 8,
              background: isBrand ? 'rgba(255,255,255,0.1)' : 'rgba(255,255,255,0.55)'
            }}>
              <div style={{ fontSize: 9, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.7 }}>{l}</div>
              <div className="font-display tabular" style={{ fontSize: 16, fontWeight: 700, lineHeight: 1.1, marginTop: 2 }}>{v}</div>
              <div style={{ fontSize: 9.5, opacity: 0.75 }}>{sub}</div>
            </div>
          ))}
        </div>
        <div className="mt-3">
          <div className="row items-center justify-between" style={{ fontSize: 10, fontWeight: 700, opacity: 0.9, marginBottom: 4 }}>
            <span>{isBrand ? 'Q2 budget' : 'Q2 earnings goal'}</span>
            <span className="tabular">72%</span>
          </div>
          <div style={{ height: 5, borderRadius: 999, background: isBrand ? 'rgba(255,255,255,0.18)' : 'rgba(0,43,80,0.18)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: '72%', background: isBrand ? 'var(--mint)' : 'var(--ink)', borderRadius: 999 }} />
          </div>
        </div>
      </div>
      <div style={{ padding: 8 }}>
        {(isBrand ? [
          ['View dashboard', '🏠', 'brand-dashboard'],
          ['All campaigns', '📣', 'brand-campaigns'],
          ['Reports & invoices', '📊', 'brand-reports'],
          ['Workspace settings', '⚙️', 'brand-settings'],
        ] : [
          ['Edit media kit', '🎨', 'creator-profile'],
          ['Earnings & payouts', '💰', 'creator-earnings'],
          ['My campaigns', '📣', 'creator-campaigns'],
          ['Account settings', '⚙️', 'creator-settings'],
        ]).map(([l, ic, route]) => (
          <button key={route} onClick={() => { go(route); onClose(); }} className="row items-center gap-10" style={{
            width: '100%', padding: '9px 10px', borderRadius: 8, border: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
            background: 'transparent', fontSize: 12.5, fontWeight: 600
          }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span style={{ fontSize: 16, width: 22, textAlign: 'center' }}>{ic}</span>
            <span className="flex-1">{l}</span>
            <span style={{ color: 'var(--ink-soft)' }}>{Icon.arrow}</span>
          </button>
        ))}
      </div>
      <div style={{ padding: '8px 16px 14px', borderTop: '1px solid var(--line)' }}>
        <button onClick={() => { go('landing'); onClose(); }} style={{
          width: '100%', padding: '8px 0', background: 'transparent', border: 0, cursor: 'pointer',
          fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: 'var(--pink-hot)'
        }}>Log out</button>
      </div>
    </div>
  );
}

function NewCampaignMenu({ onClose }) {
  const { go } = useRouter();
  const opts = [
    { l: 'Full wizard', sub: '5 steps · budget, brief, audience, deliverables', ic: '✨', route: 'brand-campaign-new', primary: true },
    { l: 'From template', sub: 'Pick from your 4 saved campaign blueprints', ic: '📄', route: 'brand-campaign-new' },
    { l: 'Duplicate existing', sub: 'Clone Coffee morning drop / SPF Tour / others', ic: '🔁', route: 'brand-campaigns' },
    { l: 'Quick brief', sub: 'Single screen — perfect for testing an idea', ic: '⚡', route: 'brand-brief-new' },
  ];
  return (
    <div style={{ padding: 8 }}>
      <div style={{ padding: '8px 10px 4px', fontSize: 9, fontWeight: 800, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Start a new campaign</div>
      {opts.map((o, i) => (
        <button key={i} onClick={() => { go(o.route); onClose(); }} className="row items-start gap-12" style={{
          width: '100%', padding: 12, borderRadius: 10, border: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
          background: o.primary ? 'rgba(0,156,255,0.06)' : 'transparent',
          marginBottom: 2
        }}
          onMouseEnter={e => e.currentTarget.style.background = o.primary ? 'rgba(0,156,255,0.12)' : 'var(--bg-soft)'}
          onMouseLeave={e => e.currentTarget.style.background = o.primary ? 'rgba(0,156,255,0.06)' : 'transparent'}>
          <div style={{ fontSize: 22, width: 28, textAlign: 'center' }}>{o.ic}</div>
          <div className="flex-1">
            <div className="bold" style={{ fontSize: 13 }}>{o.l}</div>
            <div className="muted" style={{ fontSize: 11, marginTop: 1 }}>{o.sub}</div>
          </div>
          {o.primary && <Pill variant="cyan">Recommended</Pill>}
        </button>
      ))}
    </div>
  );
}

const BRAND_NAV = [
  { group: 'nav.group.workspace', items: [
    { id: 'brand-dashboard', tkey: 'nav.dashboard', icon: 'home' },
    { id: 'brand-discovery', tkey: 'nav.discovery', icon: 'search' },
    { id: 'brand-campaigns', tkey: 'nav.campaigns', icon: 'megaphone', badge: '3' },
    { id: 'brand-reports', tkey: 'nav.reports', icon: 'chart' },
    { id: 'brand-aff', tkey: 'nav.aff', icon: 'dollar', badge: 'NEW' },
  ]},
  { group: 'nav.group.data', items: [
    { id: 'brand-import', tkey: 'nav.import', icon: 'file' },
    { id: 'brand-settings', tkey: 'nav.settings', icon: 'settings' },
  ]}
];

const CREATOR_NAV = [
  { group: 'nav.group.workspace', items: [
    { id: 'creator-dashboard', tkey: 'nav.dashboard', icon: 'home' },
    { id: 'creator-discover', tkey: 'nav.openCampaigns', icon: 'file', badge: '7' },
    { id: 'creator-applications', tkey: 'nav.applications', icon: 'check' },
    { id: 'creator-campaigns', tkey: 'nav.myCampaigns', icon: 'megaphone' },
    { id: 'creator-earnings', tkey: 'nav.earnings', icon: 'dollar' },
    { id: 'creator-profile', tkey: 'nav.mediakit', icon: 'users' },
  ]},
  { group: 'nav.group.account', items: [
    { id: 'creator-settings', tkey: 'nav.settings', icon: 'settings' },
  ]}
];

function AppSidebar({ portal = 'brand', active }) {
  const { t } = useT();
  const { go } = useRouter();
  const navs = portal === 'brand' ? BRAND_NAV : CREATOR_NAV;
  const wsRef = React.useRef(null);
  const [wsOpen, setWsOpen] = React.useState(false);
  return (
    <aside className="sidebar">
      <div className="logo">
        <div style={{
          width: 30, height: 30, borderRadius: 9,
          background: 'linear-gradient(135deg, #009CFF, #1C1CC9)',
          color: 'white', display: 'grid', placeItems: 'center',
          fontWeight: 800, fontSize: 16, boxShadow: '0 4px 12px rgba(28,28,201,0.32)'
        }}>P</div>
        <span>Prime</span>
        <span style={{
          fontSize: 9, letterSpacing: '0.1em',
          background: portal === 'brand' ? 'var(--cyan)' : 'var(--mint)',
          color: portal === 'brand' ? 'white' : 'var(--ink)',
          padding: '2px 6px', borderRadius: 999, marginLeft: 'auto'
        }}>{portal === 'brand' ? 'BRAND' : 'CREATOR'}</span>
      </div>

      {navs.map((g, gi) => (
        <div key={gi} className="nav-group">
          <div className="nav-label">{t(g.group)}</div>
          {g.items.map(n => (
            <div
              key={n.id}
              className={`nav-item ${active === n.id ? 'active' : ''}`}
              onClick={() => go(n.id)}
            >
              <span className="nav-icon">{Icon[n.icon]}</span>
              {t(n.tkey)}
              {n.badge && <span className="nav-badge">{n.badge}</span>}
            </div>
          ))}
        </div>
      ))}

      <div ref={wsRef} className="workspace-card" onClick={() => setWsOpen(o => !o)} style={{ cursor: 'pointer' }}>
        <div className="row items-center gap-8 mb-2">
          {portal === 'brand'
            ? <Avatar name="Coolmate VN" size={28} />
            : <Avatar name="Linh Châu" size={28} />}
          <div className="flex-1">
            <div className="ws-name" style={{ fontSize: 12 }}>{portal === 'brand' ? 'Coolmate VN' : 'Linh Châu'}</div>
            <div style={{ fontSize: 10, opacity: 0.8 }}>{portal === 'brand' ? 'Brand workspace' : '@linhchau · Skincare'}</div>
          </div>
          <span style={{ color: 'var(--ink-soft)', fontSize: 10, transition: 'transform .2s', transform: wsOpen ? 'rotate(180deg)' : 'none' }}>{Icon.arrowDown}</span>
        </div>
        <div style={{ height: 6, borderRadius: 999, background: 'rgba(0,43,80,0.15)', overflow: 'hidden', marginTop: 8 }}>
          <div style={{ height: '100%', width: '72%', background: 'var(--ink)', borderRadius: 999, animation: 'grow-w 1.5s .4s cubic-bezier(.4,0,.2,1) backwards', transformOrigin: 'left', transform: 'scaleX(0)' }} />
        </div>
        <div className="row items-center justify-between" style={{ fontSize: 10, marginTop: 4, fontWeight: 600 }}>
          <span>{portal === 'brand' ? 'Q2 spend' : 'Q2 earnings'}</span>
          <span>{portal === 'brand' ? '$72K / $100K' : '$4.7K / $6.5K'}</span>
        </div>
      </div>
      <Popover open={wsOpen} onClose={() => setWsOpen(false)} anchorRef={wsRef} align="left" width={320}>
        <WorkspacePanel portal={portal} onClose={() => setWsOpen(false)} />
      </Popover>
    </aside>
  );
}

function AppTopbar({ showNewCampaign = true, showNewBrief, portal = 'brand' }) {
  const { t, locale } = useT();
  const { go, route } = useRouter();
  const setLocale = (l) => window.__setLocale && window.__setLocale(l);
  // Infer portal from current route if not given; respect legacy showNewBrief alias
  const isCreator = portal === 'creator' || (route && route.startsWith('creator'));
  const portalKey = isCreator ? 'creator' : 'brand';
  const showCTA = (showNewBrief === false) ? false : (isCreator ? false : showNewCampaign);
  const bellRef = React.useRef(null);
  const ctaRef  = React.useRef(null);
  const [bellOpen, setBellOpen] = React.useState(false);
  const [ctaOpen,  setCtaOpen]  = React.useState(false);
  const unread = (portalKey === 'brand' ? NOTIFS_BRAND : NOTIFS_CREATOR).filter(n => n.unread).length;

  return (
    <div className="topbar">
      <div className="search">
        {Icon.search}
        <input placeholder={t('topbar.search')} />
        <span className="muted" style={{ fontSize: 11, padding: '2px 8px', background: 'var(--bg-soft)', borderRadius: 6 }}>⌘ K</span>
      </div>
      <div style={{ marginLeft: 'auto' }} className="row items-center gap-12">
        <LanguageSwitcher locale={locale} onChange={setLocale} />
        {showCTA && (
          <button ref={ctaRef} className="btn btn-cyan btn-sm" onClick={() => setCtaOpen(o => !o)}>
            {Icon.plus} {t('topbar.newCampaign')}
          </button>
        )}
        <div ref={bellRef} className="bell" onClick={() => setBellOpen(o => !o)} style={{ cursor: 'pointer', position: 'relative' }}>
          {Icon.bell}
          {unread > 0 && (
            <span style={{
              position: 'absolute', top: 4, right: 4, minWidth: 16, height: 16,
              padding: '0 4px', borderRadius: 999, background: 'var(--pink-hot)', color: 'white',
              fontSize: 9, fontWeight: 800, display: 'grid', placeItems: 'center',
              border: '2px solid white'
            }}>{unread}</span>
          )}
        </div>
        <UserMenuTrigger />
      </div>
      <Popover open={bellOpen} onClose={() => setBellOpen(false)} anchorRef={bellRef} align="right" width={400}>
        <NotificationsPanel portal={portalKey} onClose={() => setBellOpen(false)} />
      </Popover>
      <Popover open={ctaOpen} onClose={() => setCtaOpen(false)} anchorRef={ctaRef} align="right" width={340}>
        <NewCampaignMenu onClose={() => setCtaOpen(false)} />
      </Popover>
    </div>
  );
}

// Re-usable Page header
function PageHeader({ eyebrow, title, subtitle, actions }) {
  return (
    <div className="row items-end justify-between mb-6">
      <div>
        {eyebrow}
        <h1 className="page-title" style={{ marginTop: eyebrow ? 8 : 0 }}>{title}</h1>
        {subtitle && <div className="page-subtitle">{subtitle}</div>}
      </div>
      {actions && <div className="row gap-8">{actions}</div>}
    </div>
  );
}

Object.assign(window, { RouterCtx, useRouter, AppSidebar, AppTopbar, PageHeader, BRAND_NAV, CREATOR_NAV });
