// IndustryLanding.jsx — 9A: Partner hub with td_role_sub-tailored CTAs
// Route: #industry · POST /api/industry/lead → industry_leads
// Compliance: AB 3030, AB 489 (information not diagnosis), no PHI

const { useState, useEffect } = React;

const AB3030 =
  'AI-assisted content is disclosed under California AB 3030. Information only — not clinical, legal, or insurance advice. Confirm material claims with a licensed professional.';

/** Slugs align with teaser industry sub-roles (td_role_sub). */
const PARTNER_ROLES = [
  { slug: 'software', label: 'PMS / SaaS vendor', emoji: '💻', desc: 'Practice management, imaging, and workflow software.' },
  { slug: 'devtools', label: 'Dental app developer', emoji: '🛠️', desc: 'APIs, plugins, and developer tools for dental workflows.' },
  { slug: 'supplier', label: 'Equipment & materials', emoji: '📦', desc: 'Distribution, procurement, and B2B catalog listings.' },
  { slug: 'insurance', label: 'Insurance / payer', emoji: '🛡️', desc: 'Carrier networks, eligibility, and cost transparency.' },
  { slug: 'recruiter', label: 'Recruiter / staffing', emoji: '👥', desc: 'Dental hiring, PRN, and Smile Mentors job board.' },
  { slug: 'marketing', label: 'Marketing agency', emoji: '📣', desc: 'GEO, SEO, and practice presence add-ons.' },
  { slug: 'consult', label: 'Practice consultant', emoji: '📊', desc: 'Coaching, operations, and Dentist Apprentice OS packages.' },
  { slug: 'lender', label: 'Lender / financing', emoji: '🏦', desc: 'Practice acquisition and equipment financing referrals.' },
  { slug: 'legal', label: 'Legal / compliance', emoji: '⚖️', desc: 'Contracts, M&A, and regulatory counsel referrals.' },
  { slug: 'accounting', label: 'Accounting / CFO', emoji: '🧮', desc: 'Bookkeeping, RCM advisory, and referral partnerships.' },
  { slug: 'otc', label: 'OTC / consumer products', emoji: '🛒', desc: 'Marketplace listing and storefront distribution.' },
];

const ROLE_CONTENT = {
  software: {
    bullets: ['Open API for directory and triage events', 'Webhook integrations with Practice Suite', 'Co-marketing in verified partner directory'],
    primary: { label: 'Explore tech & API docs', href: '/for-dentists/', external: true },
    secondary: { label: 'Request API partnership', action: 'form' },
  },
  devtools: {
    bullets: ['Developer sandbox and schema docs', 'GitHub-style dental app listings', 'OAuth-scoped practice integrations'],
    primary: { label: 'Explore tech & API docs', href: '/for-dentists/', external: true },
    secondary: { label: 'Request API partnership', action: 'form' },
  },
  supplier: {
    bullets: ['B2B supplier profile in verified directory', 'Practice procurement signals (de-identified)', 'Co-branded CE and product education'],
    primary: { label: 'Request B2B listing', action: 'form' },
    secondary: { label: 'View marketplace', screen: 'marketplace' },
  },
  insurance: {
    hitl: true,
    bullets: ['Carrier partnership intake (human review before any claims language)', 'ZIP3 cost benchmark cross-reference', 'Eligibility API pilot (Stedi-compatible)'],
    primary: { label: 'Carrier partnership form', action: 'form', hitl: true },
    secondary: null,
  },
  recruiter: {
    bullets: ['Smile Mentors job board listings', 'PRN and hygiene recall matching', 'Verified practice employer profiles'],
    primary: { label: 'Open job board', screen: 'jobs' },
    secondary: { label: 'Post a role', screen: 'jobs-post' },
  },
  marketing: {
    bullets: ['Dentist Apprentice OS GEO/SEO add-ons ($149–$1,499/mo tiers)', 'ZIP3-exclusivity marketing packages', 'Payment-independent VPS wall — spend never affects scores'],
    primary: { label: 'View marketing packages', screen: 'marketplace' },
    secondary: { label: 'Request partner access', action: 'form' },
  },
  consult: {
    bullets: ['Dentist Apprentice OS advisory modules', 'Practice DNA analytics for clients', 'White-label triage and cost tools'],
    primary: { label: 'Apprentice OS overview', href: 'https://dentistapprentice.com/', external: true },
    secondary: { label: 'Request partner access', action: 'form' },
  },
  lender: {
    bullets: ['Referral partner intake for qualified practices', 'De-identified performance context only', 'No credit decisions on-platform'],
    primary: { label: 'Referral partner form', action: 'form' },
    secondary: null,
  },
  legal: {
    bullets: ['Referral partner intake for dental practices', 'Compliance documentation requests', 'M&A and contract workflow handoffs'],
    primary: { label: 'Referral partner form', action: 'form' },
    secondary: null,
  },
  accounting: {
    bullets: ['Referral partner intake for RCM and CFO services', 'Benchmark Council-reviewed billing education', 'No PHI in partner workflows'],
    primary: { label: 'Referral partner form', action: 'form' },
    secondary: null,
  },
  otc: {
    bullets: ['Marketplace listing request for consumer SKUs', 'Practice-branded OTC storefront pilots', 'Compliance-reviewed product claims only'],
    primary: { label: 'Marketplace listing request', action: 'form' },
    secondary: { label: 'Browse marketplace', screen: 'marketplace' },
  },
};

function readSubRole() {
  if (window.TDRoleSub?.read) return window.TDRoleSub.read();
  try {
    return (localStorage.getItem('td_role_sub') || '').trim().toLowerCase();
  } catch {
    return '';
  }
}

