// 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 WhyWeAsk({ card, mode }) {
  const [open, setOpen] = useTCs(false);
  if (mode === 'clinician') return null;

  const lens = card?.patient_lens
    || (window.PatientLens && window.PatientLens.resolvePatientLens
      ? window.PatientLens.resolvePatientLens(card, null, card?.id)
      : null);
  if (!lens) return null;

  const layers = [
    { key: 'what_we_heard', label: 'What we heard' },
    { key: 'what_we_thinking', label: 'What we\'re thinking' },
    { key: 'what_this_step_does', label: 'What this step does' },
    { key: 'what_happens_next', label: 'What happens next' },
  ];

  const renderValue = (key) => {
    const v = lens[key];
    if (!v) return null;
    if (key === 'what_happens_next') {
      if (typeof v === 'string') return v;
      if (window.PatientLens?.formatHappensNext) return window.PatientLens.formatHappensNext(lens);
      return v.text || '';
    }
    return String(v);
  };

  const hasContent = layers.some((l) => renderValue(l.key));
  if (!hasContent) return null;

  return (
    <details
      className="triage-why-ask"
      open={open}
      onToggle={(e) => setOpen(e.target.open)}
      style={{
        marginTop: 8,
        padding: '10px 12px',
        borderRadius: 10,
        border: '1px solid var(--line, #e0e0e0)',
        background: 'var(--panel2, rgba(0,0,0,.03))',
        fontSize: 13,
        lineHeight: 1.5,
      }}
    >
      <summary
        style={{ cursor: 'pointer', fontWeight: 600, color: 'var(--ink-2, #444)', listStyle: 'none' }}
      >
        Why we ask this
      </summary>
      <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {layers.map((l) => {
          const text = renderValue(l.key);
          if (!text) return null;
          return (
            <div key={l.key}>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3, #666)', marginBottom: 2 }}>
                {l.label}
              </div>
              <p style={{ margin: 0, color: 'var(--ink-2, #333)' }}>{text}</p>
            </div>
          );
        })}
        <p style={{ margin: 0, fontSize: 11, color: 'var(--ink-3, #666)' }}>
          {lens._compliance || 'Information, not diagnosis — confirm with a licensed dentist.'}
        </p>
      </div>
    </details>
  );
}

function ConditionGuidePanel({ mode, history, card }) {
  const [open, setOpen] = useTCs(false);
  if (mode === 'clinician') return null;

  const narr = window.DecisionTreeEngine?.getConditionNarrative?.(mode)
    || window.ConditionNarrative?.extractPublicConditionNarrative?.(window.DecisionTreeEngine?.seed?.(mode));
  if (!narr?.condition_title && !narr?.condition_narrative) return null;

  const tree = window.DecisionTreeEngine?.seed?.(mode);
  const pathTaken = (history?.length && window.ConditionNarrative?.buildPathNarrative)
    ? window.ConditionNarrative.buildPathNarrative(tree, history, card?.id)
    : null;

  return (
    <details
      open={open}
      onToggle={(e) => setOpen(e.target.open)}
      style={{
        marginBottom: 12,
        padding: '12px 14px',
        borderRadius: 10,
        border: '1px solid var(--line, #e0e0e0)',
        background: 'var(--panel2, rgba(0,0,0,.03))',
        fontSize: 13,
        lineHeight: 1.55,
      }}
    >
      <summary style={{ cursor: 'pointer', fontWeight: 600, color: 'var(--ink-2, #444)', listStyle: 'none' }}>
        About this condition &amp; how we guide you
      </summary>
      <div style={{ marginTop: 10 }}>
        {narr.condition_title ? (
          <h3 style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 600 }}>{narr.condition_title}</h3>
        ) : null}
        {narr.condition_narrative ? (
          <p style={{ margin: '0 0 10px', color: 'var(--ink-2)' }}>{narr.condition_narrative}</p>
        ) : null}
        {narr.path_to_conclusion ? (
          <>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', marginBottom: 4 }}>
              How this decision tree works
            </div>
            <p style={{ margin: '0 0 10px', color: 'var(--ink-2)' }}>{narr.path_to_conclusion}</p>
          </>
        ) : null}
        {pathTaken?.paragraphs?.length > 1 ? (
          <>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', marginBottom: 4 }}>
              Path you took so far
            </div>
            <p style={{ margin: '0 0 10px', color: 'var(--ink-2)' }}>
              {pathTaken.paragraphs.slice(1, -1).join(' ')}
            </p>
          </>
        ) : null}
        <p style={{ margin: 0, fontSize: 11, color: 'var(--ink-3)' }}>
          AI-assisted information (AB 3030): {narr.clinical_framing || 'Possible explanations only — confirm with a licensed dentist.'}
        </p>
      </div>
    </details>
  );
}

function OutcomeSummary({ card, mode, history }) {
  if (mode === 'clinician' || !card) return null;
  const isOutcome = card.node_role === 'outcome'
    || (card.kind === 'info' && !(card.branches && card.branches._next));
  if (!isOutcome && !card.outcome_narrative) return null;

  const tree = window.DecisionTreeEngine?.seed?.(mode);
  const pathTaken = window.ConditionNarrative?.buildPathNarrative
    ? window.ConditionNarrative.buildPathNarrative(tree, history || [], card.id)
    : null;

  const body = card.outcome_narrative
    || (pathTaken?.paragraphs?.length ? pathTaken.paragraphs[pathTaken.paragraphs.length - 2] : null);
  if (!body) return null;

  return (
    <div
      role="note"
      style={{
        marginTop: 10,
        padding: '12px 14px',
        borderRadius: 10,
        border: '1px solid var(--seal, #2a9d6a)',
        background: 'var(--bone, #f7f5f0)',
        fontSize: 13,
        lineHeight: 1.55,
      }}
    >
      <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', marginBottom: 6 }}>
        Where this path leads
      </div>
      <p style={{ margin: 0, color: 'var(--ink-2)' }}>{body}</p>
      <p style={{ margin: '8px 0 0', fontSize: 11, color: 'var(--ink-3)' }}>
        Information, not diagnosis — confirm with a licensed dentist.
      </p>
    </div>
  );
}

function TriageCard({ card, value, onChange, onAnswer, onBack, canBack, mode = 'patient', history = [] }) {
  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>
      )}

      <WhyWeAsk card={card} mode={mode} />
      <OutcomeSummary card={card} mode={mode} history={history} />

      <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;
