// Real bridge — talks to the Flask backend via fetch and SSE.

function createBridge({ onLog, onState, onResp, onInboundSMS, onInboundCall,
                       onChatCreated, onSmsOut, onSmsOutStatus, onCleared,
                       onReady }) {

  // ── REST helpers ───────────────────────────────────────────────────

  async function api(path, opts = {}) {
    const method = opts.method || 'GET';
    const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' };
    const r = await fetch(path, {
      method,
      headers,
      body: opts.body ? JSON.stringify(opts.body) : undefined,
    });
    if (!r.ok) {
      const text = await r.text();
      throw new Error(`${r.status} ${text}`);
    }
    return r.json();
  }

  const cmd = (command) => api('/api/cmd', { method: 'POST', body: { command } });

  // ── Bootstrap ──────────────────────────────────────────────────────

  async function bootstrap() {
    const data = await api('/api/bootstrap');
    onReady?.(data);
    return data;
  }

  // ── SSE event stream ───────────────────────────────────────────────

  function startStream() {
    const es = new EventSource('/api/events');
    es.addEventListener('state',          e => onState?.(JSON.parse(e.data)));
    es.addEventListener('response',       e => onResp?.(JSON.parse(e.data)));
    es.addEventListener('log',            e => onLog?.(JSON.parse(e.data)));
    es.addEventListener('sms_in',         e => onInboundSMS?.(JSON.parse(e.data)));
    es.addEventListener('call_in',        e => onInboundCall?.(JSON.parse(e.data)));
    es.addEventListener('sms_out',        e => onSmsOut?.(JSON.parse(e.data)));
    es.addEventListener('sms_out_status', e => onSmsOutStatus?.(JSON.parse(e.data)));
    es.addEventListener('chat_upserted',  e => onChatCreated?.(JSON.parse(e.data)));
    es.addEventListener('cleared',        () => onCleared?.());
    es.onerror = () => { /* browser auto-retries */ };
    return es;
  }

  return {
    bootstrap,
    startStream,
    connect:    () => cmd('connect'),
    disconnect: () => cmd('disconnect'),
    setup:      () => cmd('setup'),
    status:     () => cmd('status'),
    reset:      () => cmd('reset'),
    sendSMS:    (number, message) => api('/api/sms',
                                         { method: 'POST', body: { number, message } }),
    createChat: (number, name)    => api('/api/chats',
                                         { method: 'POST', body: { number, name } }),
    clearAll:   () => api('/api/chats/clear', { method: 'POST' }),
  };
}

window.createBridge = createBridge;
