// Instant dental consult — connecting / matching screen with queue + symptom intake

function instantRouteParams() {
  const q = (window.location.hash.replace(/^#/, '') || '').split('?')[1] || '';
  return new URLSearchParams(q);
}

function InstantConsult() {
  useDoctorReviews();
  const requestedDoctorId = Number(instantRouteParams().get('doctor'));
  const requestedDoctor = Number.isFinite(requestedDoctorId) ? DOC_BY_ID(requestedDoctorId) : null;
  const [phase, setPhase] = React.useState(requestedDoctor ? 'matched' : 'intake'); // intake | matching | matched
  const [selectedSpec, setSelectedSpec] = React.useState(requestedDoctor?.k || 'emergency');
  const [symptoms, setSymptoms] = React.useState('');
  const [mode, setMode] = React.useState('video');
  const presence = usePresence();
  const matchedDoctor = requestedDoctor || DOCTORS.find((d) => presence.has(d.id) && doctorMatchesSpec(d, selectedSpec)) || DOCTORS.find((d) => doctorMatchesSpec(d, selectedSpec)) || DOC_BY_ID(1);
  const selectedSpecialty = SPECIALTIES.find((s) => s.k === selectedSpec) || SPECIALTIES[0];

  const steps = [
    { k: 'intake',   label: 'Describe symptoms' },
    { k: 'matching', label: 'Matching dentist' },
    { k: 'matched',  label: 'Connect' },
  ];

  return (
    <PortalShell active="home" title="Instant Dental Consult" subtitle="Talk to an available dentist — typical wait under 5 minutes">
      <div style={{ padding: 32, maxWidth: 980, margin: '0 auto' }}>
        {/* Stepper */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 28 }}>
          {steps.map((s, i) => {
            const idx = steps.findIndex(x => x.k === phase);
            const done = i < idx, on = i === idx;
            return (
              <div key={s.k} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 999,
                  display: 'grid', placeItems: 'center',
                  background: done || on ? 'var(--blue)' : 'var(--line-2)',
                  color: done || on ? '#fff' : 'var(--ink-3)',
                  fontSize: 11, fontWeight: 500,
                }}>{done ? '✓' : i + 1}</div>
                <div style={{ fontSize: 12.5, color: on ? 'var(--ink)' : 'var(--ink-3)', fontWeight: on ? 500 : 400 }}>{s.label}</div>
                {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: 'var(--line)' }}/>}
              </div>
            );
          })}
        </div>

        {phase === 'intake' && (
          <div className="ml-card" style={{ padding: 28 }}>
            <div className="ml-label" style={{ marginBottom: 8 }}>Step 1 of 3</div>
            <h2 style={{ fontSize: 28, marginBottom: 6 }}>What brings you in today?</h2>
            <p className="ml-muted" style={{ marginTop: 0, marginBottom: 24, fontSize: 14 }}>
              We'll match you with the right available dentist.
            </p>

            <div className="ml-label" style={{ marginBottom: 10 }}>Choose dental care</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginBottom: 26 }}>
              {SPECIALTIES.slice(0, 10).map(s => {
                const Icon = I[s.icon] || I.tooth;
                const on = selectedSpec === s.k;
                return (
                  <div key={s.k} onClick={() => setSelectedSpec(s.k)}
                    style={{
                      border: on ? '1.5px solid var(--blue)' : '1px solid var(--line)',
                      background: on ? 'var(--blue-soft)' : '#fff',
                      borderRadius: 10, padding: 12, cursor: 'pointer',
                      display: 'flex', flexDirection: 'column', gap: 6,
                    }}>
                    <Icon size={18} color={on ? 'var(--blue-deep)' : 'var(--ink-2)'}/>
                    <div style={{ fontSize: 12.5, fontWeight: on ? 500 : 400 }}>{s.n}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{s.count} online</div>
                  </div>
                );
              })}
            </div>

            <div className="ml-label" style={{ marginBottom: 10 }}>Describe your concern</div>
            <textarea className="ml-input" rows={4} value={symptoms} onChange={e => setSymptoms(e.target.value)}
              placeholder="Tell the dentist what you are feeling, when it started, and what makes it better or worse."
              style={{ resize: 'none', fontFamily: 'var(--sans)', marginBottom: 24 }}/>

            <div className="ml-label" style={{ marginBottom: 10 }}>Consult mode</div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 28 }}>
              {[
                { k: 'video', icon: 'video', label: 'Video call', sub: 'Most personal' },
                { k: 'audio', icon: 'mic',   label: 'Audio only', sub: 'Low bandwidth' },
                { k: 'chat',  icon: 'chat',  label: 'Chat',       sub: 'Async-friendly' },
              ].map(m => {
                const Icon = I[m.icon];
                const on = mode === m.k;
                return (
                  <div key={m.k} onClick={() => setMode(m.k)}
                    style={{
                      flex: 1, padding: 16, borderRadius: 10, cursor: 'pointer',
                      border: on ? '1.5px solid var(--blue)' : '1px solid var(--line)',
                      background: on ? 'var(--blue-soft)' : '#fff',
                    }}>
                    <Icon size={20} color={on ? 'var(--blue-deep)' : 'var(--ink-2)'}/>
                    <div style={{ fontSize: 14, fontWeight: 500, marginTop: 8 }}>{m.label}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.sub}</div>
                  </div>
                );
              })}
            </div>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div className="ml-muted" style={{ fontSize: 12.5 }}>
                Estimated cost <strong style={{ color: 'var(--ink)' }}>₹399 – ₹699</strong> · billed after consult
              </div>
              <button className="ml-btn ml-btn--primary" onClick={() => setPhase('matching')}>
                Find a dentist <I.arrowR size={14}/>
              </button>
            </div>
          </div>
        )}

        {phase === 'matching' && (
          <div className="ml-card" style={{ padding: 48, textAlign: 'center' }}>
            <div style={{ position: 'relative', width: 120, height: 120, margin: '0 auto 24px' }}>
              <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2px solid var(--blue)', opacity: 0.2 }}/>
              <div style={{ position: 'absolute', inset: -16, borderRadius: '50%', border: '2px solid var(--blue)', opacity: 0.1 }}/>
              <div style={{ position: 'absolute', inset: -32, borderRadius: '50%', border: '2px solid var(--blue)', opacity: 0.05 }}/>
              <div style={{ position: 'absolute', inset: 16, borderRadius: '50%', background: 'var(--blue)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                <I.tooth size={32}/>
              </div>
            </div>
            <h2 style={{ fontSize: 24, marginBottom: 6 }}>Finding the right dentist for you...</h2>
            <p className="ml-muted" style={{ fontSize: 14, marginBottom: 28 }}>
              Estimated wait <strong style={{ color: 'var(--ink)' }}>under 3 minutes</strong> · {selectedSpecialty.count} dentists online for {selectedSpecialty.n.toLowerCase()}
            </p>

            {/* Queue position */}
            <div style={{ maxWidth: 360, margin: '0 auto', textAlign: 'left' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 }}>
                <span className="ml-muted">Position in queue</span>
                <span style={{ fontFamily: 'var(--mono)' }}>2 of 7</span>
              </div>
              <div style={{ height: 6, background: 'var(--line-2)', borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ width: '72%', height: '100%', background: 'var(--blue)', borderRadius: 999 }}/>
              </div>
              <div style={{ marginTop: 24, padding: 14, background: 'var(--paper-2)', borderRadius: 8, fontSize: 12.5, color: 'var(--ink-2)' }}>
                <I.shield size={14} style={{ marginRight: 6, verticalAlign: -2 }} color="var(--accent)"/>
                Your symptoms and ID are encrypted end-to-end.
              </div>
            </div>

            <button className="ml-btn ml-btn--ghost" style={{ marginTop: 28 }} onClick={() => setPhase('matched')}>
              Skip to matched →
            </button>
          </div>
        )}

        {phase === 'matched' && (
          <div className="ml-card" style={{ padding: 32, display: 'grid', gridTemplateColumns: '120px 1fr', gap: 24, alignItems: 'center' }}>
            <div className="ml-avatar" style={{ width: 120, height: 120, borderRadius: '50%', fontSize: 38, background: TONE_BG[matchedDoctor.tone], color: TONE_FG[matchedDoctor.tone] }}>{matchedDoctor.avatar}</div>
            <div>
              <span className="ml-pill ml-pill--mint"><span className="ml-live"/> Matched · ready to connect</span>
              <h2 style={{ fontSize: 26, marginTop: 10, marginBottom: 4 }}>{matchedDoctor.n}</h2>
              <div className="ml-muted" style={{ fontSize: 13.5, marginBottom: 14 }}>
                {matchedDoctor.creds} · {matchedDoctor.spec} · {matchedDoctor.y} yrs experience · ★ {doctorStats(matchedDoctor).rating} ({doctorStats(matchedDoctor).reviews.toLocaleString()})
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => window.navigate && window.navigate('/visit')} className="ml-btn ml-btn--primary"><I.video size={14}/> Join {mode} call</button>
                <button onClick={() => window.navigate && window.navigate('/dashboard')} className="ml-btn ml-btn--ghost">Cancel</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </PortalShell>
  );
}

window.InstantConsult = InstantConsult;
