// SmileMentors.jsx — Dental career hub: JobBoard, JobPost, CeHub
// Routes: #smile-mentors (hub), #jobs (board), #jobs-post (post a job), #ce-hub (CE courses)
// Compliance: AB 3030, no PHI, Pickaxe placeholders for paid flows

const { useState, useEffect } = React;

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

function openPickaxePayment(embedKey, title, desc) {
  if (window.PickaxeEmbeds?.openEmbed?.(embedKey, title, desc)) return true;
  if (window.PickaxeEmbeds?.showEmailFallback) {
    window.PickaxeEmbeds.showEmailFallback(title, desc);
    return true;
  }
  return false;
}

const ROLES = [
  { slug: 'rdh',     label: 'Registered Dental Hygienist', emoji: '🦷', desc: 'Prophylaxis, scaling, patient ed' },
  { slug: 'da',      label: 'Dental Assistant',             emoji: '🩺', desc: 'Chairside support, x-rays, sterilization' },
  { slug: 'tc',      label: 'Treatment Coordinator',        emoji: '📋', desc: 'Case acceptance, patient financing' },
  { slug: 'om',      label: 'Office Manager',               emoji: '🏥', desc: 'Operations, team lead, compliance' },
  { slug: 'billing', label: 'Dental Biller',                emoji: '💳', desc: 'Claims, EOBs, AR collections' },
  { slug: 'student', label: 'Dental Student',               emoji: '🎓', desc: 'Externship, residency, first job' },
];

const SEED_JOBS = [
  { id: 1, title: 'Registered Dental Hygienist', practice: 'Pacific Oral Care', city: 'San Francisco, CA', type: 'Full-time', pay: '$48–$58/hr', posted: '2 days ago', role: 'rdh' },
  { id: 2, title: 'Dental Assistant — Ortho', practice: 'Bay Area Family Dentistry', city: 'Oakland, CA', type: 'Part-time', pay: '$22–$28/hr', posted: '5 days ago', role: 'da' },
  { id: 3, title: 'Treatment Coordinator', practice: 'Sunrise Dental Group', city: 'San Jose, CA', type: 'Full-time', pay: '$26–$34/hr', posted: '1 week ago', role: 'tc' },
  { id: 4, title: 'Dental Biller / RCM Specialist', practice: 'West Coast Dental MSO', city: 'Remote', type: 'Full-time', pay: '$25–$32/hr', posted: '3 days ago', role: 'billing' },
  { id: 5, title: 'Office Manager — Multi-site', practice: 'Golden Gate Dental', city: 'San Francisco, CA', type: 'Full-time', pay: '$65k–$85k/yr', posted: '1 week ago', role: 'om' },
  { id: 6, title: 'RDH — Per Diem / PRN', practice: 'Various SF Practices', city: 'San Francisco, CA', type: 'PRN', pay: '$52–$60/hr', posted: 'Today', role: 'rdh' },
];

const CE_COURSES = [
  { id: 1, title: 'OSHA Compliance for the Dental Team', credits: 2, provider: 'ADA CERP', price: 49, category: 'Compliance' },
  { id: 2, title: 'Perio Maintenance: Updated Protocols', credits: 3, provider: 'ADHA Approved', price: 79, category: 'Clinical' },
  { id: 3, title: 'Implant Foundations for the DA', credits: 2, provider: 'PACE Approved', price: 59, category: 'Clinical' },
  { id: 4, title: 'Insurance Coding & Documentation', credits: 3, provider: 'DANB', price: 69, category: 'Business' },
  { id: 5, title: 'Case Acceptance Psychology', credits: 1, provider: 'PACE Approved', price: 39, category: 'Business' },
  { id: 6, title: 'Infection Control Update 2026', credits: 2, provider: 'ADA CERP', price: 49, category: 'Compliance' },
];

