// SATMELI — Shell de la app: navegación + router por instancia.

function BrandMark({ size = 30, withName = true, mode }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
      <span style={{ width: size, height: size, borderRadius: 9, background: 'var(--ink)', color: 'var(--signal)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name="radar" size={size * 0.62} stroke={2} />
      </span>
      {withName && (
        <div style={{ lineHeight: 1 }}>
          <div style={{ fontFamily: 'var(--font)', fontSize: 16, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)' }}>SATMELI</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 8.5, letterSpacing: '0.1em', color: 'var(--muted-3)', marginTop: 2 }}>ALERTA TEMPRANA</div>
        </div>
      )}
    </div>
  );
}

function ThemeBtn({ dark, onToggle }) {
  return (
    <button type="button" onClick={onToggle} className="sat-iconbtn" title="Cambiar tema"
      style={{ width: 36, height: 36, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', background: 'var(--surface)',
        color: 'var(--muted-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
      <Icon name={dark ? 'sparkle' : 'eye'} size={17} />
    </button>
  );
}

function App({ mode, dark, cardVariant, onToggleTheme, store, user }) {
  const { searches, notifs, toggleSearch, markRead, markAll, saveSearch, deleteSearch } = store;
  const [tab, setTab] = React.useState('dashboard');
  const [overlay, setOverlay] = React.useState(null); // {type, id}
  const desktop = mode === 'desktop';
  const unread = notifs.filter((n) => !n.read).length;
  const scrollRef = React.useRef(null);

  // ── Estado de conexiones (MELI + Telegram) ──
  const [meliStatus, setMeliStatus] = React.useState(null);
  const [tgStatus, setTgStatus] = React.useState(null);
  React.useEffect(() => {
    apiFetch('/meli/status').then(setMeliStatus).catch(() => setMeliStatus(null));
    apiFetch('/telegram/status').then(setTgStatus).catch(() => setTgStatus(null));
  }, []);
  // Solo el admin (flashiando@gmail.com) puede configurar conexiones; el resto solo ve el estado.
  const isAdmin = !!(user && user.isAdmin);

  const go = (t) => { setOverlay(null); setTab(t); if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const openDetail = (id) => { setOverlay({ type: 'detail', id }); if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const openCreate = () => { setOverlay({ type: 'create' }); if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const openEdit = (id) => { setOverlay({ type: 'edit', id }); if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const goMeli = () => window.open('https://www.mercadolibre.com.ar', '_blank');

  const current = overlay ? null : tab;
  const selSearch = overlay ? searches.find((s) => s.id === overlay.id) : null;

  // ── pantallas ──
  let screen;
  if (overlay && overlay.type === 'detail' && selSearch) {
    screen = <Detail search={selSearch} notifs={notifs} mode={mode}
      onBack={() => setOverlay(null)} onEdit={() => openEdit(selSearch.id)} onToggle={() => toggleSearch(selSearch.id)}
      onDelete={() => { deleteSearch(selSearch.id); setOverlay(null); }} onGoMeli={goMeli} />;
  } else if (overlay && (overlay.type === 'create' || overlay.type === 'edit')) {
    screen = <CreateSearch initial={overlay.type === 'edit' ? selSearch : null} mode={mode}
      onCancel={() => setOverlay(null)} onSave={(s) => { saveSearch(s); setOverlay(null); setTab('dashboard'); }}
      onOpenTelegram={() => { setOverlay(null); setTab('telegram'); }} />;
  } else if (tab === 'dashboard') {
    screen = <Dashboard searches={searches} notifs={notifs} variant={cardVariant} mode={mode}
      onOpen={openDetail} onToggle={toggleSearch} onCreate={openCreate} />;
  } else if (tab === 'feed') {
    screen = <Feed notifs={notifs} searches={searches} mode={mode} onOpenSearch={openDetail}
      onMarkRead={markRead} onMarkAll={markAll} onGoMeli={goMeli} onOpenTelegram={() => go('telegram')} />;
  }

  const isTelegram = !overlay && tab === 'telegram';

  // ── NAV: tabs mobile ──
  const navItems = [
    { id: 'dashboard', icon: 'grid', label: 'Panel' },
    { id: 'feed', icon: 'bell', label: 'Alertas', badge: unread },
    { id: 'telegram', icon: 'send', label: 'Telegram' },
  ];

  const bottomBar = (
    <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-around',
      background: 'var(--surface)', borderTop: '1px solid var(--line)', padding: '8px 8px 24px', position: 'relative', zIndex: 5 }}>
      <TabBtn item={navItems[0]} active={current === 'dashboard'} onClick={() => go('dashboard')} />
      <TabBtn item={navItems[1]} active={current === 'feed'} onClick={() => go('feed')} />
      <button type="button" onClick={openCreate} style={{ width: 52, height: 52, borderRadius: 16, border: 'none', background: 'var(--signal)',
        color: 'var(--signal-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        boxShadow: '0 6px 16px var(--signal-glow)', marginTop: -14, flexShrink: 0 }}>
        <Icon name="plus" size={24} stroke={2.4} />
      </button>
      <TabBtn item={navItems[2]} active={current === 'telegram'} onClick={() => go('telegram')} />
      <TabBtn item={{ icon: 'sliders', label: 'Ajustes' }} active={false} onClick={() => {}} />
    </div>
  );

  // ── MOBILE LAYOUT ──
  if (!desktop) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', position: 'relative' }}>
        {isTelegram ? (
          <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
            <TelegramChat dark={dark} mode={mode} onBack={() => go('dashboard')} notifs={notifs} searches={searches} />
          </div>
        ) : (
          <>
            {/* top bar */}
            <div style={{ flexShrink: 0, paddingTop: 50, padding: '50px 16px 12px', background: 'var(--bg-bar)', backdropFilter: 'blur(10px)',
              borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative', zIndex: 5 }}>
              <BrandMark mode={mode} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <ThemeBtn dark={dark} onToggle={onToggleTheme} />
                <UserAvatar user={user} size={36} />
              </div>
            </div>
            <div ref={scrollRef} className="sat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '18px 16px 24px' }}>
              {!overlay && tab === 'dashboard' && (
                <div style={{ marginBottom: 16 }}>
                  <ConnectionsPanel meliStatus={meliStatus} tgStatus={tgStatus} isAdmin={isAdmin} />
                </div>
              )}
              {screen}
            </div>
          </>
        )}
        {!isTelegram && bottomBar}
      </div>
    );
  }

  // ── DESKTOP LAYOUT ──
  return (
    <div style={{ height: '100%', display: 'flex', background: 'var(--bg)' }}>
      {/* sidebar */}
      <div style={{ width: 248, flexShrink: 0, borderRight: '1px solid var(--line)', background: 'var(--bg-bar)',
        display: 'flex', flexDirection: 'column', padding: 18 }}>
        <div style={{ padding: '6px 8px 22px' }}><BrandMark size={32} mode={mode} /></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {navItems.map((it) => (
            <SideBtn key={it.id} item={it} active={current === it.id} onClick={() => go(it.id)} />
          ))}
        </div>
        <div style={{ marginTop: 18 }}>
          <Btn variant="primary" icon="plus" full onClick={openCreate}>Nueva búsqueda</Btn>
        </div>
        <div style={{ flex: 1 }} />
        <ConnectionsPanel meliStatus={meliStatus} tgStatus={tgStatus} isAdmin={isAdmin} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <UserAvatar user={user} size={34} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {user ? user.name : 'Usuario'}
            </div>
          </div>
          <ThemeBtn dark={dark} onToggle={onToggleTheme} />
        </div>
      </div>

      {/* main */}
      <div ref={scrollRef} className="sat-scroll" style={{ flex: 1, overflowY: 'auto', position: 'relative' }}>
        {isTelegram ? (
          <div style={{ minHeight: '100%', display: 'flex', alignItems: 'stretch', justifyContent: 'center', padding: 28, background: 'var(--bg-alt)' }}>
            <div style={{ width: 460, maxWidth: '100%', borderRadius: 'var(--r-xl)', overflow: 'hidden', position: 'relative',
              border: '1px solid var(--line)', boxShadow: 'var(--shadow-lg)', minHeight: 640 }}>
              <TelegramChat dark={dark} mode={mode} onBack={() => go('dashboard')} notifs={notifs} searches={searches} />
            </div>
          </div>
        ) : (
          <div style={{ maxWidth: 880, margin: '0 auto', padding: '30px 32px 48px' }}>{screen}</div>
        )}
      </div>
    </div>
  );
}

function TabBtn({ item, active, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{ background: 'transparent', border: 'none', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '4px 10px', position: 'relative', flex: 1, maxWidth: 70 }}>
      <span style={{ position: 'relative', color: active ? 'var(--ink)' : 'var(--muted-3)' }}>
        <Icon name={item.icon} size={22} fill={active ? 'var(--signal)' : 'none'} stroke={active ? 1.6 : 1.75} />
        {item.badge > 0 && <span style={{ position: 'absolute', top: -4, right: -7, minWidth: 15, height: 15, padding: '0 4px', borderRadius: 999,
          background: 'var(--alert)', color: '#fff', fontFamily: 'var(--font)', fontSize: 9.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{item.badge}</span>}
      </span>
      <span style={{ fontFamily: 'var(--font)', fontSize: 10.5, fontWeight: 600, color: active ? 'var(--ink)' : 'var(--muted-3)', letterSpacing: '-0.01em' }}>{item.label}</span>
    </button>
  );
}

function SideBtn({ item, active, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', borderRadius: 'var(--r-md)',
      border: 'none', cursor: 'pointer', background: active ? 'var(--surface)' : 'transparent', width: '100%', textAlign: 'left',
      boxShadow: active ? 'var(--shadow-sm)' : 'none', transition: 'background 150ms var(--ease)' }}>
      <span style={{ color: active ? 'var(--ink)' : 'var(--muted)' }}>
        <Icon name={item.icon} size={20} fill={active ? 'var(--signal)' : 'none'} />
      </span>
      <span style={{ flex: 1, fontFamily: 'var(--font)', fontSize: 14.5, fontWeight: 600, color: active ? 'var(--ink)' : 'var(--muted-2)', letterSpacing: '-0.01em' }}>{item.label}</span>
      {item.badge > 0 && <span style={{ minWidth: 20, height: 20, padding: '0 6px', borderRadius: 999, background: 'var(--alert)', color: '#fff',
        fontFamily: 'var(--font)', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{item.badge}</span>}
    </button>
  );
}

function UserAvatar({ user, size = 36 }) {
  if (user && user.picture) {
    return <img src={user.picture} alt={user.name || 'Usuario'} referrerPolicy="no-referrer"
      style={{ width: size, height: size, borderRadius: 999, objectFit: 'cover', border: '1px solid var(--line)', flexShrink: 0 }} />;
  }
  const initials = user && user.name ? user.name.charAt(0).toUpperCase() : 'U';
  return (
    <div style={{ width: size, height: size, borderRadius: 999, background: 'var(--surface-2)', border: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font)', fontWeight: 700,
      fontSize: Math.round(size * 0.4), color: 'var(--ink)', flexShrink: 0 }}>
      {initials}
    </div>
  );
}

// ── Panel de conexiones (MELI + Telegram) — siempre visible ───────────────────
function connBtnStyle(border, color) {
  return { width: '100%', marginTop: 9, padding: '7px 8px', borderRadius: 8, border: '1px solid ' + border,
    background: 'transparent', color, fontFamily: 'var(--font)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer' };
}

function ConnIconML({ size = 22 }) {
  // Marca de Mercado Libre: cuadrito amarillo con "ML" (sin depender de un ícono externo).
  return (
    <span style={{ width: size, height: size, borderRadius: 6, background: '#FFE600', color: '#2D3277',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      fontFamily: 'var(--mono)', fontSize: Math.round(size * 0.42), fontWeight: 700, letterSpacing: '-0.03em' }}>ML</span>
  );
}

function ServiceRow({ mark, name, dot, statusText, action }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {mark}
        <span style={{ fontFamily: 'var(--font)', fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{name}</span>
        <span style={{ flex: 1 }} />
        <span style={{ width: 8, height: 8, borderRadius: 999, background: dot, flexShrink: 0 }} />
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted)', marginTop: 5, lineHeight: 1.4 }}>{statusText}</div>
      {action}
    </div>
  );
}

function ConnectionsPanel({ meliStatus, tgStatus, isAdmin }) {
  // ── Mercado Libre ──
  const meliLoading = meliStatus === null;
  const meliConnected = !!(meliStatus && meliStatus.connected);
  const meliConfigured = !!(meliStatus && meliStatus.configured);
  const meliDot = meliLoading ? 'var(--muted-3)' : meliConnected ? 'var(--signal)' : 'var(--alert)';
  const meliText = meliLoading ? 'Verificando…'
    : meliConnected ? ('Conectado' + (isAdmin && meliStatus.userId ? ' · #' + meliStatus.userId : ''))
    : meliConfigured ? 'No conectado' : 'Sin configurar';
  let meliAction = null;
  if (isAdmin && !meliLoading && meliConfigured && !meliConnected) {
    meliAction = (
      <button type="button" onClick={() => { window.location.href = '/api/meli/connect'; }}
        style={connBtnStyle('var(--alert-line)', 'var(--alert-ink)')}>Conectar Mercado Libre</button>
    );
  } else if (isAdmin && meliConnected) {
    meliAction = (
      <button type="button" onClick={() => { window.location.href = '/api/meli/connect'; }}
        style={connBtnStyle('var(--line-strong)', 'var(--muted-2)')}>Reconectar</button>
    );
  }

  // ── Telegram ──
  const tgLoading = tgStatus === null;
  const tgConfigured = !!(tgStatus && tgStatus.configured);
  const tgLinked = !!(tgStatus && tgStatus.chatLinked);
  const tgUsername = (tgStatus && tgStatus.username) || 'SatmeliBot';
  const tgDot = tgLoading ? 'var(--muted-3)' : (tgConfigured && tgLinked) ? 'var(--signal)' : (tgConfigured ? '#F5A623' : 'var(--muted-3)');
  const tgText = tgLoading ? 'Verificando…'
    : !tgConfigured ? 'Sin configurar'
    : tgLinked ? 'Conectado · entregando alertas' : 'Falta vincular chat';
  let tgAction = null;
  if (isAdmin && tgConfigured && !tgLinked) {
    tgAction = (
      <a href={'https://t.me/' + tgUsername} target="_blank" rel="noreferrer"
        style={Object.assign(connBtnStyle('var(--line-strong)', 'var(--ink)'), { display: 'block', textAlign: 'center', textDecoration: 'none' })}>
        Abrir @{tgUsername}
      </a>
    );
  } else if (isAdmin && !tgConfigured) {
    tgAction = (
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--muted-3)', marginTop: 6, lineHeight: 1.4 }}>
        Falta cargar TELEGRAM_BOT_TOKEN en el servidor.
      </div>
    );
  }

  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: 13, marginBottom: 12 }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.12em', color: 'var(--muted-3)', marginBottom: 11 }}>CONEXIONES</div>
      <div style={{ marginBottom: 14 }}>
        <ServiceRow mark={<ConnIconML />} name="Mercado Libre" dot={meliDot} statusText={meliText} action={meliAction} />
      </div>
      <div style={{ height: 1, background: 'var(--line)', margin: '0 -13px 14px' }} />
      <ServiceRow
        mark={<span style={{ width: 22, height: 22, borderRadius: 6, background: '#229ED9', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="send" size={12} /></span>}
        name="Telegram" dot={tgDot} statusText={tgText} action={tgAction} />
    </div>
  );
}

Object.assign(window, { App, UserAvatar, ConnectionsPanel });
