// Patient view showcase — a fully scrollable phone with the patient experience.
// User can scroll within the phone OR use the side annotations to jump to a section.

const PVSection = React.forwardRef(({ id, kicker, title, children, style }, ref) => (
  <div ref={ref} id={`pv-${id}`} className="pv-section" style={{ padding: '24px 22px', ...style }}>
    {kicker && <h5>{kicker}</h5>}
    {title && <div style={{ fontWeight: 500, fontSize: 17, color: '#1A1A1A', marginBottom: 14, letterSpacing: '-0.01em' }}>{title}</div>}
    {children}
  </div>
));

const PatientView = () => {
  const phoneRef = useRef(null);
  const [activeSection, setActiveSection] = useState('procedure');

  const sectionRefs = {
    welcome: useRef(null),
    procedure: useRef(null),
    timeline: useRef(null),
    risks: useRef(null),
    faq: useRef(null),
    pricing: useRef(null),
    cta: useRef(null),
  };

  useEffect(() => {
    const container = phoneRef.current;
    if (!container) return;
    const onScroll = () => {
      // Find which section is most visible in the container
      const cTop = container.scrollTop;
      const cMid = cTop + container.clientHeight * 0.35;
      let best = 'welcome';
      let bestDelta = Infinity;
      Object.entries(sectionRefs).forEach(([k, r]) => {
        if (!r.current) return;
        const t = r.current.offsetTop;
        const delta = Math.abs(t - cMid);
        if (t <= cMid + 40 && delta < bestDelta) {
          best = k;
          bestDelta = delta;
        }
      });
      setActiveSection(best);
    };
    container.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => container.removeEventListener('scroll', onScroll);
  }, []);

  const jumpTo = (key) => {
    const target = sectionRefs[key]?.current;
    const container = phoneRef.current;
    if (!target || !container) return;
    container.scrollTo({ top: target.offsetTop - 4, behavior: 'smooth' });
  };

  const nav = [
    { k: 'welcome', label: 'Welcome' },
    { k: 'procedure', label: 'Procedure' },
    { k: 'timeline', label: 'What to expect' },
    { k: 'risks', label: 'Risks & benefits' },
    { k: 'faq', label: 'FAQ' },
    { k: 'pricing', label: 'Investment' },
    { k: 'cta', label: 'Book consult' },
  ];

  const [faqOpen, setFaqOpen] = useState(0);
  const faqs = [
    { q: 'Will it hurt?', a: 'You\'ll be under IV sedation for the surgery itself — most patients describe it as napping. The first few days after, you\'ll feel pressure and mild swelling, managed easily with ibuprofen. By day three, most people are back to normal activity.' },
    { q: 'How long does the whole process take?', a: 'The implant placement is one visit (about 75 minutes). Then your bone needs 3–4 months to fuse with it before we attach your permanent crown. You\'ll wear a temporary in the meantime — nobody will know.' },
    { q: 'Can I eat normally afterwards?', a: 'Soft foods for the first 48 hours. Smoothies, yogurt, soup, eggs. Avoid the surgical site when chewing. By the end of week one, you\'re back to most foods.' },
    { q: 'Why an implant instead of a bridge?', a: 'Bridges grind down two healthy teeth to anchor a fake one. Implants replace just the missing tooth, preserve your jawbone, and last 25+ years with good care.' },
  ];

  return (
    <section id="patient" style={{ background: 'var(--bg-soft)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 64px' }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24, justifyContent: 'center' }}>The patient view</div>
          <h2 className="reveal" style={{ marginBottom: 24 }}>
            This <span className="serif" style={{ color: 'var(--gold-deep)' }}>is</span> the demo. Scroll the phone — that's exactly what your patient sees.
          </h2>
          <p className="lede reveal" style={{ margin: '0 auto' }}>
            Generated for "single tooth implant + bone graft, tooth #14." Branded to
            Riverside Oral Surgery. No two plans are identical — every word is written
            for this patient, this procedure, this practice.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto minmax(0, 1fr)', gap: 56, alignItems: 'center', justifyItems: 'center' }}>
          {/* Left annotations */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, width: '100%', maxWidth: 320 }}>
            {[
              { k: 'welcome', label: 'Personal greeting', desc: 'Specialist photo, credentials, and a sentence that\'s actually warm.' },
              { k: 'procedure', label: 'Plain-language explanation', desc: 'Written for this patient and this case. No jargon. No templates.' },
              { k: 'timeline', label: 'Visual timeline', desc: 'From pre-op to fully healed. Anxiety is mostly fear of the unknown.' },
            ].map((n) => (
              <button
                key={n.k}
                onClick={() => jumpTo(n.k)}
                style={{
                  textAlign: 'left',
                  padding: '16px 18px',
                  borderRadius: 12,
                  border: '1px solid ' + (activeSection === n.k ? 'var(--gold)' : 'var(--line)'),
                  background: activeSection === n.k ? 'var(--card-solid)' : 'transparent',
                  color: 'var(--fg)',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  fontFamily: 'inherit',
                  boxShadow: activeSection === n.k ? 'var(--shadow-sm)' : 'none',
                }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{n.label}</span>
                  <span style={{
                    width: 6, height: 6, borderRadius: '50%',
                    background: activeSection === n.k ? 'var(--gold)' : 'var(--line-strong)',
                  }}></span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-faint)', lineHeight: 1.5 }}>{n.desc}</div>
              </button>
            ))}
          </div>

          {/* Phone */}
          <div className="phone" style={{ boxShadow: 'var(--shadow-lg)' }}>
            <div className="phone-notch"></div>
            <div
              ref={phoneRef}
              className="phone-screen scroll-soft pv-body"
              style={{ overflowY: 'auto', scrollBehavior: 'smooth' }}>

              {/* Sticky inner header */}
              <div style={{
                position: 'sticky', top: 0, zIndex: 5,
                background: 'rgba(255,255,255,0.92)',
                backdropFilter: 'blur(12px)',
                borderBottom: '1px solid rgba(0,0,0,0.06)',
                padding: '46px 18px 12px',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, background: '#1A1A1A', color: '#E6CC8A', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Noto Sans JP', fontWeight: 600, fontSize: 15 }}>R</div>
                  <div style={{ lineHeight: 1.1 }}>
                    <div style={{ fontWeight: 600, fontSize: 12 }}>Riverside Oral Surgery</div>
                    <div style={{ fontSize: 10, color: '#8A8170' }}>Plan for Marcus Chen</div>
                  </div>
                </div>
              </div>

              {/* Welcome */}
              <PVSection ref={sectionRefs.welcome} id="welcome" style={{ borderBottom: 'none' }}>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '16px 14px', marginBottom: 16,
                  borderRadius: 12,
                  background: 'linear-gradient(135deg, #FBF6EC 0%, #F4E7CC 100%)',
                }}>
                  <div className="placeholder-stripes" style={{ width: 56, height: 56, borderRadius: '50%', flexShrink: 0 }}></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Dr. Mira Halevy, DDS</div>
                    <div style={{ fontSize: 11, color: '#8A8170' }}>Oral & Maxillofacial Surgery · 12 yrs</div>
                  </div>
                </div>
                <p style={{ fontSize: 14, lineHeight: 1.55, color: '#3a3a3a', margin: 0 }}>
                  Hi Marcus — thanks for the trust your dentist Dr. Yoon placed in
                  us. Below is exactly what I'd like to do, why, and what to expect.
                  Read it on your own time, and bring me any question, no matter
                  how small.
                </p>
              </PVSection>

              {/* Procedure */}
              <PVSection ref={sectionRefs.procedure} id="procedure" kicker="YOUR PROCEDURE" title="Dental implant · tooth #14">
                <ImplantCarousel />
                <p style={{ fontSize: 13, lineHeight: 1.55, color: '#3a3a3a', margin: 0 }}>
                  A titanium post is gently placed into your jawbone where your
                  missing tooth used to be. Titanium is special — your body grows
                  bone directly around it, locking it in place as firmly as a real
                  root. After three months of healing, we attach a permanent
                  porcelain crown that matches your other teeth.
                </p>
                <div style={{
                  marginTop: 14, padding: '12px 14px',
                  background: '#FBF6EC', borderRadius: 10,
                  border: '1px solid rgba(184, 146, 74, 0.2)',
                  fontSize: 12, color: '#5C4A1F',
                }}>
                  <strong style={{ display: 'block', marginBottom: 2 }}>Because you mentioned you smoke —</strong>
                  We'll plan extra healing time and check in at week 2 instead of week 4. Healing rates are about 30% slower for smokers, but very manageable.
                </div>
              </PVSection>

              {/* Timeline */}
              <PVSection ref={sectionRefs.timeline} id="timeline" kicker="WHAT TO EXPECT" title="From now to fully healed">
                <div style={{ position: 'relative', paddingLeft: 24 }}>
                  <div style={{
                    position: 'absolute', left: 7, top: 8, bottom: 8,
                    width: 2, background: 'linear-gradient(180deg, #B8924A 0%, #E6CC8A 100%)',
                  }}></div>
                  {[
                    { t: '2 weeks before', d: 'Pre-op consult. Stop blood thinners with your GP\'s approval. Pick up prescriptions.' },
                    { t: 'Day of surgery', d: 'IV sedation. The procedure itself takes 60–90 minutes. Plan to take the day off.' },
                    { t: 'Days 1–3', d: 'Mild swelling and soreness. Soft foods. Most people are back to desk work by day 2.' },
                    { t: 'Week 2', d: 'Check-in with us. Stitches dissolve on their own. You\'ll feel basically normal.' },
                    { t: 'Months 2–4', d: 'Quiet healing phase. Bone grows around the implant. Temporary crown in place.' },
                    { t: 'Month 4', d: 'Permanent crown placed. You\'re done. Looks, feels, and chews like a real tooth.' },
                  ].map((s, i) => (
                    <div key={i} style={{ marginBottom: 14, position: 'relative' }}>
                      <div style={{
                        position: 'absolute', left: -22, top: 3,
                        width: 12, height: 12, borderRadius: '50%',
                        background: '#FFFFFF',
                        border: '2px solid ' + (i === 0 ? '#B8924A' : '#E6CC8A'),
                      }}></div>
                      <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 2 }}>{s.t}</div>
                      <div style={{ fontSize: 12, color: '#5C5648', lineHeight: 1.5 }}>{s.d}</div>
                    </div>
                  ))}
                </div>
              </PVSection>

              {/* Risks */}
              <PVSection ref={sectionRefs.risks} id="risks" kicker="RISKS & BENEFITS" title="An honest look">
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  <div style={{ padding: 12, borderRadius: 10, background: '#FBF6EC' }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: '#8B6B2E', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Benefits</div>
                    {['Lasts 25+ years', 'Preserves jawbone', 'Looks identical to a real tooth', 'No grinding healthy teeth'].map((b) => (
                      <div key={b} style={{ display: 'flex', alignItems: 'flex-start', gap: 6, fontSize: 11, marginBottom: 4, color: '#3a3a3a' }}>
                        <Icon name="check" size={11} stroke={2} /><span>{b}</span>
                      </div>
                    ))}
                  </div>
                  <div style={{ padding: 12, borderRadius: 10, background: '#F4EDE0' }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: '#6B5230', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Risks</div>
                    {['Infection (<2%)', 'Slower healing if smoking', 'Rare nerve sensitivity', 'Implant failure (~3%)'].map((b) => (
                      <div key={b} style={{ display: 'flex', alignItems: 'flex-start', gap: 6, fontSize: 11, marginBottom: 4, color: '#3a3a3a' }}>
                        <Icon name="minus" size={11} stroke={2} /><span>{b}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </PVSection>

              {/* FAQ */}
              <PVSection ref={sectionRefs.faq} id="faq" kicker="QUESTIONS YOU MIGHT HAVE" title="">
                {faqs.map((f, i) => (
                  <div key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.06)', padding: '12px 0' }}>
                    <button
                      onClick={() => setFaqOpen(faqOpen === i ? -1 : i)}
                      style={{
                        width: '100%',
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'flex-start',
                        background: 'transparent',
                        border: 'none',
                        padding: 0,
                        textAlign: 'left',
                        cursor: 'pointer',
                        gap: 12,
                        fontFamily: 'inherit',
                      }}>
                      <span style={{ fontSize: 13, fontWeight: 500, color: '#1A1A1A' }}>{f.q}</span>
                      <Icon name={faqOpen === i ? 'minus' : 'plus'} size={14} />
                    </button>
                    {faqOpen === i && (
                      <p style={{ fontSize: 12, color: '#5C5648', marginTop: 8, lineHeight: 1.55 }}>{f.a}</p>
                    )}
                  </div>
                ))}
              </PVSection>

              {/* Pricing */}
              <PVSection ref={sectionRefs.pricing} id="pricing" kicker="YOUR INVESTMENT" title="">
                <div style={{ background: '#FBF6EC', borderRadius: 12, padding: 16 }}>
                  {[
                    ['Implant placement', '$2,850'],
                    ['Bone graft + membrane', '$1,200'],
                    ['Healing abutment', '$350'],
                    ['IV sedation (45 min)', '$440'],
                    ['Consults + imaging', '$375'],
                    ['Post-op medications', '$85'],
                  ].map(([l, v]) => (
                    <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '6px 0', color: '#3a3a3a' }}>
                      <span>{l}</span><span>{v}</span>
                    </div>
                  ))}
                  <div style={{ borderTop: '1px solid rgba(0,0,0,0.1)', marginTop: 10, paddingTop: 10, display: 'flex', justifyContent: 'space-between', fontSize: 14, fontWeight: 600 }}>
                    <span>Total</span><span>$5,300</span>
                  </div>
                </div>
                <p style={{ fontSize: 11, color: '#8A8170', marginTop: 12, lineHeight: 1.5 }}>
                  Most extended insurance plans cover 30–50%. We'll help you submit
                  the predetermination. Financing available — as low as $147/mo.
                </p>
              </PVSection>

              {/* CTA */}
              <PVSection ref={sectionRefs.cta} id="cta" style={{ borderBottom: 'none', paddingBottom: 40 }}>
                <div style={{
                  background: '#1A1A1A',
                  color: '#F5F1E8',
                  padding: 20,
                  borderRadius: 14,
                  textAlign: 'center',
                }}>
                  <div style={{ fontSize: 14, marginBottom: 14, lineHeight: 1.45 }}>Ready to move forward, or have questions first?</div>
                  <button style={{
                    width: '100%',
                    padding: '12px',
                    borderRadius: 10,
                    background: '#E6CC8A',
                    color: '#1A1A1A',
                    fontWeight: 600,
                    fontSize: 14,
                    border: 'none',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    marginBottom: 8,
                  }}>Book my consult</button>
                  <button style={{
                    width: '100%',
                    padding: '12px',
                    borderRadius: 10,
                    background: 'transparent',
                    color: '#F5F1E8',
                    fontSize: 13,
                    border: '1px solid rgba(245,241,232,0.2)',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                  }}>I have a question</button>
                </div>
                <div style={{ textAlign: 'center', marginTop: 16, fontSize: 10, color: '#8A8170', fontFamily: 'Geist Mono' }}>
                  Made with <span style={{ color: '#B8924A' }}>日</span> Hinata
                </div>
              </PVSection>
            </div>
          </div>

          {/* Right annotations */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, width: '100%', maxWidth: 320 }}>
            {[
              { k: 'risks', label: 'Risks & benefits, paired', desc: 'Honesty builds trust. We surface both — neither buried.' },
              { k: 'faq', label: 'FAQ written for this case', desc: 'Not generic — addresses smoking, anxiety, this tooth, this surgery.' },
              { k: 'pricing', label: 'Price at the end, with context', desc: 'Patients see the value before the number. And financing without friction.' },
              { k: 'cta', label: 'One tap to book or ask', desc: 'No portal. No password. Two buttons — answered into your calendar.' },
            ].map((n) => (
              <button
                key={n.k}
                onClick={() => jumpTo(n.k)}
                style={{
                  textAlign: 'left',
                  padding: '16px 18px',
                  borderRadius: 12,
                  border: '1px solid ' + (activeSection === n.k ? 'var(--gold)' : 'var(--line)'),
                  background: activeSection === n.k ? 'var(--card-solid)' : 'transparent',
                  color: 'var(--fg)',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  fontFamily: 'inherit',
                  boxShadow: activeSection === n.k ? 'var(--shadow-sm)' : 'none',
                }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{n.label}</span>
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: activeSection === n.k ? 'var(--gold)' : 'var(--line-strong)' }}></span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-faint)', lineHeight: 1.5 }}>{n.desc}</div>
              </button>
            ))}
          </div>
        </div>

        {/* Bottom analytics chip */}
        <div className="reveal" style={{
          marginTop: 80,
          padding: 28,
          borderRadius: 'var(--radius-lg)',
          background: 'var(--card-solid)',
          border: '1px solid var(--line)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: 32,
          flexWrap: 'wrap',
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 10 }}>And you see, too</div>
            <h3 style={{ fontSize: 22 }}>Every plan tracks itself.</h3>
            <p style={{ marginTop: 8, maxWidth: '52ch', fontSize: 14 }}>
              Watch open rate, time on each section, FAQ taps, and accept/decline
              clicks. Know what's working before the consult.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 24 }}>
            {[
              { v: '94%', l: 'Opened' },
              { v: '4m 12s', l: 'Avg time' },
              { v: '71%', l: 'Booked' },
            ].map((s) => (
              <div key={s.l} style={{ textAlign: 'center' }}>
                <div className="serif" style={{ fontSize: 36, color: 'var(--gold-deep)', lineHeight: 1 }}>{s.v}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)', textTransform: 'uppercase', marginTop: 4, letterSpacing: '0.06em' }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { PatientView });
