// src/app.jsx — host shell (route + theme + viewport toggle)
const { useState: useAS, useEffect: useAE } = React;

const LS_KEY = 'prestes-catalog-state-v1';

function loadState() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch { return null; }
}
function saveState(s) {
  try { localStorage.setItem(LS_KEY, JSON.stringify(s)); } catch {}
}

function useIsRealMobile() {
  const [isMobile, setIsMobile] = useAS(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia('(max-width: 720px)').matches;
  });
  useAE(() => {
    const mql = window.matchMedia('(max-width: 720px)');
    const update = () => setIsMobile(mql.matches);
    mql.addEventListener ? mql.addEventListener('change', update) : mql.addListener(update);
    return () => {
      mql.removeEventListener ? mql.removeEventListener('change', update) : mql.removeListener(update);
    };
  }, []);
  return isMobile;
}

function App() {
  const initial = loadState() || {};
  const [route, setRoute] = useAS(initial.route || { name: 'home' });
  const [frame, setFrame] = useAS(initial.frame || 'mobile');
  const [theme, setTheme] = useAS(initial.theme || 'light');
  const [menuOpen, setMenuOpen] = useAS(false);
  const isRealMobile = useIsRealMobile();

  // Quando o usuário está em celular real, força layout mobile fullscreen
  // (sem host-bar e sem phone bezel — já está num dispositivo móvel real).
  const effectiveFrame = isRealMobile ? 'mobile' : frame;

  useAE(() => { saveState({ route, frame, theme }); }, [route, frame, theme]);
  useAE(() => { document.documentElement.dataset.theme = theme; }, [theme]);
  useAE(() => { if (menuOpen) { setMenuOpen(false); } /* close when route changes */ }, [route.name, route.id]);

  const goHome = () => setRoute({ name: 'home' });
  const goCategory = (id) => setRoute({ name: 'category', id });
  const goDetail = (placaId) => setRoute({ name: 'detail', id: placaId });
  const goBack = () => {
    if (route.name === 'detail') setRoute({ name: 'category', id: 'placas' });
    else if (route.name === 'category') setRoute({ name: 'home' });
  };

  const screen = (
    <>
      <AppHeader route={route} onBack={goBack} theme={theme} setTheme={setTheme}
                 onOpenMenu={() => setMenuOpen(true)} />
      {route.name === 'home' && <HomeScreen onOpenCategory={goCategory} frame={effectiveFrame}/>}
      {route.name === 'category' && <CategoryScreen onOpenPlaca={goDetail} frame={effectiveFrame}/>}
      {route.name === 'detail' && <DetailScreen frame={effectiveFrame}/>}
    </>
  );

  const drawer = (
    <SideDrawer
      open={menuOpen}
      onClose={() => setMenuOpen(false)}
      theme={theme}
      setTheme={setTheme}
      route={route}
      onHome={goHome}
      onCategory={goCategory}
      frame={effectiveFrame}
      fullscreenMobile={isRealMobile}
    />
  );

  const crumb = (
    <>
      <span className="crumb">
        <span className="crumb-text">Prestes /</span>{' '}
        <b>{route.name === 'home' ? 'Manual' : route.name === 'category' ? 'Placas' : 'Avaliação de Parceiros'}</b>
      </span>
    </>
  );

  // Mobile real: renderiza app direto fullscreen, sem host-bar e sem phone bezel.
  if (isRealMobile) {
    return (
      <div className="host fullscreen-mobile">
        <div className="app in-fullscreen">
          {screen}
        </div>
        {drawer}
      </div>
    );
  }

  return (
    <div className="host">
      <div className="host-bar">
        <a href="#" onClick={(e)=>{e.preventDefault(); goHome();}}
           style={{ display:'inline-flex', alignItems:'center', gap: 8, color: 'var(--ink)', textDecoration:'none' }}>
          <img src="assets/prestes-logo.png" alt="Prestes" style={{ width: 22, height: 22, objectFit: 'contain' }}/>
          <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Prestes</span>
        </a>
        <span style={{ color: 'var(--ink-faint)', opacity: 0.4 }}>·</span>
        {crumb}

        <div className="spacer"/>

        <div className="seg" title="Visualização">
          <button className={frame === 'mobile' ? 'on' : ''} onClick={() => setFrame('mobile')}>
            <IconPhone size={13}/> Mobile
          </button>
          <button className={frame === 'desktop' ? 'on' : ''} onClick={() => setFrame('desktop')}>
            <IconDesktop size={13}/> Desktop
          </button>
        </div>
      </div>

      <div className={`stage ${frame}`}>
        {frame === 'mobile'
          ? <PhoneFrame theme={theme} overlay={drawer}>{screen}</PhoneFrame>
          : <DesktopFrame overlay={drawer}>{screen}</DesktopFrame>}
      </div>
    </div>
  );
}