// ─── CeHub (shared between SmileMentors + Marketplace) ───────────────────────
function CeHub({ go, embedded }) {
  const courseList = (
    <div style={{ display: 'grid', gap: 12 }}>
      {CE_COURSES.map(c => (
        <div key={c.id} className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{c.title}</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <span className="badge badge-blue" style={{ fontSize: 11 }}>{c.credits} CE credit{c.credits > 1 ? 's' : ''}</span>
              <span className="badge badge-gray" style={{ fontSize: 11 }}>{c.provider}</span>
              <span className="badge badge-gray" style={{ fontSize: 11 }}>{c.category}</span>
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div className="session-price">${c.price}</div>
            <button type="button" className="btn btn-primary btn-sm" style={{ marginTop: 6 }}
              onClick={() => openPickaxePayment('ce_enroll', `Enroll: ${c.title}`, `CE enrollment for "${c.title}" — ${c.credits} credit(s), $${c.price}.`) || window.open('https://pickaxe.com', '_blank', 'noopener')}>
              Enroll
            </button>
          </div>
        </div>
      ))}
    </div>
  );

  if (embedded) {
    return (
      <div>
        <p className="session-text-xs" style={{ marginBottom: 12 }}>
          ADA CERP · ADHA · PACE-approved continuing education for dental professionals.
        </p>
        {courseList}
      </div>
    );
  }

  return (
    <div className="session-screen gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('smile-mentors')} aria-label="Back to Smile Mentors">
        ← Smile Mentors
      </button>
      <p className="session-eyebrow">SMILE MENTORS · CE HUB</p>
      <h1 className="session-title">Continuing Education</h1>
      <p className="section-subtitle session-subtitle">ADA CERP · ADHA · PACE-approved courses for dental professionals.</p>

      {courseList}

      <div className="disclaimer-banner" style={{ marginTop: 24 }}>{AB3030}</div>
    </div>
  );
}

