// App shell: sidebar + topbar used across logged-in screens.
// Em mobile vira um app com header compacto + bottom tab bar.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

function useIsMobile() {
  const get = () => (typeof window !== 'undefined' && window.matchMedia('(max-width: 860px)').matches);
  const [isMobile, setIsMobile] = useState(get());
  useEffect(() => {
    const mq = window.matchMedia('(max-width: 860px)');
    const onChange = () => setIsMobile(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', onChange) : mq.addListener(onChange);
    return () => mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener(onChange);
  }, []);
  return isMobile;
}

function Sidebar({ route, navigate }) {
  const items = [
    { id: 'dashboard', label: 'Editor',          icon: 'Sparkles' },
    { id: 'gallery',   label: 'Galeria',         icon: 'Photo' },
    { id: 'presets',   label: 'Predefinições',   icon: 'Grid' },
  ];
  if (window.__isAdmin) {
    items.push({ id: 'admin', label: 'Admin', icon: 'Settings' });
  }
  return (
    <aside style={shellStyles.sidebar} className="hide-mobile">
      <div style={shellStyles.brand} onClick={() => navigate('#/landing')}>
        <AftershotMark />
        <span className="serif" style={{ fontSize: 24, lineHeight: 1 }}>Aftershot</span>
      </div>

      <nav style={{ display:'flex', flexDirection:'column', gap: 2, padding: '0 12px' }}>
        {items.map(it => {
          const Ic = Icons[it.icon];
          const active = route.startsWith('#/' + it.id);
          return (
            <button key={it.id} onClick={() => navigate('#/' + it.id)}
              style={{
                ...shellStyles.navItem,
                background: active ? 'var(--bg-deep)' : 'transparent',
                color: active ? 'var(--ink)' : 'var(--ink-3)',
                fontWeight: active ? 600 : 500,
              }}>
              <Ic size={17} sw={active ? 1.8 : 1.5} />
              <span>{it.label}</span>
            </button>
          );
        })}
      </nav>

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

      <div style={shellStyles.usage}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 8 }}>
          <span style={{ fontSize: 12, color:'var(--ink-3)', letterSpacing:'.02em', textTransform:'uppercase' }}>Uso do mês</span>
          <span className="mono" style={{ fontSize: 11, color:'var(--ink-4)' }}>{window.USER?.creditsUsed || 0}/{window.USER?.creditsTotal || 0}</span>
        </div>
        <div style={{ height: 4, background:'var(--line)', borderRadius: 4, overflow:'hidden' }}>
          <div style={{ width: `${((window.USER?.creditsUsed || 0)/(window.USER?.creditsTotal || 1))*100}%`, height:'100%', background:'var(--accent)' }} />
        </div>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop: 10 }}>
          <span style={{ fontSize: 12, color:'var(--ink-2)' }}>Plano {window.USER?.planName || 'Gratuito'}</span>
          <button style={{ fontSize: 12, color:'var(--accent)', fontWeight: 500 }}>Gerenciar</button>
        </div>
      </div>

      <div style={shellStyles.userRow}>
        <div style={shellStyles.avatar}>{(window.USER?.name || 'Us').slice(0,2).toUpperCase()}</div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{window.USER?.name}</div>
          <div style={{ fontSize: 12, color:'var(--ink-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{window.USER?.email}</div>
        </div>
        <button title="Sair" onClick={() => {
          window.DB.logout();
          navigate('#/login');
        }} style={{ color:'var(--ink-3)', padding: 6, borderRadius: 6 }}>
          <Icons.Logout size={16} />
        </button>
      </div>
    </aside>
  );
}

