/**
 * ConsoltoConsent.jsx — CA Penal Code §632 consent modal (Bundle 2B)
 * Shared gate before Consolto embed or voice capture. Uses td_voice_consent (ISO date).
 */
const { useState, useCallback } = React;

const CONSENT_KEY = 'td_voice_consent';
const AB3030 =
  'AI-assisted chat is disclosed under California AB 3030. Information only — not a clinical diagnosis. Confirm with a licensed dentist.';

function sessionToken() {
  try {
    let t = sessionStorage.getItem('td_session_token');
    if (!t) {
      t = (typeof crypto !== 'undefined' && crypto.randomUUID)
        ? crypto.randomUUID()
        : `s_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
      sessionStorage.setItem('td_session_token', t);
    }
    return t;
  } catch {
    return `s_${Date.now()}`;
  }
}

async function logConsentCapture() {
  try {
    await fetch('/api/consolto-consent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        session_token: sessionToken(),
        consent_type: 'video_ca_632',
        ca_penal_632_captured: true,
        consent: true,
        surface: 'consolto',
        channel: 'consolto',
        sb1120_hitl_required: false,
      }),
    });
  } catch (_) {
    /* non-blocking — localStorage is primary gate */
  }
}

function ConsoltoConsent({ onConsent, onTextOnly, compact }) {
  const [busy, setBusy] = useState(false);

  const grant = useCallback(async () => {
    setBusy(true);
    try {
      localStorage.setItem(CONSENT_KEY, new Date().toISOString());
    } catch (_) {}
    await logConsentCapture();
    setBusy(false);
    if (typeof onConsent === 'function') onConsent();
  }, [onConsent]);

  const deny = useCallback(() => {
    try { localStorage.removeItem(CONSENT_KEY); } catch (_) {}
    if (typeof onTextOnly === 'function') onTextOnly();
  }, [onTextOnly]);

  return React.createElement(
    'div',
    {
      className: compact ? 'consolto-consent' : 'consolto-consent preview-banner',
      role: 'dialog',
      'aria-labelledby': 'consolto-consent-title',
      'aria-describedby': 'consolto-consent-desc',
    },
    React.createElement('p', {
      id: 'consolto-consent-desc',
      className: 'disclaimer-banner',
      style: { fontSize: 12, marginBottom: 12 },
    }, AB3030),
    React.createElement('strong', { id: 'consolto-consent-title' }, 'Recording consent (California)'),
    React.createElement('p', { style: { margin: '8px 0 12px', fontSize: 14, lineHeight: 1.5 } },
      'This session may be recorded. California law requires your consent before live audio or video. By continuing you consent to this session. We do not retain raw audio after transcription (zero retention policy).'
    ),
    React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
      React.createElement('button', {
        type: 'button',
        className: 'btn btn-primary',
        disabled: busy,
        onClick: grant,
      }, busy ? 'Starting…' : 'I Consent — Start Chat'),
      React.createElement('button', {
        type: 'button',
        className: 'btn btn-secondary',
        disabled: busy,
        onClick: deny,
      }, 'No, use text-only'),
    ),
  );
}

function ConsoltoTextOnlyForm({ onBack }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [status, setStatus] = useState('');
  const [err, setErr] = useState('');
  const [sending, setSending] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    setStatus('');
    if (!email.trim() || !message.trim()) {
      setErr('Email and message are required.');
      return;
    }
    setSending(true);
    try {
      const resp = await fetch('/api/portal/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          form_id: 'consolto-text-only',
          fields: { yourname: name.trim(), inquiry_email: email.trim(), comments: message.trim() },
        }),
      });
      const d = await resp.json().catch(() => ({}));
      if (!resp.ok || d.ok === false) {
        setErr(d.error || 'Could not send your message. Try again or call the practice.');
        return;
      }
      setStatus('Message sent. The practice will reply by email — no recording was used.');
      setName('');
      setEmail('');
      setMessage('');
    } catch {
      setErr('Network error. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return React.createElement(
    'form',
    { className: 'consolto-text-only card', onSubmit: submit, style: { marginTop: 12 } },
    React.createElement('p', { className: 'section-subtitle', style: { marginBottom: 12 } },
      'Text-only contact — no live audio or video. Do not include medical record numbers or other identifiers.'
    ),
    React.createElement('label', { className: 'form-label' }, 'Your name (optional)'),
    React.createElement('input', {
      type: 'text',
      className: 'form-control',
      value: name,
      maxLength: 120,
      onChange: (ev) => setName(ev.target.value),
      autoComplete: 'name',
    }),
    React.createElement('label', { className: 'form-label', style: { marginTop: 8 } }, 'Email'),
    React.createElement('input', {
      type: 'email',
      className: 'form-control',
      value: email,
      required: true,
      maxLength: 200,
      onChange: (ev) => setEmail(ev.target.value),
      autoComplete: 'email',
    }),
    React.createElement('label', { className: 'form-label', style: { marginTop: 8 } }, 'Message'),
    React.createElement('textarea', {
      className: 'form-control',
      rows: 4,
      value: message,
      required: true,
      maxLength: 2000,
      onChange: (ev) => setMessage(ev.target.value),
    }),
    err && React.createElement('p', { className: 'emergency-banner', style: { fontSize: 13 } }, err),
    status && React.createElement('p', { className: 'disclaimer-banner', style: { fontSize: 13 } }, status),
    React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' } },
      React.createElement('button', { type: 'submit', className: 'btn btn-primary', disabled: sending },
        sending ? 'Sending…' : 'Send message'),
      onBack && React.createElement('button', {
        type: 'button',
        className: 'btn btn-ghost btn-sm',
        onClick: onBack,
      }, '← Back to consent'),
    ),
  );
}

ConsoltoConsent.CONSENT_KEY = CONSENT_KEY;
ConsoltoConsent.hasConsent = function hasConsent() {
  try { return !!localStorage.getItem(CONSENT_KEY); } catch { return false; }
};
ConsoltoConsent.clearConsent = function clearConsent() {
  try { localStorage.removeItem(CONSENT_KEY); } catch (_) {}
};

window.ConsoltoConsent = ConsoltoConsent;
window.ConsoltoTextOnlyForm = ConsoltoTextOnlyForm;
