// Survey.jsx — Post-visit satisfaction survey
//
// Accessible via #survey or #survey/<npi> (pre-fills practice).
// Collects the VPS-relevant dimensions: rating, communication, wait, value,
// recommendation. Submits to POST /api/survey, which writes to Supabase
// `surveys` table and fires an Encharge event when those env vars are bound.
//
// Privacy: no PHI collected. The survey is keyed by NPI (public provider ID)
// and a random visit token. "Your response helps assign Verified Performance
// Scores. It is never sold and never linked to your diagnosis."
//
// Compliance note: Asking patients about care quality is explicitly outside
// SB 1120 / AB 3030 clinical-content scope. This is satisfaction data, not
// clinical data. Still, we display the standard disclosure footer.

const { useState, useEffect, useRef } = React;

// ── Stars ────────────────────────────────────────────────────────────────────
function StarRow({ value, onChange, disabled }) {
  const [hover, setHover] = useState(0);
  const active = hover || value;
  return (
    <div style={{ display: 'flex', gap: 8 }} role="radiogroup" aria-label="Overall rating">
      {[1, 2, 3, 4, 5].map(n => (
        <button
          key={n}
          type="button"
          role="radio"
          aria-checked={value === n}
          aria-label={`${n} star${n > 1 ? 's' : ''}`}
          disabled={disabled}
          onMouseEnter={() => setHover(n)}
          onMouseLeave={() => setHover(0)}
          onClick={() => onChange(n)}
          style={{
            background: 'none', border: 'none', cursor: disabled ? 'default' : 'pointer',
            padding: 4, lineHeight: 1, fontSize: 40,
            color: n <= active ? '#F5A623' : 'var(--ink-5)',
            transition: 'color 0.1s, transform 0.1s',
            transform: n === active ? 'scale(1.15)' : 'scale(1)',
          }}
        >★</button>
      ))}
    </div>
  );
}