function MobileBottomNav({ route, navigate }) {
  const items = [
    { id: 'dashboard', label: 'Editor',  icon: 'Sparkles' },
    { id: 'presets',   label: 'Estilos', icon: 'Grid' },
    { id: 'account',   label: 'Conta',   icon: 'Photo' },
  ];
  return (
    <nav style={{
      position:'fixed', bottom: 0, left: 0, right: 0,
      background:'var(--paper)',
      borderTop:'1px solid var(--line)',
      paddingTop: 6,
      paddingBottom: 'calc(6px + var(--safe-bottom))',
      paddingLeft: 'var(--safe-left)', paddingRight: 'var(--safe-right)',
      display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 2,
      zIndex: 90,
      boxShadow:'0 -1px 0 rgba(31,26,21,.03), 0 -8px 20px -12px rgba(31,26,21,.08)',
      backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)',
    }}>
      {items.map(it => {
        const Ic = Icons[it.icon];
        const active = route.startsWith('#/' + it.id);
        return (
          <button key={it.id} onClick={() => navigate('#/' + it.id)}
            className="tap-fade"
            style={{
              display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap: 4,
              padding: '8px 6px', fontSize: 11, fontWeight: 600,
              color: active ? 'var(--accent)' : 'var(--ink-3)',
              minHeight: 52,
            }}>
            <div style={{
              display:'flex', alignItems:'center', justifyContent:'center',
              padding: '4px 14px', borderRadius: 14,
              background: active ? 'var(--accent-soft)' : 'transparent',
              transition: 'background .2s',
            }}>
              <Ic size={20} sw={active ? 2 : 1.6} />
            </div>
            <span style={{ letterSpacing:'.01em' }}>{it.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

function MobileTopbar({ title, onBack, right, navigate }) {
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 50,
      background:'rgba(245,241,235,.92)',
      backdropFilter:'blur(14px)', WebkitBackdropFilter:'blur(14px)',
      borderBottom:'1px solid var(--line)',
      paddingTop: 'calc(8px + var(--safe-top))',
      paddingLeft: 'calc(16px + var(--safe-left))',
      paddingRight: 'calc(16px + var(--safe-right))',
      paddingBottom: 10,
      display:'flex', alignItems:'center', gap: 10, minHeight: 52,
    }}>
      {onBack ? (
        <button onClick={onBack} className="tap-fade"
          style={{ width: 36, height: 36, borderRadius: 10, display:'flex', alignItems:'center', justifyContent:'center', background:'var(--paper)', border:'1px solid var(--line)', flexShrink: 0 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
        </button>
      ) : (
        <button onClick={() => navigate?.('#/landing')} style={{ display:'flex', alignItems:'center', gap: 8, flexShrink: 0 }}>
          <AftershotMark size={28}/>
        </button>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="serif" style={{ fontSize: 22, lineHeight: 1.1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{title}</div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap: 6, flexShrink: 0 }}>
        {right}
      </div>
    </div>
  );
}

function AftershotMark({ size = 28 }) {
  // Minimal mark: abstracted camera aperture / sunrise
  return (
    <div style={{ width: size, height: size, borderRadius: 8,
      background: 'linear-gradient(135deg, var(--accent) 0%, #8B5A3C 100%)',
      display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
      boxShadow: '0 2px 6px -2px rgba(201,100,66,.4)' }}>
      <svg width={size*0.6} height={size*0.6} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round">
        <path d="M4 16 Q12 4 20 16" />
        <circle cx="12" cy="14" r="2.5" fill="white" stroke="none" />
      </svg>
    </div>
  );
}

function Topbar({ title, subtitle, right }) {
  return (
    <div className="hide-mobile" style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: '22px 40px 20px', borderBottom: '1px solid var(--line)', background: 'var(--bg)',
    }}>
      <div>
        <div className="serif" style={{ fontSize: 30, lineHeight: 1.1 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 13, color:'var(--ink-3)', marginTop: 4 }}>{subtitle}</div>}
      </div>
      <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
        {right}
      </div>
    </div>
  );
}

function AppShell({ route, navigate, children, title, subtitle, topbarRight }) {
  const isMobile = useIsMobile();

  if (isMobile) {
    return (
      <div style={{ minHeight: '100dvh', background:'var(--bg)', display:'flex', flexDirection:'column' }}>
        <MobileTopbar title={title} navigate={navigate} right={topbarRight}/>
        <main style={{ flex: 1, paddingBottom: 'calc(var(--tab-bar-height) + var(--safe-bottom) + 8px)' }}>
          {children}
        </main>
        <MobileBottomNav route={route} navigate={navigate}/>
      </div>
    );
  }

  return (
    <div style={{ display:'grid', gridTemplateColumns: '256px 1fr', minHeight: '100vh', background:'var(--bg)' }}>
      <Sidebar route={route} navigate={navigate} />
      <main style={{ minWidth: 0, display:'flex', flexDirection:'column' }}>
        <Topbar title={title} subtitle={subtitle} right={topbarRight} />
        <div style={{ flex: 1, overflow:'auto' }}>{children}</div>
      </main>
    </div>
  );
}

function Pill({ children, tone = 'default' }) {
  const tones = {
    default:  { bg: 'var(--bg-deep)', fg: 'var(--ink-2)' },
    accent:   { bg: 'var(--accent-soft)', fg: 'var(--accent-deep)' },
    olive:    { bg: '#E7EADE', fg: 'var(--olive)' },
    ink:      { bg: 'var(--ink)', fg: 'var(--bg-warm)' },
  };
  const t = tones[tone] || tones.default;
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap: 4,
      padding: '3px 9px', borderRadius: 999, background: t.bg, color: t.fg,
      fontSize: 11, fontWeight: 500, letterSpacing:'.02em', textTransform:'uppercase',
    }}>{children}</span>
  );
}

function Button({ children, variant = 'primary', size = 'md', ...rest }) {
  const sz = size === 'lg' ? { padding: '14px 22px', fontSize: 15, minHeight: 48 } :
             size === 'sm' ? { padding: '8px 13px', fontSize: 13, minHeight: 36 } :
                             { padding: '11px 16px', fontSize: 14, minHeight: 42 };
  const variants = {
    primary:   { background:'var(--ink)',     color:'var(--bg-warm)', border:'1px solid var(--ink)' },
    accent:    { background:'var(--accent)',  color:'#fff',           border:'1px solid var(--accent)' },
    secondary: { background:'var(--paper)',   color:'var(--ink)',     border:'1px solid var(--line-2)' },
    ghost:     { background:'transparent',    color:'var(--ink-2)',   border:'1px solid transparent' },
  };
  return (
    <button {...rest} style={{
      ...sz, ...variants[variant],
      borderRadius: 12, fontWeight: 500, display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 8,
      transition: 'transform .1s, box-shadow .15s, background .15s, opacity .15s',
      ...(rest.style || {}),
    }}
    onMouseDown={e => e.currentTarget.style.transform = 'translateY(1px)'}
    onMouseUp={e => e.currentTarget.style.transform = ''}
    onMouseLeave={e => e.currentTarget.style.transform = ''}
    >{children}</button>
  );
}

const shellStyles = {
  sidebar: {
    display:'flex', flexDirection:'column',
    background: 'var(--bg-warm)',
    borderRight: '1px solid var(--line)',
    padding: '18px 0',
    gap: 20,
    position: 'sticky', top: 0, height: '100vh',
  },
  brand: {
    display:'flex', alignItems:'center', gap: 10, padding: '2px 20px', cursor: 'pointer',
  },
  navItem: {
    display:'flex', alignItems:'center', gap: 10,
    padding: '9px 12px', borderRadius: 8,
    fontSize: 14, textAlign: 'left',
    transition: 'background .12s',
  },
  usage: {
    margin: '0 16px', padding: '14px 14px',
    background: 'var(--paper)', border: '1px solid var(--line)',
    borderRadius: 12,
  },
  userRow: {
    display:'flex', alignItems:'center', gap: 10,
    padding: '12px 16px', margin: '0 8px',
    borderTop: '1px solid var(--line)',
  },
  avatar: {
    width: 32, height: 32, borderRadius: 8,
    background: 'var(--accent)', color: 'white',
    display:'flex', alignItems:'center', justifyContent:'center',
    fontSize: 12, fontWeight: 600, letterSpacing:'.02em',
  },
};

Object.assign(window, { Sidebar, Topbar, AppShell, AftershotMark, Pill, Button, MobileTopbar, MobileBottomNav, useIsMobile });
