// ResearcherHub.jsx — 9E part 2: De-identified data request, methodology, API preview
// Compliance: AB 3030, no PHI, de-identified only

const { useState } = React;

const AB3030 = 'AI-assisted content is disclosed under California AB 3030. For research purposes — not clinical advice or diagnosis.';

const DATASETS = [
  { id: 'cost', name: 'Cost Benchmarks by ZIP3', desc: 'Median, 25th, 75th percentile for 50+ CDT codes by ZIP3. FAIR Health-anchored, quarterly updates.', status: 'Available', format: 'CSV / API' },
  { id: 'vps', name: 'VPS Performance Signals', desc: 'De-identified practice quality axes (anxious-friendly, continuity, multilingual, etc.) without PII.', status: 'Application required', format: 'API / JSON' },
  { id: 'triage', name: 'Triage Pattern Data', desc: 'Aggregated decision-tree pathways (anonymized, no patient identifiers). Batch export available.', status: 'In progress', format: 'CSV' },
  { id: 'geo', name: 'Geographic Access Index', desc: 'Practice density, VPS distribution, and insurance acceptance by ZIP3 and state.', status: 'Q3 2026', format: 'CSV / API' },
];

const API_PREVIEW = `// GET /api/research/cost?zip3=941&cdt=D1110
{
  "zip3": "941",
  "cdt": "D1110",
  "procedure": "Adult Prophylaxis",
  "median": 128,
  "p25": 98,
  "p75": 165,
  "sample_size": "masked (n>30)",
  "methodology": "https://thedentist.ai/methodology/",
  "version": "2026.05"
}`;

function ResearcherRequestForm() {
  const [form, setForm] = useState({ name: '', institution: '', email: '', role: '', datasets: '', purpose: '', irb: '' });
  const [status, setStatus] = useState('idle');
  const [err, setErr] = useState('');
  const update = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.purpose) { setErr('Name, email, and purpose are required.'); return; }
    setStatus('loading'); setErr('');
    try {
      const res = await fetch('/api/researcher/request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      setStatus('done');
    } catch (ex) { setErr(ex.message); setStatus('idle'); }
  };

  if (status === 'done') return (
    <div className="card" style={{ textAlign: 'center', padding: 24 }}>
      <div style={{ fontSize: 32, marginBottom: 8 }}>✅</div>
      <p>Access request received. Our data team reviews applications within 5 business days.</p>
    </div>
  );

  return (
    <form onSubmit={submit} className="field-stack">
      {err && <div className="error-banner">{err}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div><label className="field-label">Name *</label><input className="input" value={form.name} onChange={update('name')} /></div>
        <div><label className="field-label">Institution</label><input className="input" value={form.institution} onChange={update('institution')} /></div>
      </div>
      <div><label className="field-label">Email *</label><input className="input" type="email" value={form.email} onChange={update('email')} /></div>
      <div>
        <label className="field-label">Role</label>
        <select className="input" value={form.role} onChange={update('role')}>
          <option value="">Select...</option>
          {['Academic Researcher', 'Public Health Official', 'Graduate Student', 'Government / Policy', 'Nonprofit / NGO', 'Journalist (data)', 'Other'].map(r => <option key={r}>{r}</option>)}
        </select>
      </div>
      <div>
        <label className="field-label">Datasets requested</label>
        <input className="input" value={form.datasets} onChange={update('datasets')} placeholder="e.g. Cost Benchmarks, VPS Signals" />
      </div>
      <div>
        <label className="field-label">Research purpose *</label>
        <textarea className="input" rows={3} value={form.purpose} onChange={update('purpose')} placeholder="Describe your research question and how you plan to use the data..." />
      </div>
      <div>
        <label className="field-label">IRB approval number (if applicable)</label>
        <input className="input" value={form.irb} onChange={update('irb')} placeholder="IRB-XXXX or N/A" />
      </div>
      <button type="submit" className="btn btn-primary btn-block" disabled={status === 'loading'}>
        {status === 'loading' ? 'Sending…' : 'Request Data Access →'}
      </button>
    </form>
  );
}

