// studio.jsx — creator studio shell + sub-screens
// Sidebar nav with Overview / Outfits / Products / Analytics / Revenue / Audience / Drafts / Settings.
// Composes existing components (OutfitBoard, Silhouette, Avatar) + chart primitives from studio-charts.jsx.

const { useState: useStateS, useMemo: useMemoS, useEffect: useEffectS } = React;

// ─── Studio shell ──────────────────────────────────────────────────────────
function StudioScreen({ go, exitStudio, initialView = 'overview' }) {
  const [view, setView] = useStateS({ name: initialView });
  const session = window.useSession ? window.useSession() : (window.MBAuth?.get?.() || null);
  // Identity is the account's own: the public profile row where it exists,
  // falling back to what the signup form collected. There is no demo creator
  // to borrow a name, city or follower count from any more.
  const [profile, setProfile] = useStateS(null);
  const [isAdmin, setIsAdmin] = useStateS(false);
  const loadProfile = React.useCallback(async () => {
    if (!window.MBProfile || !session) { setProfile(null); return; }
    const res = await window.MBProfile.mine();
    if (!res.error) setProfile(res.profile);
  }, [session && session.id]);
  useEffectS(() => { loadProfile(); }, [loadProfile]);

  // Admin-only areas are hidden for everyone else. The hiding is a courtesy —
  // the policies on `brands` are what actually refuse a non-admin's write.
  useEffectS(() => {
    let cancelled = false;
    (async () => {
      if (!window.MBBrands || !session) { setIsAdmin(false); return; }
      const res = await window.MBBrands.isAdmin();
      if (!cancelled) setIsAdmin(!!res.admin);
    })();
    return () => { cancelled = true; };
  }, [session && session.id]);

  const emailName = ((session && session.email) || '').split('@')[0];
  const displayName = (profile && profile.displayName)
    || (session && (session.fullName || session.creatorName))
    || emailName
    || 'there';
  const me = {
    name: displayName,
    username: profile ? profile.username : null,
    handle: (profile && profile.username) || session?.handle || emailName || 'me',
    avatar: (displayName[0] || 'M').toUpperCase(),
    avatarUrl: (profile && profile.avatarUrl) || null,
    bio: (profile && profile.bio) || '',
    location: (profile && profile.location) || '',
    tags: (profile && profile.tags) || [],
  };

  const navTo = (v) => { setView(v); setDrawerOpen(false); };
  // Lets the honest empty-state screens link back to the dashboard.
  window.__studioNavTo = navTo;
  const logout = () => { window.MBAuth?.clear?.(); go({ name: 'home' }); };
  const [drawerOpen, setDrawerOpen] = useStateS(false);

  return (
    <div className={'dc-studio-shell' + (drawerOpen ? ' drawer-open' : '')} style={{ display: 'grid', gridTemplateColumns: '232px 1fr', minHeight: '100vh', background: '#F4F2EC' }}>
      <div className="dc-studio-overlay" onClick={() => setDrawerOpen(false)}/>
      <StudioSidebar view={view} navTo={navTo} exitStudio={exitStudio} me={me} isAdmin={isAdmin} onLogout={logout} onClose={() => setDrawerOpen(false)} go={go} />
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        {/* Mobile top bar (hidden on desktop via CSS) */}
        <header className="dc-studio-mobilebar" style={{
          position: 'sticky', top: 0, zIndex: 60,
          alignItems: 'center', justifyContent: 'space-between', gap: 12,
          padding: '12px 18px', background: 'rgba(244,242,236,0.92)',
          backdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(20,20,18,0.06)',
        }}>
          <button onClick={() => setDrawerOpen(true)} title="Menu" style={{
            appearance: 'none', border: '1px solid rgba(20,20,18,0.12)', background: '#FAFAF7',
            width: 40, height: 40, borderRadius: '50%', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#1a1a18" strokeWidth="1.8"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Logo size={16}/>
            <span style={{ fontSize: 9.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#8a8580' }}>Studio</span>
          </div>
          <button onClick={() => navTo({ name: 'settings' })} style={{
            appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, flexShrink: 0,
          }}>
            <Avatar creator={me} size={34}/>
          </button>
        </header>

        <StudioTopbar view={view} navTo={navTo} go={go} me={me}/>
        <main className="dc-studio-main" style={{ padding: '28px 36px 80px', flex: 1, background: '#F4F2EC', minWidth: 0 }}>
          {view.name === 'overview' && <StudioOverview navTo={navTo} me={me} go={go}/>}
          {view.name === 'outfits' && <StudioOutfits navTo={navTo} go={go}/>}
          {view.name === 'products' && <StudioProducts go={go}/>}
          {view.name === 'analytics' && <StudioAnalytics/>}
          {view.name === 'revenue' && <StudioRevenue/>}
          {view.name === 'audience' && <StudioAudience/>}
          {view.name === 'drafts' && <StudioDrafts go={go}/>}
          {view.name === 'moodboards' && <StudioMoodboards/>}
          {view.name === 'settings' && <StudioSettings me={me} onProfileSaved={loadProfile} go={go}/>}
          {view.name === 'brands' && <StudioBrands isAdmin={isAdmin} go={go}/>}
          {view.name === 'messages' && <StudioMessages isAdmin={isAdmin}/>}
          {view.name === 'partnerships' && <StudioPartnerships navTo={navTo}/>}
          {view.name === 'partnership-detail' && <StudioPartnershipDetail partnershipId={view.id} navTo={navTo}/>}
          {view.name === 'outfit-detail' && <StudioOutfitDetail outfitId={view.id} navTo={navTo} go={go}/>}
        </main>

        {/* Sticky bottom nav (mobile only) */}
        <StudioBottomNav view={view} navTo={navTo} openMore={() => setDrawerOpen(true)}/>
      </div>
    </div>
  );
}

// ─── Mobile bottom nav ──────────────────────────────────────────────────────
function StudioBottomNav({ view, navTo, openMore }) {
  const items = [
    { id: 'overview',  label: 'Home',     icon: 'grid' },
    { id: 'outfits',   label: 'Outfits',  icon: 'hanger' },
    { id: 'analytics', label: 'Stats',    icon: 'chart' },
    { id: 'revenue',   label: 'Revenue',  icon: 'coin' },
  ];
  return (
    <nav className="dc-studio-bottomnav" style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 100,
      alignItems: 'stretch', justifyContent: 'space-around',
      background: 'rgba(250,249,247,0.96)', backdropFilter: 'blur(12px)',
      borderTop: '1px solid rgba(20,20,18,0.08)',
      paddingBottom: 'env(safe-area-inset-bottom, 0px)',
    }}>
      {items.map(it => {
        const active = view.name === it.id;
        return (
          <button key={it.id} onClick={() => navTo({ name: it.id })} style={{
            appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
            flex: 1, padding: '10px 4px 12px', display: 'flex', flexDirection: 'column',
            alignItems: 'center', gap: 4, fontFamily: 'inherit',
            color: active ? '#1a1a18' : '#9a958e',
          }}>
            <SideIcon name={it.icon} color={active ? '#1a1a18' : '#9a958e'}/>
            <span style={{ fontSize: 9.5, letterSpacing: '0.06em', fontWeight: active ? 500 : 400 }}>{it.label}</span>
          </button>
        );
      })}
      <button onClick={openMore} style={{
        appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
        flex: 1, padding: '10px 4px 12px', display: 'flex', flexDirection: 'column',
        alignItems: 'center', gap: 4, fontFamily: 'inherit', color: '#9a958e',
      }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#9a958e" strokeWidth="1.6" strokeLinecap="round"><circle cx="5" cy="12" r="1.4"/><circle cx="12" cy="12" r="1.4"/><circle cx="19" cy="12" r="1.4"/></svg>
        <span style={{ fontSize: 9.5, letterSpacing: '0.06em' }}>More</span>
      </button>
    </nav>
  );
}

// ─── Sidebar ───────────────────────────────────────────────────────────────
function StudioSidebar({ view, navTo, exitStudio, me, isAdmin, onLogout, onClose, go }) {
  const items = [
    { id: 'overview',     label: 'Dashboard',     icon: 'grid' },
    { id: 'outfits',      label: 'My outfits',    icon: 'hanger' },
    { id: 'products',     label: 'Products',      icon: 'tag' },
    { id: 'analytics',    label: 'Analytics',     icon: 'chart' },
    { id: 'revenue',      label: 'Revenue',       icon: 'coin' },
    { id: 'audience',     label: 'Audience',      icon: 'users' },
    { id: 'partnerships', label: 'Partnerships',  icon: 'handshake' },
  ];
  const items2 = [
    { id: 'drafts',     label: 'Drafts',      icon: 'pen' },
    { id: 'moodboards', label: 'Moodboards',  icon: 'board' },
    // Only admins have anywhere to go here.
    ...(isAdmin ? [
      { id: 'brands',   label: 'Brands',   icon: 'tag' },
      { id: 'messages', label: 'Messages', icon: 'pen' },
    ] : []),
    { id: 'settings',   label: 'Settings',    icon: 'gear' },
  ];

  return (
    <aside className="dc-studio-sidebar" style={{
      borderRight: '1px solid rgba(20,20,18,0.06)',
      background: '#FAFAF7',
      padding: '20px 16px',
      display: 'flex', flexDirection: 'column', gap: 18,
      position: 'sticky', top: 0, height: '100vh', overflowY: 'auto',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 6px' }}>
        <button onClick={exitStudio} style={{ appearance: 'none', border: 'none', background: 'transparent', padding: 0, cursor: 'pointer' }}>
          <Logo size={17}/>
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#8a8580' }}>Studio</span>
          {/* Close button — only meaningful as drawer on mobile */}
          <button className="dc-studio-mobilebar" onClick={onClose} style={{
            appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
            fontSize: 22, lineHeight: 1, color: '#5a5a54', padding: 0,
          }}>×</button>
        </div>
      </div>

      <button onClick={() => { onClose?.(); go?.({ name: 'dashboard' }); }} style={{
        appearance: 'none', border: 'none', cursor: 'pointer', width: '100%',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        padding: '11px 12px', borderRadius: 10, background: '#1a1a18', color: '#FAFAF7',
        fontSize: 13, fontFamily: 'inherit', fontWeight: 500, letterSpacing: '-0.005em',
      }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#FAFAF7" strokeWidth="1.8" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
        New outfit
      </button>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {items.map(it => <SidebarItem key={it.id} item={it} active={view.name === it.id} onClick={() => navTo({ name: it.id })}/>)}
      </div>
      <div style={{ height: 1, background: 'rgba(20,20,18,0.06)', margin: '4px 8px' }}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {items2.map(it => <SidebarItem key={it.id} item={it} active={view.name === it.id} onClick={() => navTo({ name: it.id })}/>)}
      </div>

      {/* The monthly revenue goal that used to sit here was a hardcoded demo
          figure with no data source, so it has been removed. */}
      <div style={{ marginTop: 'auto' }}/>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 6px' }}>
        <Avatar creator={me} size={28}/>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{me.name}</div>
          <div style={{ fontSize: 10.5, color: '#8a8580' }}>@{me.handle}</div>
        </div>
        <button onClick={onLogout} title="Log out" style={{
          appearance: 'none', border: '1px solid rgba(20,20,18,0.1)', background: 'transparent',
          width: 28, height: 28, borderRadius: 8, cursor: 'pointer', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#5a5a54" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/></svg>
        </button>
      </div>
    </aside>
  );
}

function SidebarItem({ item, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', border: 'none', cursor: 'pointer',
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '9px 10px', borderRadius: 8,
      background: active ? '#1a1a18' : 'transparent',
      color: active ? '#FAFAF7' : '#1a1a18',
      fontSize: 13, fontFamily: 'inherit', textAlign: 'left',
      letterSpacing: '-0.005em', fontWeight: active ? 500 : 400,
    }}>
      <SideIcon name={item.icon} color={active ? '#FAFAF7' : '#3a3a36'}/>
      <span>{item.label}</span>
    </button>
  );
}

function SideIcon({ name, color = '#3a3a36' }) {
  const s = { width: 15, height: 15, fill: 'none', stroke: color, strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const map = {
    grid:   <svg {...s} viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>,
    hanger: <svg {...s} viewBox="0 0 24 24"><path d="M12 8a2 2 0 1 0-2-2"/><path d="M12 8v3l-9 7h18l-9-7"/></svg>,
    tag:    <svg {...s} viewBox="0 0 24 24"><path d="M3 12V3h9l9 9-9 9z"/><circle cx="7.5" cy="7.5" r="1"/></svg>,
    chart:  <svg {...s} viewBox="0 0 24 24"><path d="M3 21V3"/><path d="M21 21H3"/><path d="M7 16l4-5 4 3 5-7"/></svg>,
    coin:   <svg {...s} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M14.5 9a3 3 0 0 0-3-1.5c-1.5 0-3 .8-3 2.3 0 3.7 6 1.8 6 5.4 0 1.5-1.5 2.3-3 2.3a3 3 0 0 1-3-1.5"/><path d="M12 6v12"/></svg>,
    users:  <svg {...s} viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.5"/><path d="M2 21c0-3.5 3-6 7-6s7 2.5 7 6"/><circle cx="17" cy="9" r="2.5"/><path d="M22 19c0-2.5-2-4.5-5-4.5"/></svg>,
    pen:    <svg {...s} viewBox="0 0 24 24"><path d="M3 21l4-1 11-11-3-3L4 17l-1 4z"/></svg>,
    board:  <svg {...s} viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 3v18"/></svg>,
    handshake: <svg {...s} viewBox="0 0 24 24"><path d="M11 17l2 2a1.5 1.5 0 0 0 2.1 0l3.9-3.9a1.5 1.5 0 0 0 0-2.1L17 11"/><path d="M21 11l-3-3-3 3-2-2-5 5 2 2 3-3 3 3 2-2 3-3z"/><path d="M3 11l3-3 3 3 2-2"/></svg>,
  };
  return map[name] || null;
}

// ─── Topbar ───────────────────────────────────────────────────────────────
function StudioTopbar({ view, navTo, go, me }) {
  return (
    <header className="dc-studio-topbar" style={{
      position: 'sticky', top: 0, zIndex: 40,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 36px', background: 'rgba(244,242,236,0.86)',
      backdropFilter: 'blur(12px) saturate(140%)',
      borderBottom: '1px solid rgba(20,20,18,0.06)', gap: 16,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, minWidth: 0 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '9px 14px', borderRadius: 999,
          background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.08)',
          width: 280,
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#8a8580" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5"/></svg>
          <input placeholder="Search outfits, products, brands…" style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 12.5, fontFamily: 'inherit',
          }}/>
          <span style={{ fontSize: 10, color: '#8a8580', border: '1px solid rgba(20,20,18,0.12)', padding: '1px 5px', borderRadius: 4 }}>⌘K</span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {/* A hardcoded "$12,480.42 ↑ +18.2%" revenue pill lived here. There is no
            revenue data source, so it has been removed rather than faked. */}
        <button onClick={() => navTo({ name: 'overview' })} title="Notifications" style={iconBtnStudio}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1a1a18" strokeWidth="1.6"><path d="M18 16v-5a6 6 0 1 0-12 0v5l-2 2v1h16v-1z"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>
          <span style={notifDot}/>
        </button>
        <button onClick={() => go({ name: 'dashboard' })} style={{
          appearance: 'none', border: 'none', background: '#1a1a18', color: '#FAFAF7',
          padding: '9px 16px', borderRadius: 999, fontSize: 11.5,
          letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 500, cursor: 'pointer',
        }}>+ Upload outfit</button>
      </div>
    </header>
  );
}

const iconBtnStudio = {
  position: 'relative', appearance: 'none', border: '1px solid rgba(20,20,18,0.08)',
  background: '#FAFAF7', width: 36, height: 36, borderRadius: '50%',
  display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
};
const notifDot = {
  position: 'absolute', top: 8, right: 9, width: 7, height: 7, borderRadius: '50%',
  background: '#a8331a', border: '1.5px solid #FAFAF7',
};

// ─── Section header ───────────────────────────────────────────────────────
function StudioHeader({ kicker, title, sub, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 24 }}>
      <div>
        {kicker && <div style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: '#8a8580' }}>{kicker}</div>}
        <h1 style={{ margin: '8px 0 0', fontSize: 36, letterSpacing: '-0.025em', fontWeight: 400 }}>{title}</h1>
        {sub && <div style={{ marginTop: 8, fontSize: 13.5, color: '#5a5a54', maxWidth: '56ch' }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// ─── Card primitive ────────────────────────────────────────────────────────
function Card({ children, title, sub, right, padding = 20, style, className }) {
  return (
    <div className={className} style={{
      background: '#FAFAF7', borderRadius: 14, border: '1px solid rgba(20,20,18,0.06)',
      padding, ...style,
    }}>
      {(title || right) && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <div>
            {title && <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: '-0.005em' }}>{title}</div>}
            {sub && <div style={{ fontSize: 11.5, color: '#8a8580', marginTop: 2 }}>{sub}</div>}
          </div>
          {right}
        </div>
      )}
      {children}
    </div>
  );
}

// ─── Range selector pill ──────────────────────────────────────────────────
function RangeSelect({ value, onChange, options = ['7D', '30D', '90D', '12M', 'All'] }) {
  return (
    <div style={{ display: 'inline-flex', gap: 0, padding: 2, background: 'rgba(20,20,18,0.05)', borderRadius: 999 }}>
      {options.map(o => (
        <button key={o} onClick={() => onChange(o)} style={{
          appearance: 'none', border: 'none', cursor: 'pointer', padding: '5px 11px',
          borderRadius: 999, fontSize: 11, fontFamily: 'inherit',
          background: value === o ? '#FAFAF7' : 'transparent',
          color: value === o ? '#1a1a18' : '#5a5a54',
          fontWeight: value === o ? 500 : 400,
          boxShadow: value === o ? '0 1px 4px rgba(20,20,18,0.08)' : 'none',
        }}>{o}</button>
      ))}
    </div>
  );
}

Object.assign(window, { StudioScreen, StudioSidebar, StudioTopbar, SidebarItem, SideIcon, StudioHeader, Card, RangeSelect, iconBtnStudio });