/* ===== Side Drawer (hamburger menu) ===== */
function SideDrawer({ open, onClose, theme, setTheme, route, onHome, onCategory, frame, fullscreenMobile }) {
  const useFixed = frame === 'desktop' || fullscreenMobile;
  return (
    <div aria-hidden={!open} className={`sd-wrap ${useFixed ? 'fixed' : ''} ${open ? 'open' : ''}`}>
      {/* Scrim */}
      <div onClick={onClose} className="sd-scrim"/>
      {/* Panel */}
      <aside className="sd-panel">
        {/* Drawer header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '20px 22px 16px',
          borderBottom: '1px solid var(--line-soft)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <img src="assets/prestes-logo.png" alt="Prestes"
                 style={{ width: 28, height: 28, objectFit: 'contain' }} />
            <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Prestes</span>
              <span style={{ fontSize: 14, fontWeight: 600, marginTop: 3 }}>Menu</span>
            </div>
          </div>
          <button onClick={onClose} aria-label="Fechar menu" style={{
            width: 32, height: 32, borderRadius: 999,
            border: '1px solid var(--line)',
            background: 'var(--bg-elev)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ink)',
          }}>
            <IconClose size={14}/>
          </button>
        </div>

        {/* Quick actions */}
        <nav style={{ padding: '16px 14px 6px' }}>
          <DrawerItem icon={IconHome} label="Início"
            active={route.name === 'home'}
            onClick={() => { onHome(); onClose(); }}/>
          <DrawerItem icon={IconSearch} label="Buscar peça"
            hint="⌘ K"
            onClick={() => { onCategory('placas'); onClose(); }}/>
        </nav>

        {/* Categories section */}
        <div style={{ padding: '8px 22px 4px' }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Categorias</div>
        </div>
        <nav style={{ padding: '0 14px 12px' }}>
          {CATEGORIES.map(cat => (
            <DrawerItem
              key={cat.id}
              label={cat.label}
              meta={String(cat.count).padStart(2,'0')}
              active={route.name === 'category' && route.id === cat.id}
              disabled={!cat.active}
              tag={cat.active ? 'Ativo' : 'Em breve'}
              icon={!cat.active ? IconLock : null}
              onClick={() => { if (cat.active) { onCategory(cat.id); onClose(); } }}
            />
          ))}
        </nav>

        {/* Appearance */}
        <div style={{ padding: '8px 22px 4px', borderTop: '1px solid var(--line-soft)', marginTop: 8 }}>
          <div className="eyebrow" style={{ marginTop: 14, marginBottom: 10 }}>Aparência</div>
          <div style={{
            display: 'inline-flex',
            background: 'var(--bg-sunk)',
            border: '1px solid var(--line)',
            borderRadius: 999, padding: 3,
            width: '100%',
            justifyContent: 'space-between',
          }}>
            <ThemeSegBtn active={theme === 'light'} onClick={() => setTheme('light')}>
              <IconSun size={13}/> Claro
            </ThemeSegBtn>
            <ThemeSegBtn active={theme === 'dark'} onClick={() => setTheme('dark')}>
              <IconMoon size={13}/> Escuro
            </ThemeSegBtn>
          </div>
        </div>

        {/* Footer */}
        <div style={{ marginTop: 'auto', padding: '20px 22px', borderTop: '1px solid var(--line-soft)' }}>
          <a href="mailto:duvidas@prestes.com.br"
             style={{
               display: 'flex', alignItems: 'center', gap: 10,
               textDecoration: 'none', color: 'var(--ink)',
               padding: '10px 0',
             }}>
            <IconMail size={14}/>
            <span style={{ fontSize: 13 }}>duvidas@prestes.com.br</span>
          </a>
          <div className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 10 }}>
            Manual v2.1 · Mar / 2026
          </div>
        </div>
      </aside>
    </div>
  );
}

function DrawerItem({ icon: Ic, label, hint, meta, tag, active, disabled, onClick }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      borderRadius: 10,
      background: active ? 'color-mix(in oklch, var(--prestes-green) 16%, transparent)' : 'transparent',
      color: active ? 'var(--prestes-teal)' : 'var(--ink)',
      opacity: disabled ? 0.48 : 1,
      cursor: disabled ? 'default' : 'pointer',
      textAlign: 'left',
      fontSize: 14,
      fontWeight: active ? 600 : 500,
      transition: 'background 0.15s',
    }}
    onMouseEnter={e => { if (!disabled && !active) e.currentTarget.style.background = 'var(--bg-sunk)'; }}
    onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      {Ic && <Ic size={16}/>}
      <span style={{ flex: 1 }}>{label}</span>
      {meta && <span className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)' }}>{meta}</span>}
      {tag && (
        <span style={{
          fontFamily: 'var(--font-mono)',
          fontSize: 9,
          textTransform: 'uppercase',
          letterSpacing: '0.06em',
          padding: '3px 7px',
          borderRadius: 999,
          background: tag === 'Ativo' ? 'var(--prestes-green)' : 'var(--bg-sunk)',
          color: tag === 'Ativo' ? '#0a2a0a' : 'var(--ink-faint)',
          border: tag === 'Ativo' ? 'none' : '1px solid var(--line)',
          fontWeight: 600,
        }}>{tag}</span>
      )}
      {hint && <span className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)', padding: '2px 6px', border: '1px solid var(--line)', borderRadius: 5 }}>{hint}</span>}
    </button>
  );
}

