// 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.';

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 }) {
  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?.('smile-mentors')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Smile Mentors
      </button>
      <p className="t-eyebrow" style={{ fontSize: 11, color: 'var(--color-accent)', fontWeight: 700, letterSpacing: '0.1em', marginBottom: 8 }}>
        SMILE MENTORS · CE HUB
      </p>
      <h1 style={{ fontSize: 'clamp(1.25rem,4vw,1.75rem)', fontWeight: 700, margin: '0 0 4px', letterSpacing: '-0.02em' }}>
        Continuing Education
      </h1>
      <p className="section-subtitle" style={{ marginBottom: 24 }}>ADA CERP · ADHA · PACE-approved courses for dental professionals.</p>

      <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 style={{ fontWeight: 700, fontSize: 16, color: 'var(--color-accent)' }}>${c.price}</div>
              <button type="button" className="btn btn-primary btn-sm" style={{ marginTop: 6 }}
                onClick={() => window.open('https://pickaxe.com', '_blank', 'noopener')}>
                Enroll
              </button>
            </div>
          </div>
        ))}
      </div>

      <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="gap-screen animate-fade-in-up" style={{ maxWidth: 600, margin: '0 auto', padding: '24px 16px' }}>
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => go?.('jobs')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Job Board
      </button>
      <h1 style={{ fontSize: 'clamp(1.1rem,3vw,1.5rem)', fontWeight: 700, margin: '0 0 4px' }}>Post a Job</h1>
      <p className="section-subtitle" style={{ marginBottom: 20 }}>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" style={{ marginBottom: 16, background: 'var(--color-accent-light)' }}>
            <p style={{ fontWeight: 700, marginBottom: 4 }}>Post for $59/month</p>
            <p style={{ fontSize: 13, color: 'var(--color-text-secondary)' }}>
              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={() => 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 params = new URLSearchParams({ role, type, zip });
      const r = await fetch(`/api/jobs/search?${params}`);
      if (r.ok) {
        const d = await r.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="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?.('smile-mentors')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Smile Mentors
      </button>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap', marginBottom: 20 }}>
        <div>
          <h1 style={{ fontSize: 'clamp(1.25rem,4vw,1.75rem)', fontWeight: 700, margin: '0 0 4px' }}>Dental Jobs</h1>
          <p className="section-subtitle">{filtered.length} open positions</p>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => go?.('jobs-post')}>+ 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}>
          {loading ? '…' : 'Search'}
        </button>
      </div>

      {/* Job cards */}
      {filtered.length === 0 ? (
        <div className="card" style={{ textAlign: 'center', padding: 32 }}>
          <div style={{ fontSize: 32, marginBottom: 8 }}>🔍</div>
          <p>No jobs match these filters. Try broadening your search.</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {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 style={{ fontSize: 13, color: 'var(--color-text-secondary)', 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 ─────────────────────────────────────────────────────────
// initialTab: when deep-linking via #jobs-post or #ce-hub, the Screen wrapper
// passes initialTab so we immediately navigate to the correct sub-screen.
function SmileMentors({ go, initialTab }) {
  // Deep-link: if initialTab is set, immediately call go() on first render.
  useEffect(() => {
    if (initialTab === 'jobs-post') go?.('jobs-post');
    else if (initialTab === 'ce-hub') go?.('ce-hub');
    else if (initialTab === 'jobs') go?.('jobs');
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  if (initialTab === 'jobs-post' || initialTab === 'ce-hub' || initialTab === 'jobs') {
    // Render nothing while we wait for the redirect — avoids flash.
    return <div style={{ minHeight: 120 }} />;
  }

  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?.('landing')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Home
      </button>

      {/* Hero */}
      <div className="landing-modern-hero" style={{ textAlign: 'center', marginBottom: 32 }}>
        <p style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--color-accent)', textTransform: 'uppercase', marginBottom: 8 }}>
          SMILE MENTORS
        </p>
        <h1 className="landing-modern-headline" style={{ marginBottom: 12 }}>
          Your Dental Career,<br />Amplified.
        </h1>
        <p style={{ fontSize: 15, color: 'var(--color-text-secondary)', maxWidth: 480, margin: '0 auto 20px' }}>
          Jobs, PRN shifts, CE credits, and salary benchmarks — built for every role in the dental team.
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button type="button" className="btn btn-primary" onClick={() => go?.('jobs')}>Browse Jobs →</button>
          <button type="button" className="btn btn-secondary" onClick={() => go?.('ce-hub')}>Earn CE Credits →</button>
        </div>
      </div>

      {/* Role cards */}
      <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>
        Your Role
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 12, marginBottom: 32 }}>
        {ROLES.map(r => (
          <div
            key={r.slug}
            className="card chooser-card-b5"
            onClick={() => {
              try { localStorage.setItem('sm_role', r.slug); } catch (_) {}
              go?.('jobs');
            }}
          >
            <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>

      {/* Quick stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, 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 style={{ fontSize: 24, fontWeight: 700, color: 'var(--color-accent)' }}>{n}</div>
            <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginTop: 2 }}>{label}</div>
          </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>
  );
}

// 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;