function writeSubRole(slug) {
  if (window.TDRoleSub?.set) window.TDRoleSub.set(slug);
  else {
    try {
      localStorage.setItem('td_role_sub', slug);
    } catch (_) {}
  }
}

function roleBySlug(slug) {
  return PARTNER_ROLES.find((r) => r.slug === slug) || null;
}

function PartnerForm({ roleSlug, hitl, 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.email) {
      setErr('Name and work email are required.');
      return;
    }
    setStatus('loading');
    setErr('');
    try {
      const res = await fetch('/api/industry/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          company: form.company,
          email: form.email,
          message: form.message,
          partner_type: roleSlug,
          hitl: !!hitl,
          source_path: '/#industry',
        }),
      });
      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 session-empty">
        <div className="session-success-icon" aria-hidden="true">✅</div>
        <h3 style={{ margin: '0 0 8px' }}>Request received</h3>
        <p className="session-text-sm" style={{ fontSize: 14 }}>
          {hitl
            ? 'Partnership requests involving insurance or clinical claims are reviewed by a licensed human before follow-up.'
            : 'Our partnerships team will be in touch within 2 business days.'}
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="field-stack">
      {hitl && (
        <div className="disclaimer-banner" style={{ marginBottom: 8, fontSize: 12 }}>
          <strong>Human review required (SB 1120 / HITL):</strong> Insurance and carrier partnership inquiries are not auto-approved. A licensed reviewer validates any clinical or network claims before we respond.
        </div>
      )}
      {err && (window.ErrorRetry
        ? <ErrorRetry message={err} onRetry={() => { setErr(''); setStatus('idle'); }} retryLabel="Try again" />
        : <div className="error-banner" role="alert">{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 partnership idea or integration…"
        />
      </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);

  useEffect(() => {
    const sub = readSubRole();
    if (!sub) return;
    const match = roleBySlug(sub) || roleBySlug(sub === 'insurer' ? 'insurance' : sub);
    if (match) setSelected(match);
  }, []);

  const choose = (role) => {
    setSelected(role);
    setShowForm(false);
    writeSubRole(role.slug);
  };

  const content = selected ? ROLE_CONTENT[selected.slug] || ROLE_CONTENT.supplier : null;

  const runCta = (cta) => {
    if (!cta) return;
    if (cta.action === 'form') {
      setShowForm(true);
      return;
    }
    if (cta.screen && go) {
      go(cta.screen);
      return;
    }
    if (cta.href) {
      if (cta.external) window.open(cta.href, '_blank', 'noopener,noreferrer');
      else window.location.href = cta.href;
    }
  };

  return (
    <div className="session-screen gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('other')} aria-label="Back to stakeholders">
        ← Stakeholders
      </button>
      <p className="session-eyebrow">VERIFIED · INDEPENDENT · NO PAID PLACEMENT</p>
      <h1 className="session-title">Partner with the Verified Dental Network</h1>
      <p className="section-subtitle session-subtitle">
        Data, distribution, and workflow integrations — built for verified dental industry partners. VPS recognition is positive-only and payment-independent.
      </p>

      {!selected && (
        <>
          <p className="session-label" style={{ marginBottom: 12 }}>What describes you best?</p>
          <div className="session-card-grid" style={{ marginBottom: 24 }}>
            {PARTNER_ROLES.map((r) => (
              <div key={r.slug} className="card chooser-card-b5 session-chooser-card" role="button" tabIndex={0} aria-label={r.label} onClick={() => choose(r)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); choose(r); } }}>
                <div className="session-chooser-emoji" aria-hidden="true">{r.emoji}</div>
                <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--txt)' }}>{r.label}</div>
                <div className="session-muted" style={{ fontSize: 12 }}>{r.desc}</div>
              </div>
            ))}
          </div>
        </>
      )}

      {selected && content && (
        <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 className="session-text-sm" style={{ fontSize: 14, marginBottom: 16 }}>{selected.desc}</p>

            {content.hitl && (
              <div className="disclaimer-banner" style={{ marginBottom: 12, fontSize: 12 }}>
                Carrier and network partnership claims require human review (HITL) before any public or contractual language is shared.
              </div>
            )}

            <ul className="session-text-sm" style={{ paddingLeft: 16, marginBottom: 16 }}>
              {content.bullets.map((b) => (
                <li key={b}>{b}</li>
              ))}
            </ul>

            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: showForm || content.primary?.action === 'form' ? 0 : 8 }}>
              {content.primary && content.primary.action !== 'form' && (
                <button type="button" className="btn btn-primary" onClick={() => runCta(content.primary)}>
                  {content.primary.label} →
                </button>
              )}
              {content.secondary && (
                <button type="button" className="btn btn-secondary" onClick={() => runCta(content.secondary)}>
                  {content.secondary.label} →
                </button>
              )}
            </div>

            {(showForm || content.primary?.action === 'form') && (
              <div style={{ marginTop: 16, borderTop: '1px solid var(--line)', paddingTop: 16 }}>
                <PartnerForm roleSlug={selected.slug} hitl={content.hitl || content.primary?.hitl} />
              </div>
            )}

            {!showForm && content.primary?.action !== 'form' && (
              <button type="button" className="btn btn-ghost btn-sm" style={{ marginTop: 12 }} onClick={() => setShowForm(true)}>
                Request Partner Access →
              </button>
            )}
          </div>
        </div>
      )}

      <div className="disclaimer-banner">{AB3030}</div>
      <p className="session-footnote">
        TheDentist<em>.ai</em> · Smile Mentors Inc. ·{' '}
        <a href="/methodology/" className="methodology-link">Methodology →</a>
      </p>
    </div>
  );
}

window.IndustryLanding = IndustryLanding;
