/**
 * ConsoltoWidget.jsx — HIPAA video/chat with CA Penal Code §632 consent gate (Bundle 2B)
 * Loads Consolto ONLY after ConsoltoConsent. Recording disabled via /api/consolto-settings.
 */
const { useState, useEffect, useRef, useCallback } = React;

const ConsentModal = window.ConsoltoConsent;
const TextOnlyForm = window.ConsoltoTextOnlyForm;
const CONSENT_KEY = ConsentModal?.CONSENT_KEY || 'td_voice_consent';
const SCRIPT_ID = 'consolto-widget-loader';

function loadConsoltoScript(roomId, widgetId) {
  if (document.getElementById(SCRIPT_ID)) return;
  const s = document.createElement('script');
  s.id = SCRIPT_ID;
  s.src = 'https://app.consolto.com/widgetApp/widgetLoader.js';
  s.async = true;
  const id = roomId || widgetId;
  if (id) s.setAttribute('data-room-id', id);
  if (widgetId && widgetId !== id) s.setAttribute('data-widget-id', widgetId);
  document.body.appendChild(s);
}

function removeConsoltoScript() {
  const el = document.getElementById(SCRIPT_ID);
  if (el) el.remove();
  document.querySelectorAll('[id^="consolto"]').forEach((n) => n.remove());
}

function resolveRoomId(roomIdProp, config) {
  if (roomIdProp) return roomIdProp;
  if (config?.roomIdDefault) return config.roomIdDefault;
  if (config?.widgetId) return config.widgetId;
  return null;
}

function ConsoltoWidget({ roomId: roomIdProp, onClose }) {
  const [phase, setPhase] = useState(() => {
    try {
      return localStorage.getItem(CONSENT_KEY) ? 'active' : 'consent';
    } catch {
      return 'consent';
    }
  });
  const [textOnly, setTextOnly] = useState(false);
  const [config, setConfig] = useState(null);
  const [error, setError] = useState('');
  const handlerRef = useRef(null);
  const roomId = resolveRoomId(roomIdProp, config);

  const clearConsent = useCallback(() => {
    if (ConsentModal?.clearConsent) ConsentModal.clearConsent();
    else {
      try { localStorage.removeItem(CONSENT_KEY); } catch (_) {}
    }
  }, []);

  useEffect(() => {
    let cancelled = false;
    fetch('/api/consolto-config')
      .then((r) => r.json())
      .then((d) => { if (!cancelled) setConfig(d); })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    handlerRef.current = (event) => {
      if (event?.data?.type === 'session_ended' || event?.data === 'session_ended') {
        clearConsent();
        removeConsoltoScript();
        setPhase('consent');
        setTextOnly(false);
        if (typeof onClose === 'function') onClose();
      }
    };
    window.addEventListener('message', handlerRef.current);
    return () => {
      window.removeEventListener('message', handlerRef.current);
      removeConsoltoScript();
    };
  }, [clearConsent, onClose]);

  useEffect(() => {
    if (phase !== 'active' || textOnly) return;
    const id = resolveRoomId(roomIdProp, config);
    if (!id) {
      setError('No Consolto room configured. Set CONSOLTO_WIDGET_ID in operator env.');
      setPhase('consent');
      return;
    }
    loadConsoltoScript(id, config?.widgetId);
  }, [phase, textOnly, roomIdProp, config]);

  const startFromStoredConsent = useCallback(() => {
    const id = resolveRoomId(roomIdProp, config);
    if (!id) {
      setError('No Consolto room configured for this practice.');
      return;
    }
    setError('');
    setTextOnly(false);
    setPhase('active');
  }, [roomIdProp, config]);

  if (textOnly) {
    return React.createElement('div', { className: 'consolto-widget animate-fade-in-up', style: { marginTop: 16 } },
      TextOnlyForm
        ? React.createElement(TextOnlyForm, { onBack: () => setTextOnly(false) })
        : React.createElement('p', null, 'Text-only contact is unavailable.'),
    );
  }

  if (phase === 'consent') {
    if (!ConsentModal) {
      return React.createElement('div', { className: 'consolto-widget' },
        React.createElement('p', null, 'Consent module failed to load.'),
      );
    }
    return React.createElement('div', { className: 'consolto-widget animate-fade-in-up', style: { marginTop: 16 } },
      React.createElement(ConsentModal, {
        onConsent: startFromStoredConsent,
        onTextOnly: () => { clearConsent(); setTextOnly(true); },
      }),
      error && React.createElement('p', { className: 'emergency-banner', style: { fontSize: 13, fontWeight: 500 } }, error),
      config && !config.configured && React.createElement('p', {
        className: 'disclaimer-banner',
        style: { fontSize: 12, marginTop: 8 },
      }, 'Consolto widget ID not bound in production yet — operator: see DOCS/consolto_setup.md'),
    );
  }

  return React.createElement('div', { className: 'consolto-widget-active animate-fade-in-up', style: { marginTop: 16 } },
    React.createElement('div', { className: 'disclaimer-banner' },
      'AI-assisted video chat — information, not diagnosis. Confirm with a licensed dentist.'
    ),
    React.createElement('div', { id: 'consolto-widget-mount', 'data-room-id': roomId || '' }),
    React.createElement('button', {
      type: 'button',
      className: 'btn btn-ghost',
      style: { marginTop: 8 },
      onClick: () => {
        clearConsent();
        removeConsoltoScript();
        setPhase('consent');
        if (typeof onClose === 'function') onClose();
      },
    }, 'End session'),
  );
}

window.ConsoltoWidget = ConsoltoWidget;
