/* global React */
// =======================================================================
// BlazeConnector Admin v3 — Gate de conexión + chip de estado
// Pantalla inicial para conectar el UI a un backend BlazeConnector real
// (base URL + X-Admin-Token), o entrar en modo demo (mocks).
// =======================================================================
const { useState: _cs, useEffect: _ce } = React;

function ConnectGate() {
  const bc = window.useBC();
  const cfg = window.BC.getConfig();
  const [baseUrl, setBaseUrl] = _cs((cfg && cfg.baseUrl) || 'http://localhost:8080');
  const [token, setToken] = _cs((cfg && cfg.token) || '');
  const [testing, setTesting] = _cs(false);
  const [test, setTest] = _cs(null);   // { ok:bool, msg:string }
  const [busy, setBusy] = _cs(false);

  // Visible mientras no estemos conectados y el usuario no haya elegido demo.
  const visible = bc.status !== 'connected' && !bc.demoChosen;
  if (!visible) return null;

  async function doTest() {
    setTesting(true); setTest(null);
    try {
      const n = await window.BC.test(baseUrl, token);
      setTest({ ok: true, msg: 'Conexión OK · ' + n + ' tenant(s) visibles' });
    } catch (e) {
      setTest({ ok: false, msg: e.message || 'Falló la conexión' });
    } finally { setTesting(false); }
  }

  async function doConnect() {
    setBusy(true); setTest(null);
    try {
      await window.BC.connect(baseUrl, token);
      // status pasa a 'connected' → el gate se oculta solo.
    } catch (e) {
      setTest({ ok: false, msg: e.message || 'Falló la conexión' });
    } finally { setBusy(false); }
  }

  const connecting = bc.status === 'connecting' || busy;

  return (
    <div className="modal-mask" style={{ alignItems: 'center' }}>
      <div className="modal" style={{ maxWidth: 460 }} onClick={(e) => e.stopPropagation()}>
        <header className="modal-head">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span className="sb-mark" style={{ width: 34, height: 34 }}><span style={{ fontSize: 9 }}>BLAZE</span></span>
            <div>
              <h2 className="modal-title">Conectar a BlazeConnector</h2>
              <p className="modal-sub" style={{ margin: 0 }}>Panel de administración · v3</p>
            </div>
          </div>
        </header>
        <div className="modal-body">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--app-fg2)' }}>Base URL del API</span>
              <input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="http://localhost:8080"
                style={inputStyle} />
            </label>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--app-fg2)' }}>Admin Token <span style={{ color: 'var(--app-fg3)', fontWeight: 400 }}>· X-Admin-Token</span></span>
              <input value={token} onChange={(e) => setToken(e.target.value)} type="password" placeholder="••••••••••••••••"
                onKeyDown={(e) => { if (e.key === 'Enter' && token) doConnect(); }}
                style={Object.assign({}, inputStyle, { fontFamily: 'var(--font-mono)' })} />
            </label>

            {test && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', borderRadius: 6, fontSize: 12,
                background: test.ok ? 'var(--st-success-bg)' : 'var(--st-danger-bg)',
                border: '1px solid ' + (test.ok ? 'rgba(46,204,90,0.3)' : 'rgba(224,62,62,0.3)'),
                color: test.ok ? 'var(--st-success-fg)' : 'var(--st-danger-fg)'
              }}>
                <window.Icon name={test.ok ? 'circle-check' : 'circle-x'} size={14} />
                <span>{test.msg}</span>
              </div>
            )}

            <div style={{ fontSize: 11, color: 'var(--app-fg3)', lineHeight: 1.5 }}>
              El token queda solo en <span className="mono">localStorage</span> de este navegador. Para local usa el
              <span className="mono"> ADMIN_TOKEN</span> de tu <span className="mono">.env</span>.
            </div>
          </div>
        </div>
        <footer className="modal-actions" style={{ justifyContent: 'space-between' }}>
          <button className="btn btn-ghost" onClick={() => window.BC.demo()} disabled={connecting}>
            <window.Icon name="flask-conical" size={12} /> Modo demo
          </button>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-secondary" onClick={doTest} disabled={!baseUrl || !token || testing || connecting}>
              {testing ? 'Probando…' : 'Probar'}
            </button>
            <button className="btn btn-primary" onClick={doConnect} disabled={!baseUrl || !token || connecting}>
              <window.Icon name="plug" size={12} /> {connecting ? 'Conectando…' : 'Conectar'}
            </button>
          </div>
        </footer>
      </div>
    </div>
  );
}

const inputStyle = {
  background: 'var(--app-input-bg)', border: '1px solid var(--app-border)', borderRadius: 6,
  padding: '9px 11px', color: 'var(--app-fg1)', fontFamily: 'inherit', fontSize: 13
};

// Chip de estado en el Topbar: live / demo / connecting / error.
function ConnectionChip() {
  const bc = window.useBC();
  const [open, setOpen] = _cs(false);
  const ref = React.useRef(null);
  _ce(() => {
    if (!open) return;
    const fn = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn);
    return () => document.removeEventListener('mousedown', fn);
  }, [open]);

  const map = {
    connected:    { tone: '',            lbl: 'live',        ico: 'plug' },
    connecting:   { tone: 'is-degraded', lbl: 'conectando…', ico: 'loader' },
    error:        { tone: 'is-down',     lbl: 'error',       ico: 'circle-x' },
    disconnected: { tone: 'is-degraded', lbl: 'demo',        ico: 'flask-conical' }
  };
  const m = bc.mode === 'demo' && bc.status !== 'connecting'
    ? { tone: 'is-degraded', lbl: 'demo', ico: 'flask-conical' }
    : (map[bc.status] || map.disconnected);

  return (
    <div style={{ position: 'relative' }} ref={ref}>
      <button className={'tb-realtime ' + m.tone} title={'Backend: ' + (bc.baseUrl || 'mocks')} onClick={() => setOpen((o) => !o)} style={{ cursor: 'pointer' }}>
        <span className="tb-realtime-dot"></span>
        <span style={{ fontWeight: 600 }}>{m.lbl}</span>
      </button>
      {open && (
        <div className="popover" style={{ top: 34, right: 0, minWidth: 240 }}>
          <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--app-divider)' }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--app-fg1)' }}>
              {bc.mode === 'live' ? 'Conectado (live)' : 'Modo demo (mocks)'}
            </div>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--app-fg3)', marginTop: 2, wordBreak: 'break-all' }}>
              {bc.baseUrl || 'datos de ejemplo · sin backend'}
            </div>
            {bc.error && <div style={{ fontSize: 11, color: 'var(--st-danger-fg)', marginTop: 4 }}>{bc.error}</div>}
          </div>
          {bc.mode === 'live'
            ? <button className="popover-item" style={popItem} onClick={() => { setOpen(false); window.BC.disconnect(); }}>
                <window.Icon name="unplug" size={13} /> <span>Desconectar</span>
              </button>
            : <button className="popover-item" style={popItem} onClick={() => { setOpen(false); window.bcStore.setState({ demoChosen: false }); }}>
                <window.Icon name="plug" size={13} /> <span>Conectar a backend…</span>
              </button>}
        </div>
      )}
    </div>
  );
}
const popItem = { background: 'none', border: 'none', width: '100%', textAlign: 'left' };

Object.assign(window, { ConnectGate, ConnectionChip });