function ResearcherHub({ go }) {
  const [showApi, setShowApi] = useState(false);

  return (
    <div className="gap-screen animate-fade-in-up" style={{ maxWidth: 720, margin: '0 auto', padding: '24px 16px' }}>
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => go?.('other')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Stakeholders
      </button>
      <p style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--color-accent)', textTransform: 'uppercase', marginBottom: 8 }}>
        RESEARCHER HUB
      </p>
      <h1 style={{ fontSize: 'clamp(1.25rem,4vw,1.75rem)', fontWeight: 700, margin: '0 0 4px' }}>
        Data for Research &amp; Public Health
      </h1>
      <p className="section-subtitle" style={{ marginBottom: 24 }}>
        De-identified cost, quality, and access data for academic and public-health research.
      </p>

      {/* Data disclaimer */}
      <div className="disclaimer-banner" style={{ marginBottom: 16 }}>
        <strong>Data Policy:</strong> All datasets are de-identified. No patient PII, no practice-identifiable data below n=30 threshold, no PHI of any kind. HIPAA de-identification standard (Safe Harbor method) applied.
      </div>

      {/* Available datasets */}
      <h2 style={{ fontSize: 15, fontWeight: 700, marginBottom: 12 }}>Available Datasets</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
        {DATASETS.map(d => (
          <div key={d.id} className="card">
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>{d.name}</div>
                <p style={{ fontSize: 13, color: 'var(--color-text-secondary)', margin: '0 0 6px' }}>{d.desc}</p>
                <div style={{ display: 'flex', gap: 6 }}>
                  <span className={`badge ${d.status === 'Available' ? 'badge-green' : d.status === 'In progress' ? 'badge-yellow' : d.status.includes('2026') ? 'badge-gray' : 'badge-blue'}`} style={{ fontSize: 11 }}>{d.status}</span>
                  <span className="badge badge-gray" style={{ fontSize: 11 }}>{d.format}</span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* API preview */}
      <div className="card" style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <h2 style={{ fontSize: 15, fontWeight: 700, margin: 0 }}>API Preview</h2>
          <button type="button" className="btn btn-ghost btn-sm" onClick={() => setShowApi(!showApi)}>
            {showApi ? 'Hide' : 'Show example'}
          </button>
        </div>
        {showApi && (
          <pre style={{ background: 'var(--color-surface-raised)', padding: 12, borderRadius: 8, fontSize: 11, overflowX: 'auto', margin: 0 }}>
            {API_PREVIEW}
          </pre>
        )}
        <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginTop: 8 }}>
          Full API access granted on approved requests. Rate-limited. No sample-size below n=30.
        </p>
      </div>

      {/* Methodology */}
      <div className="card" style={{ marginBottom: 16, display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ fontSize: 24 }}>📘</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 14 }}>Recognition Methodology 2026.05</div>
          <p style={{ fontSize: 13, color: 'var(--color-text-secondary)', margin: 0 }}>Full VPS scoring model available for peer review.</p>
        </div>
        <a href="/methodology/" className="btn btn-ghost btn-sm">View →</a>
      </div>

      {/* Request form */}
      <div className="card" style={{ marginBottom: 16 }}>
        <h2 style={{ fontSize: 15, fontWeight: 700, marginBottom: 12 }}>Data Access Request</h2>
        <ResearcherRequestForm />
      </div>

      <div className="disclaimer-banner">{AB3030}</div>
      <p style={{ fontSize: 11, color: 'var(--color-text-tertiary)', marginTop: 8 }}>
        TheDentist<em>.ai</em> · Smile Mentors Inc. · research@thedentist.ai
      </p>
    </div>
  );
}

window.ResearcherHub = ResearcherHub;