// ─── JobPost ─────────────────────────────────────────────────────────────────
function JobPost({ go }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({ title: '', role: '', type: 'Full-time', pay: '', city: '', practice: '', contact: '' });
  const update = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const steps = ['Job Details', 'Contact & Pay', 'Post & Pay'];

  return (
    <div className="session-screen gap-screen animate-fade-in-up" style={{ maxWidth: 600 }}>
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('jobs')} aria-label="Back to job board">
        ← Job Board
      </button>
      <h1 className="session-title">Post a Job</h1>
      <p className="section-subtitle session-subtitle">Reach {'>'}2,000 verified dental professionals in the Smile Mentors network.</p>

      {/* Step indicator */}
      <div className="step-indicator" style={{ marginBottom: 24 }}>
        {steps.map((s, i) => (
          <React.Fragment key={i}>
            <div className={`step-dot ${i === step ? 'active' : i < step ? 'completed' : 'pending'}`}>{i < step ? '✓' : i + 1}</div>
            {i < steps.length - 1 && <div className="step-connector" />}
          </React.Fragment>
        ))}
      </div>

      {step === 0 && (
        <div className="field-stack">
          <div>
            <label className="field-label">Job Title</label>
            <input className="input" value={form.title} onChange={update('title')} placeholder="e.g. Registered Dental Hygienist" />
          </div>
          <div>
            <label className="field-label">Role Category</label>
            <select className="input" value={form.role} onChange={update('role')}>
              <option value="">Select a role...</option>
              {ROLES.map(r => <option key={r.slug} value={r.slug}>{r.label}</option>)}
            </select>
          </div>
          <div>
            <label className="field-label">Employment Type</label>
            <select className="input" value={form.type} onChange={update('type')}>
              {['Full-time', 'Part-time', 'PRN / Per Diem', 'Contract', 'Temporary'].map(t => (
                <option key={t}>{t}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="field-label">City</label>
            <input className="input" value={form.city} onChange={update('city')} placeholder="e.g. San Francisco, CA" />
          </div>
          <button type="button" className="btn btn-primary" onClick={() => setStep(1)} disabled={!form.title || !form.role}>
            Continue →
          </button>
        </div>
      )}

      {step === 1 && (
        <div className="field-stack">
          <div>
            <label className="field-label">Practice Name</label>
            <input className="input" value={form.practice} onChange={update('practice')} placeholder="e.g. Pacific Oral Care" />
          </div>
          <div>
            <label className="field-label">Pay Range</label>
            <input className="input" value={form.pay} onChange={update('pay')} placeholder="e.g. $48–$58/hr or $75k–$90k/yr" />
          </div>
          <div>
            <label className="field-label">Contact Email</label>
            <input className="input" type="email" value={form.contact} onChange={update('contact')} placeholder="hiring@practice.com" />
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button type="button" className="btn btn-ghost" onClick={() => setStep(0)}>← Back</button>
            <button type="button" className="btn btn-primary" style={{ flex: 1 }} onClick={() => setStep(2)} disabled={!form.practice || !form.contact}>
              Review & Post →
            </button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <div className="card" style={{ marginBottom: 16 }}>
            <p style={{ fontWeight: 600, marginBottom: 8 }}>Job Listing Preview</p>
            <div style={{ fontSize: 13, display: 'grid', gap: 4 }}>
              <div><strong>Title:</strong> {form.title}</div>
              <div><strong>Type:</strong> {form.type}</div>
              <div><strong>Location:</strong> {form.city}</div>
              <div><strong>Pay:</strong> {form.pay || 'TBD'}</div>
              <div><strong>Practice:</strong> {form.practice}</div>
            </div>
          </div>
          <div className="card session-panel--highlight" style={{ marginBottom: 16 }}>
            <p style={{ fontWeight: 700, marginBottom: 4 }}>Post for $59/month</p>
            <p className="session-text-sm" style={{ margin: 0 }}>
              30-day listing · Featured in network newsletter · Applies visible to practice only.
            </p>
          </div>
          {/* Pickaxe payment placeholder */}
          <button type="button" className="btn btn-primary btn-block"
            onClick={() => openPickaxePayment('jobs_post', 'Post a Job', `Post "${form.title}" on Smile Mentors — 30-day listing from $59/mo.`) || window.open('https://pickaxe.com', '_blank', 'noopener')}>
            💳 Pay & Publish via Pickaxe
          </button>
          <button type="button" className="btn btn-ghost" style={{ marginTop: 8, width: '100%' }} onClick={() => setStep(1)}>← Edit</button>
          <div className="disclaimer-banner" style={{ marginTop: 16 }}>{AB3030}</div>
        </div>
      )}
    </div>
  );
}

// ─── JobBoard ─────────────────────────────────────────────────────────────────
function JobBoard({ go }) {
  const [role, setRole] = useState('all');
  const [type, setType] = useState('all');
  const [zip, setZip] = useState('');
  const [loading, setLoading] = useState(false);
  const [jobs, setJobs] = useState(SEED_JOBS);

  const search = async () => {
    setLoading(true);
    try {
      const body = { role, type, zip };
      const r = await fetch('/api/jobs/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (r.ok) {
        const d = await r.json();
        if (d.jobs) setJobs(d.jobs);
      } else {
        const params = new URLSearchParams({ role, type, zip });
        const fallback = await fetch(`/api/jobs/search?${params}`);
        if (fallback.ok) {
          const d = await fallback.json();
          if (d.jobs) setJobs(d.jobs);
        }
      }
    } catch (_) {
      /* fall back to seed data */
    } finally {
      setLoading(false);
    }
  };

  const filtered = jobs.filter(j =>
    (role === 'all' || j.role === role) &&
    (type === 'all' || j.type === type) &&
    (!zip || j.city.includes(zip.slice(0, 3)))
  );

  return (
    <div className="session-screen gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('smile-mentors')} aria-label="Back to Smile Mentors">
        ← Smile Mentors
      </button>
      <div className="session-row session-row--between" style={{ marginBottom: 20 }}>
        <div>
          <h1 className="session-title">Dental Jobs</h1>
          <p className="section-subtitle session-muted">{filtered.length} open positions</p>
        </div>
        <button type="button" className="btn btn-primary btn-sm td-cta" onClick={() => go?.('jobs-post')} aria-label="Post a job">+ Post a Job</button>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 16 }}>
        <select className="input" style={{ width: 'auto', flex: 1, minWidth: 140 }} value={role} onChange={e => setRole(e.target.value)}>
          <option value="all">All Roles</option>
          {ROLES.map(r => <option key={r.slug} value={r.slug}>{r.label}</option>)}
        </select>
        <select className="input" style={{ width: 'auto', flex: 1, minWidth: 120 }} value={type} onChange={e => setType(e.target.value)}>
          <option value="all">All Types</option>
          {['Full-time', 'Part-time', 'PRN', 'Contract'].map(t => <option key={t}>{t}</option>)}
        </select>
        <input className="input" style={{ flex: 1, minWidth: 100 }} value={zip} onChange={e => setZip(e.target.value)} placeholder="ZIP code" />
        <button type="button" className="btn btn-secondary btn-sm" onClick={search} disabled={loading} aria-label="Search jobs">
          {loading ? 'Searching…' : 'Search'}
        </button>
      </div>

      {/* Job cards */}
      {filtered.length === 0 && !loading ? (
        window.EmptyState ? (
          <EmptyState
            title="No jobs match"
            description="Try broadening your role, type, or ZIP filters."
            variant="search"
          />
        ) : (
          <div className="card session-empty">
            <div className="session-success-icon" aria-hidden="true">🔍</div>
            <p>No jobs match these filters. Try broadening your search.</p>
          </div>
        )
      ) : loading && window.Skeleton ? (
        <Skeleton lines={4} height={18} />
      ) : (
        <div className="session-stack">
          {filtered.map(j => (
            <div key={j.id} className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 2 }}>{j.title}</div>
                <div className="session-text-sm" style={{ marginBottom: 6 }}>{j.practice} · {j.city}</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  <span className="badge badge-blue" style={{ fontSize: 11 }}>{j.type}</span>
                  <span className="badge badge-green" style={{ fontSize: 11 }}>{j.pay}</span>
                  <span className="badge badge-gray" style={{ fontSize: 11 }}>Posted {j.posted}</span>
                </div>
              </div>
              <button type="button" className="btn btn-primary btn-sm" style={{ flexShrink: 0 }}>Apply</button>
            </div>
          ))}
        </div>
      )}
      <div className="disclaimer-banner" style={{ marginTop: 24 }}>{AB3030}</div>
    </div>
  );
}

