// IndustryLanding.jsx — 9A: Sub-role chooser + partner access form
// localStorage: td_role_sub (partner sub-role)
// Routes to: #industry-detail (future) or #forms for access request
// Compliance: AB 3030, no PHI, no clinical claims

const { useState } = React;

const PARTNER_ROLES = [
  { slug: 'dso',        label: 'DSO / Group Practice', emoji: '🏢', desc: 'Multi-location dental organization', cta: 'Explore DSO Solutions' },
  { slug: 'insurer',    label: 'Insurance / Payer',     emoji: '🛡️', desc: 'Networks, eligibility, cost data', cta: 'Explore Payer Solutions' },
  { slug: 'supplier',   label: 'Supply Company',        emoji: '📦', desc: 'Distribution, procurement data', cta: 'Explore Supply Data' },
  { slug: 'edtech',     label: 'EdTech / CE Provider',  emoji: '🎓', desc: 'CE curriculum, platform integrations', cta: 'Explore CE Partnership' },
  { slug: 'technology', label: 'Technology Company',    emoji: '💻', desc: 'PMS, imaging, workflow integrations', cta: 'Explore Tech API' },
  { slug: 'employer',   label: 'Employer Benefits',     emoji: '🤝', desc: 'Corporate dental benefits, self-insured', cta: 'Explore Employer Tools' },
];

const AB3030 = 'AI-assisted content is disclosed under California AB 3030. Information only — not clinical or legal advice.';

function PartnerForm({ role, onSuccess }) {
  const [form, setForm] = useState({ name: '', company: '', email: '', message: '' });
  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.company || !form.email) { setErr('Please fill all required fields.'); return; }
    setStatus('loading');
    setErr('');
    try {
      const res = await fetch('/api/industry/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, partner_type: role }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Submission failed');
      setStatus('done');
      if (onSuccess) onSuccess();
    } catch (ex) {
      setErr(ex.message);
      setStatus('idle');
    }
  };

  if (status === 'done') return (
    <div className="card" style={{ textAlign: 'center', padding: 32 }}>
      <div style={{ fontSize: 36, marginBottom: 8 }}>✅</div>
      <h3 style={{ margin: '0 0 8px' }}>Request received</h3>
      <p style={{ color: 'var(--color-text-secondary)', fontSize: 14 }}>Our partnerships team will be in touch within 2 business days.</p>
    </div>
  );

  return (
    <form onSubmit={submit} className="field-stack">
      {err && <div className="error-banner">{err}</div>}
      <div>
        <label className="field-label">Your Name *</label>
        <input className="input" value={form.name} onChange={update('name')} placeholder="Full name" />
      </div>
      <div>
        <label className="field-label">Company / Organization *</label>
        <input className="input" value={form.company} onChange={update('company')} placeholder="Company name" />
      </div>
      <div>
        <label className="field-label">Work Email *</label>
        <input className="input" type="email" value={form.email} onChange={update('email')} placeholder="you@company.com" />
      </div>
      <div>
        <label className="field-label">What are you looking for?</label>
        <textarea className="input" rows={3} value={form.message} onChange={update('message')} placeholder="Brief description of your use case or question..." />
      </div>
      <button type="submit" className="btn btn-primary btn-block" disabled={status === 'loading'}>
        {status === 'loading' ? 'Sending…' : 'Request Partner Access →'}
      </button>
    </form>
  );
}

function IndustryLanding({ go }) {
  const [selected, setSelected] = useState(null);
  const [showForm, setShowForm] = useState(false);

  const choose = (role) => {
    setSelected(role);
    setShowForm(false);
    try { localStorage.setItem('td_role_sub', role.slug); } catch (_) {}
  };

  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 }}>
        ← Industry & Partners
      </button>
      <p style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--color-accent)', textTransform: 'uppercase', marginBottom: 8 }}>
        INDUSTRY PARTNERS
      </p>
      <h1 style={{ fontSize: 'clamp(1.25rem,4vw,1.75rem)', fontWeight: 700, margin: '0 0 4px' }}>
        Partner with TheDentist.ai
      </h1>
      <p className="section-subtitle" style={{ marginBottom: 24 }}>
        Data, distribution, and workflow integrations — built for verified dental industry partners.
      </p>

      {/* Role chooser */}
      {!selected && (
        <>
          <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>
            What describes you best?
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 12, marginBottom: 24 }}>
            {PARTNER_ROLES.map(r => (
              <div
                key={r.slug}
                className="card chooser-card-b5"
                style={{ cursor: 'pointer' }}
                onClick={() => choose(r)}
              >
                <div style={{ fontSize: 28 }}>{r.emoji}</div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{r.label}</div>
                <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>{r.desc}</div>
              </div>
            ))}
          </div>
        </>
      )}

      {/* Selected role detail */}
      {selected && (
        <div style={{ marginBottom: 24 }}>
          <button type="button" className="btn btn-ghost btn-sm" onClick={() => { setSelected(null); setShowForm(false); }} style={{ marginBottom: 16, paddingLeft: 0 }}>
            ← Change role
          </button>
          <div className="card" style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 36, marginBottom: 8 }}>{selected.emoji}</div>
            <h2 style={{ margin: '0 0 4px', fontSize: 18 }}>{selected.label}</h2>
            <p style={{ fontSize: 14, color: 'var(--color-text-secondary)', marginBottom: 16 }}>{selected.desc}</p>

            {/* Tailored CTAs */}
            {selected.slug === 'dso' && (
              <ul style={{ fontSize: 13, paddingLeft: 16, color: 'var(--color-text-secondary)', marginBottom: 16 }}>
                <li>Unified VPS dashboard across all locations</li>
                <li>Group recognition reporting</li>
                <li>Secure practice portal integration for multi-site</li>
              </ul>
            )}
            {selected.slug === 'insurer' && (
              <ul style={{ fontSize: 13, paddingLeft: 16, color: 'var(--color-text-secondary)', marginBottom: 16 }}>
                <li>Cost benchmark data by ZIP3 and procedure</li>
                <li>Provider network quality signals (de-identified)</li>
                <li>API access for eligibility cross-reference</li>
              </ul>
            )}
            {selected.slug === 'technology' && (
              <ul style={{ fontSize: 13, paddingLeft: 16, color: 'var(--color-text-secondary)', marginBottom: 16 }}>
                <li>Open API for practice data integration</li>
                <li>Webhook events for patient triage flow</li>
                <li>Co-marketing in SmileMentors CE catalog</li>
              </ul>
            )}

            {!showForm ? (
              <button type="button" className="btn btn-primary" onClick={() => setShowForm(true)}>
                {selected.cta} →
              </button>
            ) : (
              <PartnerForm role={selected.slug} onSuccess={() => setShowForm(false)} />
            )}
          </div>
        </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.
      </p>
    </div>
  );
}

window.IndustryLanding = IndustryLanding;
