// TriageCard.jsx — One decision-tree step: prompt, controls, explicit buttons (no swipe gestures).
// Cards render per `kind`: yesno | severity | chips | teeth | info.
const { useState: useTCs } = React;

function TriageCard({ card, value, onChange, onAnswer, onBack, canBack, mode = 'patient' }) {
  const [error, setError] = useTCs('');

  const submit = (direction, capturedValue) => {
    if (card.kind === 'severity' && direction === 'yes') {
      if (typeof capturedValue !== 'number') {
        setError('Move the slider to continue.');
        return;
      }
    }
    if (card.kind === 'chips' && direction === 'yes') {
      const empty = card.multi
        ? !Array.isArray(capturedValue) || capturedValue.length === 0
        : capturedValue == null || capturedValue === '';
      if (empty && !card.optional) {
        setError('Pick at least one option to continue.');
        return;
      }
    }
    setError('');
    onAnswer && onAnswer(direction, capturedValue);
  };

  const primaryLabel = card.kind === 'info' ? 'Continue' : 'Next';
  const showYesNo = card.kind === 'yesno';
  const showPrimary = card.kind !== 'yesno';

  return (
    <article
      className="triage-card triage-card--patient"
      aria-labelledby={`triage-prompt-${card.id}`}
    >
      <div className="t-eyebrow" style={{ marginBottom: 0 }}>
        {mode === 'clinician' ? 'Clinician triage' : 'Quick triage'}
      </div>
      <h2
        id={`triage-prompt-${card.id}`}
        className="triage-card-title"
      >
        {card.prompt}
      </h2>
      {card.sub && (
        <p style={{ margin: 0, color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.55 }}>{card.sub}</p>
      )}

      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: 6 }}>
        <CardBody card={card} value={value} onChange={onChange} />
      </div>

      {error && (
        <p role="alert" style={{ margin: 0, color: 'var(--alert)', fontSize: 13, textAlign: 'center' }}>{error}</p>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {showYesNo && (
          <div role="group" aria-label="Answer" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            <button type="button" className="btn btn-secondary btn-sm" onClick={() => submit('no')}>No</button>
            <button type="button" className="btn btn-tertiary btn-sm" onClick={() => submit('skip')}>Skip</button>
            <button type="button" className="btn btn-primary btn-sm" onClick={() => submit('yes')}>Yes</button>
          </div>
        )}
        {showPrimary && (
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {card.kind !== 'info' && (
              <button type="button" className="btn btn-tertiary btn-sm" onClick={() => submit('skip')}>Skip</button>
            )}
            <button
              type="button"
              className="btn btn-primary"
              style={{ flex: 1, minWidth: 140 }}
              onClick={() => submit(card.kind === 'info' ? 'skip' : 'yes', value)}
            >
              {primaryLabel} →
            </button>
          </div>
        )}
        {canBack && (
          <button
            type="button"
            className="bc-link"
            style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--ink-3)', fontSize: 13, alignSelf: 'center' }}
            onClick={onBack}
          >
            ← Back
          </button>
        )}
      </div>
    </article>
  );
}

function CardBody({ card, value, onChange }) {
  if (card.kind === 'yesno' || card.kind === 'info') {
    return (
      <div style={{ color: 'var(--ink-3)', fontSize: 13, textAlign: 'center' }}>
        {card.kind === 'info' ? 'Review the note above, then continue.' : 'Choose Yes, No, or Skip below.'}
      </div>
    );
  }
  if (card.kind === 'severity') {
    const v = typeof value === 'number' ? value : (card.min ?? 0);
    return (
      <div style={{ width: '100%' }}>
        <input
          type="range"
          min={card.min ?? 0}
          max={card.max ?? 10}
          value={v}
          onChange={(e) => onChange && onChange(+e.target.value)}
          style={{ width: '100%' }}
          aria-label="Severity 0 to 10"
        />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>
          <span>none</span>
          <span style={{ fontWeight: 700, color: 'var(--ink-1)', fontSize: 22 }}>{v}</span>
          <span>worst</span>
        </div>
      </div>
    );
  }
  if (card.kind === 'chips') {
    const multi = !!card.multi;
    const selected = multi ? (Array.isArray(value) ? value : []) : value;
    const toggle = (slug) => {
      if (!onChange) return;
      if (multi) {
        const arr = Array.isArray(value) ? value : [];
        onChange(arr.includes(slug) ? arr.filter((x) => x !== slug) : [...arr, slug]);
      } else {
        onChange(slug);
      }
    };
    return (
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center' }}>
        {(card.chips || []).map((c) => {
          const on = multi ? selected.includes(c.slug) : selected === c.slug;
          return (
            <button
              key={c.slug}
              type="button"
              onClick={() => toggle(c.slug)}
              aria-pressed={on}
              style={{
                padding: '8px 14px',
                borderRadius: 999,
                fontSize: 13,
                fontWeight: 500,
                cursor: 'pointer',
                background: on ? 'var(--ink-1)' : 'var(--paper)',
                color: on ? 'var(--paper)' : 'var(--ink-1)',
                border: `1px solid ${on ? 'var(--ink-1)' : 'var(--ink-5)'}`,
              }}
            >
              {c.label}
            </button>
          );
        })}
      </div>
    );
  }
  if (card.kind === 'teeth') {
    const data = value && typeof value === 'object' ? value : {};
    const teeth = Object.keys(data).map((n) => +n);
    const update = ({ teeth: t, toothPain: tp }) => {
      const next = {};
      t.forEach((n) => { next[n] = tp[n] ?? 5; });
      onChange && onChange(next);
    };
    if (window.ToothChart) {
      return (
        <div style={{ width: '100%' }}>
          <window.ToothChart teeth={teeth} toothPain={data} onChange={update} size="sm" />
        </div>
      );
    }
    return <div style={{ color: 'var(--ink-3)' }}>Tooth chart loading…</div>;
  }
  return null;
}

window.TriageCard = TriageCard;

function EmergencyOverlay({ open, onDismiss, go }) {
  if (!open) return null;
  return (
    <div
      className="emergency-backdrop"
      role="alertdialog"
      aria-labelledby="td-emergency-title"
      aria-modal="true"
    >
      <div className="emergency-modal">
        <h2 id="td-emergency-title">
          <span aria-hidden="true">⚠️ </span>URGENT: This may be a dental emergency.
        </h2>
        <p>
          For severe pain, swelling spreading to face or neck, difficulty breathing, or jaw trauma:
          call 911 or go to an emergency room immediately. Then contact a dentist.
        </p>
        <div className="actions">
          <a
            href="tel:911"
            className="btn btn-alert btn-block"
            style={{ textAlign: 'center', textDecoration: 'none' }}
          >
            Call 911
          </a>
          <button
            type="button"
            className="btn btn-alert-out btn-block"
            onClick={() => { onDismiss && onDismiss(); go && go('directory'); }}
          >
            Find Emergency Dentist Near Me
          </button>
          <button
            type="button"
            className="btn btn-ghost btn-sm"
            style={{ alignSelf: 'center', marginTop: 4 }}
            onClick={() => onDismiss && onDismiss()}
          >
            I understand — continue triage
          </button>
        </div>
        <p className="t-fine" style={{ marginTop: 16, marginBottom: 0, fontSize: 12, color: 'var(--mut)' }}>
          Information, not diagnosis — confirm with a licensed dentist.
        </p>
      </div>
    </div>
  );
}

window.EmergencyOverlay = EmergencyOverlay;
