/* global React, ReactDOM, window */
// Ruticomidas — app shell
const { useState, useEffect, useRef } = React;
const D = window.RC_DATA;
const SCREENS = window.RC_SCREENS;
const { AuthGate, useAuth } = window.RC_Auth;
const { StoreProvider } = window.RC_STORE;

function Sidebar({ current, onNav }) {
  const auth = useAuth();
  const user = auth?.user;
  const displayName = user ? (user.name || user.email?.split('@')[0] || '—') : '—';
  const role = user?.is_admin ? 'Hogar · admin' : 'Hogar · miembro';
  const avatarLetter = displayName[0]?.toUpperCase() || '?';

  return (
    <aside className="sidebar">
      <a className="brand" href="#" onClick={(e) => { e.preventDefault(); onNav('planning'); }}>
        Ruti<br /><span style={{color:'var(--mint)'}}>comidas</span>
      </a>

      {D.NAV.filter(group => !group.admin || user?.is_admin).map(group => (
        <div className="nav-group" key={group.group}>
          <div className="nav-group-label">{group.group}</div>
          {group.items.map(item => (
            <button
              key={item.id}
              className={'nav-link' + (current === item.id ? ' active' : '')}
              onClick={() => onNav(item.id)}
            >
              <span>{item.label}</span>
              {item.count != null && <span className="count">{item.count}</span>}
            </button>
          ))}
        </div>
      ))}

      <div className="sidebar-footer">
        <div className="user-chip">
          <div className="avatar">{avatarLetter}</div>
          <div className="who">
            <span className="name">{displayName}</span>
            <span className="role">{role}</span>
          </div>
        </div>
        <button
          onClick={() => window.rcOpen('change-password', {})}
          style={{ background: 'none', border: 'none', color: 'var(--text-meta)', fontSize: 12,
            cursor: 'pointer', padding: '4px 0', fontFamily: 'var(--f-sans)', marginTop: 6, textAlign: 'left' }}
          title="Cambiar contraseña"
        >
          Cambiar contraseña
        </button>
        <button
          onClick={() => auth?.logout()}
          style={{ background: 'none', border: 'none', color: 'var(--text-meta)', fontSize: 12,
            cursor: 'pointer', padding: '4px 0', fontFamily: 'var(--f-sans)' }}
          title="Cerrar sesión"
        >
          Salir
        </button>
      </div>
    </aside>
  );
}

function NotificationsPanel({ notifications, onClose, onReload, onOpenTicket }) {
  const unread = notifications.filter(n => !n.read);

  const markAll = async () => {
    await window.api('/api/notifications/read-all', 'POST', {});
    await onReload();
  };

  const handleClick = async (n) => {
    if (!n.read) {
      await window.api(`/api/notifications/${n.id}/read`, 'POST', {});
      await onReload();
    }
    const { queueItemId } = window.RC_notifText(n);
    if (queueItemId) {
      onClose();
      onOpenTicket && onOpenTicket(queueItemId);
    }
  };

  return (
    <div style={{
      position: 'fixed', top: 48, right: 16, width: 320, maxHeight: 480,
      background: 'var(--slate)', border: '1px solid var(--frame)',
      borderRadius: 12, boxShadow: '0 8px 24px rgba(0,0,0,.6)',
      zIndex: 1000, display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid var(--frame)' }}>
        <span style={{ fontWeight: 700, fontSize: 14, flex: 1, color: 'var(--text)' }}>Notificaciones</span>
        {unread.length > 0 && (
          <button onClick={markAll} style={{ background: 'none', border: 'none', color: 'var(--mint)', fontSize: 12, cursor: 'pointer' }}>
            Marcar todas
          </button>
        )}
        <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-meta)', fontSize: 18, cursor: 'pointer', marginLeft: 8 }}>×</button>
      </div>
      <div style={{ overflowY: 'auto', flex: 1 }}>
        {notifications.length === 0 && (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-meta)', fontSize: 13 }}>Sin notificaciones</div>
        )}
        {notifications.map(n => {
          const { title, body } = window.RC_notifText(n);
          return (
            <div key={n.id} onClick={() => handleClick(n)} style={{
              padding: '12px 16px', borderBottom: '1px solid var(--frame)',
              background: n.read ? 'transparent' : 'rgba(60,255,208,.06)',
              cursor: 'pointer',
            }}>
              <div style={{ fontSize: 13, fontWeight: n.read ? 400 : 600, color: 'var(--text)', marginBottom: 2 }}>{title}</div>
              {body ? <div style={{ fontSize: 11, color: 'var(--text-meta)', marginBottom: 2 }}>{body}</div> : null}
              <div style={{ fontSize: 11, color: 'var(--text-meta)' }}>{n.created_at?.slice(0, 16).replace('T', ' ')}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function Topbar({ current }) {
  const { notifications, reload } = window.RC_STORE.useStore();
  const [showNotifs, setShowNotifs] = useState(false);
  const unreadCount = notifications.filter(n => !n.read).length;
  const panelRef = useRef(null);

  useEffect(() => {
    if (!showNotifs) return;
    const handler = (e) => {
      if (panelRef.current && !panelRef.current.contains(e.target)) setShowNotifs(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [showNotifs]);

  return (
    <div className="topbar">
      <div className="topbar-spacer" />

      <button className="btn btn--sm" onClick={() => window.rcOpen('expense', {})}>+ Gasto manual</button>
      <button className="btn btn--sm" onClick={() => window.rcOpen('upload-ticket', {})}>📷 Subir ticket</button>
      <div ref={panelRef} style={{ position: 'relative' }}>
        <button className="bell" aria-label="notificaciones" onClick={() => setShowNotifs(v => !v)}>
          <svg className="ico" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
            <path d="M8 1.5v1M3.5 6.5a4.5 4.5 0 1 1 9 0v3l1 2H2.5l1-2v-3Z" />
            <path d="M6.5 12.5a1.5 1.5 0 0 0 3 0" />
          </svg>
          {unreadCount > 0 && (
            <span className="dot" style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 9, fontWeight: 700, minWidth: 14, height: 14, borderRadius: 7,
              padding: '0 3px',
            }}>
              {unreadCount > 9 ? '9+' : unreadCount}
            </span>
          )}
        </button>
        {showNotifs && (
          <NotificationsPanel
            notifications={notifications}
            onClose={() => setShowNotifs(false)}
            onReload={reload.notifications}
            onOpenTicket={(qid) => { window.location.hash = '#tickets'; }}
          />
        )}
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = useState(() => {
    const h = window.location.hash.slice(1);
    return SCREENS[h] ? h : 'planning';
  });

  useEffect(() => {
    window.location.hash = route;
  }, [route]);

  useEffect(() => {
    const handler = () => {
      const h = window.location.hash.slice(1);
      if (SCREENS[h]) setRoute(h);
    };
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);

  const Screen = SCREENS[route];

  return (
    <div className="app">
      <Sidebar current={route} onNav={setRoute} />
      <main className="main">
        <Topbar current={route} />
        <Screen />
      </main>
      <window.RC_ModalHost />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <AuthGate>
    <StoreProvider>
      <App />
    </StoreProvider>
  </AuthGate>
);