// ─── SmileMentors Hub ─────────────────────────────────────────────────────────
function SmileMentors({ go }) {
  return (
    <div className="session-screen gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('landing')} aria-label="Back to home">
        ← Home
      </button>

      <div className="session-hero landing-modern-hero">
        <p className="session-eyebrow">SMILE MENTORS</p>
        <h1 className="landing-modern-headline session-title" style={{ marginBottom: 12 }}>
          Your Dental Career,<br />Amplified.
        </h1>
        <p className="session-muted" style={{ fontSize: 15, maxWidth: 480, margin: '0 auto 20px' }}>
          Jobs, PRN shifts, CE credits, and salary benchmarks — built for every role in the dental team.
        </p>
        <div className="session-hero-actions">
          <button type="button" className="btn btn-primary td-cta" onClick={() => go?.('jobs')}>Browse Jobs →</button>
          <button type="button" className="btn btn-secondary" onClick={() => go?.('ce-hub')}>Earn CE Credits →</button>
        </div>
      </div>

      <p className="session-label" style={{ marginBottom: 12 }}>Your Role</p>
      <div className="session-card-grid" style={{ marginBottom: 32 }}>
        {ROLES.map(r => (
          <div
            key={r.slug}
            className="card chooser-card-b5 session-chooser-card"
            role="button"
            tabIndex={0}
            aria-label={`Browse jobs for ${r.label}`}
            onClick={() => {
              try { localStorage.setItem('sm_role', r.slug); } catch (_) {}
              go?.('jobs');
            }}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); try { localStorage.setItem('sm_role', r.slug); } catch (_) {} go?.('jobs'); } }}
          >
            <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>

      <div className="session-stat-grid" style={{ marginBottom: 32 }}>
        {[
          { n: '6+', label: 'Open positions' },
          { n: '6', label: 'CE courses' },
          { n: 'CA', label: 'Primary market' },
        ].map(({ n, label }) => (
          <div key={label} className="card" style={{ textAlign: 'center' }}>
            <div className="session-stat-num">{n}</div>
            <div className="session-stat-label">{label}</div>
          </div>
        ))}
      </div>

      <div className="disclaimer-banner">{AB3030}</div>
      <p className="session-footnote">TheDentist<em>.ai</em> · Smile Mentors Inc.</p>
    </div>
  );
}

// Route from index.html: SmileMentors hub renders for #smile-mentors and #jobs (hub is default)
window.SmileMentors = SmileMentors;
window.JobBoard     = JobBoard;
window.JobPost      = JobPost;
window.CeHub        = CeHub;