function ThemeSegBtn({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      flex: 1,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      padding: '8px 10px',
      borderRadius: 999,
      background: active ? 'var(--ink)' : 'transparent',
      color: active ? 'var(--bg)' : 'var(--ink-soft)',
      fontSize: 12,
      fontWeight: 500,
    }}>{children}</button>
  );
}

/* ===== Phone bezel ===== */
function PhoneFrame({ children, theme, overlay }) {
  return (
    <div style={{
      width: 402, height: 850,
      maxWidth: '94vw',
      borderRadius: 56,
      background: theme === 'dark'
        ? 'linear-gradient(135deg, #1a1a1a, #0d0d0d)'
        : 'linear-gradient(135deg, #2a2a2a, #1a1a1a)',
      padding: 12,
      boxShadow:
        '0 60px 120px -40px rgba(0,0,0,0.4), ' +
        '0 30px 60px -20px rgba(0,0,0,0.25), ' +
        'inset 0 0 0 2px rgba(255,255,255,0.06)',
      position: 'relative',
      flexShrink: 0,
    }}>
      {/* side buttons */}
      <div style={{ position:'absolute', left:-2, top:140, width:4, height:34, background:'#1a1a1a', borderRadius:'2px 0 0 2px' }}/>
      <div style={{ position:'absolute', left:-2, top:200, width:4, height:60, background:'#1a1a1a', borderRadius:'2px 0 0 2px' }}/>
      <div style={{ position:'absolute', left:-2, top:275, width:4, height:60, background:'#1a1a1a', borderRadius:'2px 0 0 2px' }}/>
      <div style={{ position:'absolute', right:-2, top:200, width:4, height:90, background:'#1a1a1a', borderRadius:'0 2px 2px 0' }}/>

      <div style={{
        width: '100%', height: '100%',
        borderRadius: 46,
        overflow: 'hidden',
        background: 'var(--bg)',
        position: 'relative',
      }}>
        {/* Status bar */}
        <div style={{
          height: 50,
          padding: '14px 28px 0',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
          fontFamily: 'var(--font-sans)',
          fontWeight: 600,
          fontSize: 15,
          color: 'var(--ink)',
          position: 'absolute',
          top: 0, left: 0, right: 0, zIndex: 30,
          pointerEvents: 'none',
          background: 'color-mix(in oklch, var(--bg) 78%, transparent)',
          backdropFilter: 'blur(16px) saturate(140%)',
          WebkitBackdropFilter: 'blur(16px) saturate(140%)',
        }}>
          <span>14:32</span>
          {/* Dynamic Island */}
          <div style={{
            position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
            width: 120, height: 32, background: '#000', borderRadius: 999,
          }}/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {/* signal */}
            <svg width="18" height="11" viewBox="0 0 18 11"><g fill="currentColor"><rect x="0" y="7" width="3" height="4" rx="0.5"/><rect x="5" y="5" width="3" height="6" rx="0.5"/><rect x="10" y="2" width="3" height="9" rx="0.5"/><rect x="15" y="0" width="3" height="11" rx="0.5"/></g></svg>
            <svg width="16" height="11" viewBox="0 0 16 11"><path d="M8 10.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM2 4.5a8 8 0 0 1 12 0M4 7a5 5 0 0 1 8 0" stroke="currentColor" strokeWidth="1.3" fill="none" strokeLinecap="round"/></svg>
            <svg width="26" height="12" viewBox="0 0 26 12"><rect x="0.5" y="0.5" width="22" height="11" rx="3" stroke="currentColor" fill="none"/><rect x="23" y="4" width="1.5" height="4" rx="0.5" fill="currentColor"/><rect x="2" y="2" width="18" height="8" rx="1.5" fill="currentColor"/></svg>
          </div>
        </div>

        {/* scrollable content */}
        <div className="app in-frame" style={{ paddingTop: 50, height: '100%' }}>
          {children}
        </div>

        {/* Drawer overlay (contained inside phone screen) */}
        {overlay}

        {/* Home indicator */}
        <div style={{
          position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
          width: 134, height: 5, borderRadius: 999,
          background: 'var(--ink)',
          opacity: 0.85,
          zIndex: 30,
          pointerEvents: 'none',
        }}/>
      </div>
    </div>
  );
}

/* ===== Desktop fullscreen frame ===== */
function DesktopFrame({ children, overlay }) {
  return (
    <div className="app desktop" style={{ width: '100%', position: 'relative' }}>
      {children}
      {overlay}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