// ── Chip row (single-select) ──────────────────────────────────────────────────
function ChipRow({ label, options, value, onChange, disabled }) {
  return (
    <div style={{ marginBottom: 'var(--s-5)' }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {options.map(({ id, label: lbl }) => (
          <button
            key={id}
            type="button"
            disabled={disabled}
            onClick={() => onChange(id)}
            style={{
              padding: '8px 16px',
              borderRadius: 999,
              border: `1.5px solid ${value === id ? 'var(--ink-1)' : 'var(--ink-5)'}`,
              background: value === id ? 'var(--ink-1)' : 'var(--paper)',
              color: value === id ? 'var(--paper)' : 'var(--ink-2)',
              fontSize: 14, fontWeight: value === id ? 600 : 400,
              cursor: disabled ? 'default' : 'pointer',
              transition: 'all 0.15s',
            }}
          >{lbl}</button>
        ))}
      </div>
    </div>
  );
}

// ── Dimensions config ─────────────────────────────────────────────────────────
const DIMENSIONS = [
  {
    key: 'communication',
    label: 'How well did the team explain things?',
    options: [
      { id: 'excellent', label: 'Excellent — clear and thorough' },
      { id: 'good',      label: 'Good' },
      { id: 'fair',      label: 'Fair — some gaps' },
      { id: 'poor',      label: 'Needs improvement' },
    ],
  },
  {
    key: 'wait_time',
    label: 'Wait time (from appointment to being seen)',
    options: [
      { id: 'short',  label: 'Short — on time or early' },
      { id: 'ok',     label: 'Expected' },
      { id: 'long',   label: 'Longer than expected' },
      { id: 'very_long', label: 'Much longer' },
    ],
  },
  {
    key: 'value',
    label: 'Value for cost',
    options: [
      { id: 'excellent', label: 'Excellent value' },
      { id: 'fair',      label: 'Fair' },
      { id: 'poor',      label: 'Too expensive for what I received' },
      { id: 'na',        label: 'N/A — covered by insurance' },
    ],
  },
  {
    key: 'recommend',
    label: 'Would you recommend this dentist to a family member?',
    options: [
      { id: 'yes',     label: 'Yes — without hesitation' },
      { id: 'maybe',   label: 'Maybe' },
      { id: 'no',      label: 'Probably not' },
    ],
  },
];

const STAR_LABELS = { 1: 'Poor', 2: 'Below expectations', 3: 'Meets expectations', 4: 'Good', 5: 'Excellent' };

// ── Survey screen ─────────────────────────────────────────────────────────────
function Survey({ go, state, set, lang, setLang }) {
  // Parse NPI from hash fragment, e.g. #survey/1234567890
  const [npiFromHash, setNpiFromHash] = useState(() => {
    const h = (window.location.hash || '').replace('#', '');
    const parts = h.split('/');
    return parts.length > 1 ? parts[1] : '';
  });

  const dentist = state._selectedDentist || null;
  const practiceName = dentist?.practice || dentist?.name || '';
  const dentistName  = dentist?.name || '';
  const npi = dentist?.npi || npiFromHash || '';

  const [rating,  setRating]  = useState(0);
  const [dims,    setDims]    = useState({});   // { communication, wait_time, value, recommend }
  const [went,    setWent]    = useState('');
  const [improve, setImprove] = useState('');
  const [submitting, setSub]  = useState(false);
  const [done,    setDone]    = useState(false);
  const [error,   setError]   = useState('');
  const topRef = useRef(null);

  useEffect(() => {
    topRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, []);

  const setDim = (key, val) => setDims(d => ({ ...d, [key]: val }));

  const canSubmit = rating > 0 && !submitting && !done;

  const submit = async () => {
    if (!canSubmit) return;
    setSub(true);
    setError('');
    try {
      const payload = {
        npi: npi || undefined,
        practice_name: practiceName || undefined,
        dentist_name: dentistName || undefined,
        rating,
        dimensions: dims,
        went_well: went.trim() || undefined,
        could_improve: improve.trim() || undefined,
        audit_id: state._snapshot?.audit_id || undefined,
        // visit_token: a random ID so the same patient can't submit twice without
        // making it identifiable. We generate on the client.
        visit_token: 'vt_' + Math.random().toString(36).slice(2, 14),
      };
      const r = await fetch('/api/survey', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok || !d.ok) {
        setError(d.error || 'Could not submit right now — please try again.');
        setSub(false);
        return;
      }
      setDone(true);
    } catch (e) {
      setError('Network error — check your connection and try again.');
      setSub(false);
    }
  };

  // ── Thank-you state ──────────────────────────────────────────────────────
  if (done) {
    return (
      <div className="app">
        <Masthead lang={lang} setLang={setLang} go={go}/>
        <main style={{ minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--s-8) var(--s-6)' }}>
          <div style={{ maxWidth: 480, textAlign: 'center' }}>
            <div style={{ fontSize: 64, marginBottom: 'var(--s-4)' }}>🙏</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 32, margin: '0 0 var(--s-3)' }}>
              Thank you.
            </h1>
            <p style={{ fontSize: 16, color: 'var(--ink-2)', margin: '0 0 var(--s-6)', lineHeight: 1.6 }}>
              Your feedback helps us assign Verified Performance Scores — the methodology
              that helps other patients find dentists who do right by them.
            </p>
            {rating === 5 && (
              <div style={{ padding: 'var(--s-4)', background: 'var(--bone)', borderRadius: 'var(--r-4)', marginBottom: 'var(--s-6)', fontSize: 14, color: 'var(--ink-2)' }}>
                Exceptional experience? Consider leaving a Google review — it helps the practice
                and tells future patients what to expect.
              </div>
            )}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center' }}>
              <Button variant="primary" onClick={() => go('directory')}>Find another dentist</Button>
              <Button variant="secondary" onClick={() => go('landing')}>Back to home</Button>
            </div>
          </div>
        </main>
        <Footer go={go}/>
      </div>
    );
  }

  // ── Survey form ──────────────────────────────────────────────────────────
  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main className="container article" style={{ paddingTop: 'var(--s-8)', paddingBottom: 'var(--s-12)' }} ref={topRef}>
        <Breadcrumbs
          crumbs={[{ label: 'Home', screen: 'landing' }, { label: 'Find a dentist', screen: 'directory' }, { label: 'Rate your visit' }]}
          go={go}
        />

        <div style={{ maxWidth: 640, margin: '0 auto' }}>
          {/* Header */}
          <div style={{ marginBottom: 'var(--s-8)' }}>
            <div className="t-eyebrow" style={{ marginBottom: 'var(--s-2)' }}>Verified Performance Score</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.1, margin: '0 0 var(--s-3)' }}>
              How was your visit?
            </h1>
            {(practiceName || dentistName) && (
              <p style={{ fontSize: 16, color: 'var(--ink-2)', margin: '0 0 var(--s-2)' }}>
                {practiceName && <span style={{ fontWeight: 600, color: 'var(--ink-1)' }}>{practiceName}</span>}
                {practiceName && dentistName && <span style={{ color: 'var(--ink-3)' }}> · </span>}
                {dentistName && <span>{dentistName}</span>}
              </p>
            )}
            <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: 0, lineHeight: 1.55 }}>
              Your response helps us assign a Verified Performance Score to this practice.
              It is never sold and never linked to your diagnosis. Takes &lt;2 minutes.
            </p>
          </div>

          {/* Star rating */}
          <div style={{ marginBottom: 'var(--s-8)', padding: 'var(--s-6)', background: 'var(--bone)', borderRadius: 'var(--r-5)' }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 'var(--s-3)' }}>
              Overall experience
            </div>
            <StarRow value={rating} onChange={setRating} disabled={submitting}/>
            {rating > 0 && (
              <div style={{ marginTop: 10, fontSize: 14, fontWeight: 600, color: 'var(--ink-1)' }}>
                {STAR_LABELS[rating]}
              </div>
            )}
          </div>

          {/* Dimension chips */}
          {DIMENSIONS.map(({ key, label, options }) => (
            <ChipRow
              key={key}
              label={label}
              options={options}
              value={dims[key] || ''}
              onChange={v => setDim(key, v)}
              disabled={submitting}
            />
          ))}

          {/* Free text */}
          <div style={{ marginBottom: 'var(--s-5)' }}>
            <label
              htmlFor="survey-went"
              style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.06em' }}
            >
              What went well? (optional)
            </label>
            <textarea
              id="survey-went"
              value={went}
              onChange={e => setWent(e.target.value.slice(0, 1200))}
              disabled={submitting}
              rows={3}
              placeholder="Friendly team, thorough explanation, easy parking…"
              style={{
                width: '100%', boxSizing: 'border-box',
                padding: '12px 14px',
                border: '1px solid var(--ink-5)', borderRadius: 'var(--r-3)',
                fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-1)',
                background: 'var(--paper)', resize: 'vertical', lineHeight: 1.55,
              }}
            />
          </div>

          <div style={{ marginBottom: 'var(--s-6)' }}>
            <label
              htmlFor="survey-improve"
              style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.06em' }}
            >
              What could be better? (optional)
            </label>
            <textarea
              id="survey-improve"
              value={improve}
              onChange={e => setImprove(e.target.value.slice(0, 1200))}
              disabled={submitting}
              rows={3}
              placeholder="Longer appointment slots, clearer billing, shorter wait…"
              style={{
                width: '100%', boxSizing: 'border-box',
                padding: '12px 14px',
                border: '1px solid var(--ink-5)', borderRadius: 'var(--r-3)',
                fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-1)',
                background: 'var(--paper)', resize: 'vertical', lineHeight: 1.55,
              }}
            />
          </div>

          {/* Error */}
          {error && (
            <div style={{ padding: 'var(--s-3) var(--s-4)', background: '#FFF0EE', border: '1px solid var(--alert)', borderRadius: 'var(--r-3)', marginBottom: 'var(--s-4)', fontSize: 14, color: 'var(--alert)' }}>
              {error}
            </div>
          )}

          {/* Submit */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
            <Button
              variant="primary"
              size="md"
              onClick={submit}
              disabled={!canSubmit}
              style={{ minWidth: 180 }}
            >
              {submitting ? 'Submitting…' : 'Submit feedback'}
            </Button>
            {!rating && (
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>Select a star rating to continue</span>
            )}
          </div>

          {/* Compliance footer */}
          <div style={{ marginTop: 'var(--s-8)', paddingTop: 'var(--s-4)', borderTop: '1px solid var(--ink-5)', fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6 }}>
            <strong style={{ color: 'var(--ink-2)' }}>About VPS surveys:</strong> Responses are aggregated across patients
            and weighted according to the{' '}
            <a href="/methodology/" style={{ color: 'var(--ink-2)' }}>published methodology</a>.
            No personally identifiable information is stored with your rating.
            This is satisfaction data, not clinical data — it does not affect your care.
            TheDentist.ai does not share individual survey responses with the practice; only aggregated
            score changes are reflected in the directory.
          </div>
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

// ── Export ────────────────────────────────────────────────────────────────────
window.Survey = Survey;
