/* global React */
const { useState: useStateJ, useEffect: useEffectJ } = React;

const { Ic } = window;

/* lucide icon names used across the journey timelines */
const JIC = {
  lab: 'FlaskConical',
  nutri: 'Leaf',
  shield: 'ShieldCheck',
  chart: 'TrendingUp',
  home: 'House',
  pill: 'Pill',
  heart: 'HeartPulse',
  chat: 'MessageCircle',
  refresh: 'RefreshCw',
  user: 'User' };

const JBLUE = '#0E5AA0';
const JBLUE_SOFT = 'rgba(14,90,160,.12)';
const JBLUE_GRAD = 'linear-gradient(157deg, #2A86CE 0%, #0E5AA0 52%, #0A467F 100%)';
const JTABS = [
{ id: 'family', label: 'Young Family', accent: JBLUE, soft: JBLUE_SOFT },
{ id: 'parent', label: 'Aging Parent', accent: JBLUE, soft: JBLUE_SOFT },
{ id: 'me', label: 'Just Me', accent: JBLUE, soft: JBLUE_SOFT }];

const JDATA = {
  family: {
    photoId: 'jr-family', photoPh: 'The Sharma family at home', photoSrc: 'app/images/journey-family.png',
    pill: 'The Sharma family · 12 months in',
    desc: "Rohit and Priya, both working, with two school-age kids. When they joined, health was something they reacted to. A year later, it’s something they understand and stay ahead of, together.",
    quote: "Our doctor didn’t just hand us pills but also showed us how to actually get healthier: what to eat, how to move, which numbers to watch. A year on, our reports are better and we finally understand our own health.",
    qname: 'Priya Sharma', qplace: 'Sector 54, Gurgaon',
    steps: [
    { m: 'Months 1–3', t: 'Getting the full picture', b: 'Blood work for all four at home. Their doctor maps each person’s risks and sets clear, realistic goals.', ic: JIC.lab },
    { m: 'Months 3–6', t: 'Beyond medicines', b: 'A nutritionist rebuilds everyday meals; a simple home routine for Rohit and Priya’s weight and BP.', ic: JIC.nutri },
    { m: 'Months 6–9', t: 'Staying ahead', b: 'Flu shots and immunity boosters; the kids’ vaccinations updated; Rohit’s BP medication fine-tuned.', ic: JIC.shield },
    { m: 'Months 9–12', t: 'The proof', b: 'Repeat labs come back better across the board, and two prescriptions are safely reduced.', ic: JIC.chart }],
    numbers: [
    { initials: 'R', name: 'Rohit, 42', sub: 'Borderline diabetic, rising BP', rows: [
      { l: 'Fasting sugar', o: '138', n: '96', u: 'mg/dL' },
      { l: 'Blood pressure', o: '148/96', n: '124/82', u: '' },
      { l: 'Weight', o: '86', n: '79', u: 'kg' }] },
    { initials: 'P', name: 'Priya, 39', sub: 'Low energy, thyroid & Vit D', rows: [
      { l: 'Thyroid (TSH)', o: '6.8', n: '3.1', u: 'mIU/L' },
      { l: 'Vitamin D', o: '14', n: '42', u: 'ng/mL' },
      { l: 'HbA1c', o: '6.2', n: '5.4', u: '%' }] },
    { initials: 'AS', name: 'Aarav & Sia', sub: 'The kids, 11 & 7', rows: [
      { l: 'Vaccinations', o: '—', n: '100%', u: 'on time' },
      { l: 'Sick-day clinic trips', o: '4', n: '0', u: '/ yr' },
      { l: 'Annual check-up', o: '—', n: 'Done', u: 'at home' }] }] },

  parent: {
    photoId: 'jr-parent', photoPh: 'Mr. Khanna with his home-care team', photoSrc: 'app/images/journey-parent.png',
    pill: 'Mr. Khanna, 74 · cared for from another city',
    desc: "Sunita lives in Pune; her father lives on his own in Delhi. She used to worry between phone calls. Now one doctor and a coordinator look after him, and she sees everything that happens.",
    quote: "I’m 1,400 km away, but I know my father’s blood pressure this week and exactly what his doctor said. For a daughter living apart, that is everything.",
    qname: 'Sunita Khanna', qplace: 'Pune, for her father in Delhi',
    steps: [
    { m: 'Month 1', t: 'A doctor who comes to him', b: 'No more tiring clinic trips. His family doctor visits at home and learns his full history and medicines.', ic: JIC.home },
    { m: 'Months 1–4', t: 'Medicines, simplified', b: 'Six prescriptions reconciled to four, and delivered home each month, so he never runs out.', ic: JIC.pill },
    { m: 'Months 4–8', t: 'Steady monitoring', b: 'Nurse visits track his BP and sugar; the doctor adjusts early, before anything escalates.', ic: JIC.heart },
    { m: 'All year', t: 'Sunita always knows', b: 'A WhatsApp update after every visit. She finally stopped lying awake at night.', ic: JIC.chat }],
    numbers: [
    { initials: 'MK', name: 'Mr. Khanna, 74', sub: 'BP & diabetes, lives alone', rows: [
      { l: 'Blood pressure', o: '158/98', n: '128/84', u: '' },
      { l: 'Fasting sugar', o: '152', n: '108', u: 'mg/dL' },
      { l: 'ER / urgent trips', o: '3', n: '0', u: '/ yr' }] },
    { initials: 'FS', name: 'For Sunita', sub: 'His daughter, in Pune', rows: [
      { l: 'Update after each visit', o: '—', n: '100%', u: 'sent' },
      { l: 'Missed medicines', o: 'often', n: '0', u: '' },
      { l: 'Peace of mind', o: '—', n: 'Daily', u: '' }] }] },

  me: {
    photoId: 'jr-me-2', photoPh: 'Aisha’s at-home consult', photoSrc: 'app/images/journey-me.png',
    pill: 'Aisha, 34 · taking charge of her own health',
    desc: "Aisha is 34, single, and works long hours. Tired all the time, she kept putting off a check-up. Her family doctor found out why and built a plan around her actual life, not a clinic’s timings.",
    quote: "I’d been blaming myself for being tired all the time. Turns out it was treatable, and I finally had a doctor who actually explained what was going on and what to do about it.",
    qname: 'Aisha Verma', qplace: 'Gurgaon',
    steps: [
    { m: 'Month 1', t: 'Finally, some answers', b: 'A full panel at home, after work. It uncovers an underactive thyroid plus low Vitamin D and iron.', ic: JIC.lab },
    { m: 'Months 1–3', t: 'Beyond a prescription', b: 'A nutritionist fixes her on-the-go eating; the doctor sets a routine she can realistically keep.', ic: JIC.nutri },
    { m: 'Months 3–6', t: 'Dialed in', b: 'Thyroid medication titrated by repeat labs; her energy and sleep steadily return.', ic: JIC.refresh },
    { m: 'Month 6', t: 'Back to herself', b: 'Numbers in range, and she understands her own body for the first time.', ic: JIC.chart }],
    numbers: [
    { initials: 'A', name: 'Aisha, 34', sub: 'Fatigue, thyroid, low iron', rows: [
      { l: 'Thyroid (TSH)', o: '7.4', n: '2.6', u: 'mIU/L' },
      { l: 'Vitamin D', o: '11', n: '38', u: 'ng/mL' },
      { l: 'Ferritin (iron)', o: '9', n: '32', u: 'ng/mL' }] },
    { initials: 'Hs', name: 'How she feels', sub: 'In her words, month 6', rows: [
      { l: 'Energy through the day', o: 'low', n: 'steady', u: '' },
      { l: 'Good nights’ sleep', o: '2', n: '6', u: '/ wk' },
      { l: 'Understands her health', o: '—', n: 'Fully', u: '' }] }] } };

const JGREEN = '#1F8A4C';

function JStat({ row, accent }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '11px 0', borderTop: '1px solid var(--line)' }}>
      <span style={{ fontSize: 13.5, color: 'var(--ink-2)', flexShrink: 0 }}>{row.l}</span>
      <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, fontSize: 13.5, textAlign: 'right' }}>
        {row.o !== '—' &&
        <span style={{ color: 'var(--muted)', textDecoration: 'line-through' }}>{row.o}</span>
        }
        <span style={{ color: 'var(--muted)' }}>→</span>
        <b style={{ color: JGREEN, fontSize: 15 }}>{row.n}</b>
        {row.u && <span style={{ color: 'var(--muted)' }}>{row.u}</span>}
      </span>
    </div>);

}

function JNumberCard({ card, accent, soft }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 18, padding: '16px 17px 6px', boxShadow: 'var(--shadow-sm)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 4 }}>
        <span style={{ width: 36, height: 36, borderRadius: '50%', background: soft, color: accent, display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0 }}>{card.initials}</span>
        <div>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>{card.name}</div>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 1 }}>{card.sub}</div>
        </div>
      </div>
      {card.rows.map((r) => <JStat key={r.l} row={r} accent={accent} />)}
    </div>);

}

/* ---- graphical "roadmap" timeline: one milestone at a time ---- */
function JRoadmap({ steps }) {
  const [i, setI] = useStateJ(0);
  const n = steps.length;
  const s = steps[i];
  const go = (d) => setI((p) => Math.max(0, Math.min(n - 1, p + d)));
  // progress fraction along the rail (start node = 0, finish flag = 1)
  const pct = (i + 1) / (n + 1) * 100;

  return (
    <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 18, padding: '20px 18px', marginTop: 14, boxShadow: 'var(--shadow-sm)' }}>
      <h3 style={{ fontSize: 16, color: 'var(--ink)' }}>How their doctor guided the year</h3>
      <p style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 3, marginBottom: 20 }}>From the first home visit to a healthier year. Tap through the milestones.</p>

      {/* horizontal journey rail */}
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '0 4px 22px' }}>
        {/* base track */}
        <div aria-hidden="true" style={{ position: 'absolute', left: 7, right: 7, top: '50%', transform: 'translateY(-50%)', height: 4, borderRadius: 4, background: 'var(--line-2)' }}></div>
        {/* filled track */}
        <div aria-hidden="true" style={{ position: 'absolute', left: 7, top: '50%', transform: 'translateY(-50%)', height: 4, borderRadius: 4, background: 'var(--hero-grad)', width: `calc((100% - 14px) * ${pct / 100})`, transition: 'width .4s cubic-bezier(.4,0,.2,1)' }}></div>

        {/* start node */}
        <span style={{ position: 'relative', width: 14, height: 14, borderRadius: '50%', background: '#fff', border: '3px solid #FBA64C', flexShrink: 0 }}></span>

        {/* milestone nodes */}
        {steps.map((st, k) => {
          const done = k < i,current = k === i;
          return (
            <button key={st.t} onClick={() => setI(k)} aria-label={`Milestone ${k + 1}: ${st.t}`}
            style={{ position: 'relative', border: 'none', cursor: 'pointer', padding: 0, flexShrink: 0,
              width: current ? 34 : 26, height: current ? 34 : 26, borderRadius: '50%',
              background: current || done ? 'var(--hero-grad)' : '#fff',
              boxShadow: current ? '0 0 0 4px #fff, 0 5px 12px rgba(244,122,28,.4)' : done ? '0 0 0 3px #fff' : 'inset 0 0 0 2px var(--line-2)',
              display: 'grid', placeItems: 'center', transition: 'all .3s cubic-bezier(.4,0,.2,1)' }}>
              {done ?
              <Ic n="Check" size={14} color="#fff" stroke={3} /> :
              <span style={{ fontSize: current ? 13 : 11.5, fontWeight: 800, color: current ? '#fff' : 'var(--muted)' }}>{k + 1}</span>}
            </button>);
        })}

        {/* finish flag */}
        <span style={{ position: 'relative', width: 22, height: 22, borderRadius: '50%', background: i === n - 1 ? JGREEN : '#fff', border: i === n - 1 ? 'none' : '2px solid var(--line-2)', display: 'grid', placeItems: 'center', flexShrink: 0, transition: 'all .3s' }}>
          <Ic n="Flag" size={12} color={i === n - 1 ? '#fff' : 'var(--muted)'} stroke={2.4} />
        </span>
      </div>

      {/* active milestone card */}
      <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start', background: 'rgba(14,90,160,.045)', border: '1px solid rgba(14,90,160,.12)', borderRadius: 16, padding: '16px 16px', minHeight: 116, animation: 'jrfade .4s cubic-bezier(.4,0,.2,1)' }}>
        <span style={{ position: 'relative', width: 52, height: 52, borderRadius: 14, background: 'rgba(39,26,17,.09)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <Ic n={s.ic} size={24} color="var(--espresso)" stroke={1.9} />
          <span style={{ position: 'absolute', top: -4, right: -4, width: 20, height: 20, borderRadius: '50%', background: '#fff', color: 'var(--espresso)', fontSize: 11, fontWeight: 800, display: 'grid', placeItems: 'center', boxShadow: '0 1px 3px rgba(0,0,0,.2)' }}>{i + 1}</span>
        </span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.07em', textTransform: 'uppercase', color: 'var(--brand-deep)' }}>{s.m}</div>
          <h4 style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink)', marginTop: 3 }}>{s.t}</h4>
          <p style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 5, lineHeight: 1.45 }}>{s.b}</p>
        </div>
      </div>

      {/* nav */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
        <button onClick={() => go(-1)} disabled={i === 0} aria-label="Previous milestone"
        style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--line-2)', background: '#fff', cursor: i === 0 ? 'default' : 'pointer', opacity: i === 0 ? .35 : 1, display: 'grid', placeItems: 'center', transition: 'opacity .2s' }}>
          <Ic n="ChevronLeft" size={19} color="var(--ink)" stroke={2.2} />
        </button>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--muted)', letterSpacing: '.02em' }}>
          {i === n - 1 ? <span style={{ color: JGREEN }}>1 year on · healthier &amp; on track</span> : `Milestone ${i + 1} of ${n}`}
        </span>
        <button onClick={() => go(1)} disabled={i === n - 1} aria-label="Next milestone"
        style={{ width: 40, height: 40, borderRadius: '50%', border: 'none', background: i === n - 1 ? 'var(--line-2)' : 'var(--blue-grad)', cursor: i === n - 1 ? 'default' : 'pointer', opacity: i === n - 1 ? .5 : 1, display: 'grid', placeItems: 'center', transition: 'opacity .2s' }}>
          <Ic n="ChevronRight" size={19} color="#fff" stroke={2.2} />
        </button>
      </div>
    </div>);

}

function Journeys() {
  const [tab, setTab] = useStateJ('family');
  const active = JTABS.find((t) => t.id === tab);
  const d = JDATA[tab];

  /* carousel for "The numbers, one year on" — one card visible, infinite forward auto-scroll */
  const [nIdx, setNIdx] = useStateJ(0);
  const [nAnim, setNAnim] = useStateJ(true);
  const [nNonce, setNNonce] = useStateJ(0);
  const nLen = d.numbers.length;
  const nSlides = [...d.numbers, d.numbers[0]];
  const nStartX = React.useRef(null);

  useEffectJ(() => {
    setNAnim(false);
    setNIdx(0);
    const raf = requestAnimationFrame(() => setNAnim(true));
    return () => cancelAnimationFrame(raf);
  }, [tab]);

  useEffectJ(() => {
    const id = setInterval(() => {setNAnim(true);setNIdx((p) => p + 1);}, 4000);
    return () => clearInterval(id);
  }, [tab, nNonce]);

  useEffectJ(() => {
    if (nIdx === nLen) {
      const t = setTimeout(() => {setNAnim(false);setNIdx(0);}, 650);
      return () => clearTimeout(t);
    }
    if (!nAnim) {
      const r = requestAnimationFrame(() => setNAnim(true));
      return () => cancelAnimationFrame(r);
    }
  }, [nIdx]);

  const nGoNext = () => {setNNonce((n) => n + 1);setNAnim(true);setNIdx((p) => p + 1);};
  const nGoPrev = () => {
    setNNonce((n) => n + 1);
    if (nIdx <= 0) {
      setNAnim(false);
      setNIdx(nLen);
      requestAnimationFrame(() => {setNAnim(true);setNIdx(nLen - 1);});
    } else {
      setNAnim(true);
      setNIdx(nIdx - 1);
    }
  };
  const nOnDown = (e) => {nStartX.current = e.touches ? e.touches[0].clientX : e.clientX;};
  const nOnUp = (e) => {
    if (nStartX.current == null) return;
    const endX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
    const dx = endX - nStartX.current;
    nStartX.current = null;
    if (dx < -40) nGoNext();else
    if (dx > 40) nGoPrev();
  };

  const nDot = nIdx % nLen;

  return (
    <div className="sec" style={{ background: 'var(--paper-3)' }}>
      <SecHead kicker="Real journeys, real numbers">What a year with <em style={{ fontStyle: 'normal', fontWeight: 500 }}>your own doctor</em> looks like.</SecHead>
      <p style={{ color: 'var(--muted)', fontSize: 14.5, marginTop: -4, marginBottom: 20, textAlign: 'center', maxWidth: 320, marginLeft: 'auto', marginRight: 'auto' }}>
        Every family looks different. Here’s what a year of care did for three of them.
      </p>

      {/* segmented tabs */}
      <div style={{ position: 'relative', display: 'flex', background: '#fff', borderRadius: 999, padding: 4, boxShadow: 'var(--shadow-sm)', border: '1px solid var(--line)' }}>
        <div aria-hidden="true" style={{ position: 'absolute', top: 4, bottom: 4, left: 4, width: 'calc((100% - 8px) / 3)', borderRadius: 999,
          background: JBLUE_GRAD, transition: 'transform .38s cubic-bezier(.4,0,.2,1)', transform: `translateX(${JTABS.findIndex((t) => t.id === tab) * 100}%)` }}></div>
        {JTABS.map((t) =>
        <button key={t.id} onClick={() => setTab(t.id)}
        style={{ position: 'relative', zIndex: 1, flex: 1, border: 'none', cursor: 'pointer', padding: '10px 6px', borderRadius: 999, fontSize: 13, fontWeight: 700,
          fontFamily: 'inherit', whiteSpace: 'nowrap', background: 'transparent', transition: 'color .3s',
          color: tab === t.id ? '#fff' : 'var(--ink-2)' }}>{t.label}</button>
        )}
      </div>

      {/* photo + label */}
      <div style={{ position: 'relative', marginTop: 16, borderRadius: 20, overflow: 'hidden', boxShadow: 'var(--shadow-md)' }}>
        <image-slot id={d.photoId} shape="rect" fit="cover" placeholder={d.photoPh} src={d.photoSrc || undefined}
        style={{ width: '100%', height: 180 }}></image-slot>
        <span style={{ position: 'absolute', bottom: 12, left: 12, display: 'inline-flex', alignItems: 'center', gap: 7, background: 'rgba(255,255,255,.42)', backdropFilter: 'blur(10px) saturate(150%)', WebkitBackdropFilter: 'blur(10px) saturate(150%)', border: '1px solid rgba(255,255,255,.45)',
          borderRadius: 999, padding: '7px 13px', fontSize: 12.5, fontWeight: 700, color: '#fff', boxShadow: '0 2px 10px rgba(20,12,4,.18)', maxWidth: 'calc(100% - 24px)' }}>
          <Ic n="Calendar" size={14} color="#fff" stroke={2} />
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.pill}</span>
        </span>
      </div>

      {/* quote */}
      <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 16, padding: '15px 16px', marginTop: 14, boxShadow: 'var(--shadow-sm)' }}>
        <p style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15, lineHeight: 1.5, color: 'var(--ink)' }}>“{d.quote}”</p>
        <p style={{ fontSize: 13, marginTop: 10 }}><b style={{ color: 'var(--ink)' }}>{d.qname}</b> <span style={{ color: 'var(--muted)' }}>· {d.qplace}</span></p>
      </div>

      {/* timeline — graphical roadmap */}
      <JRoadmap key={tab} steps={d.steps} />

      {/* numbers */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, margin: '20px 0 12px' }}>
        <Ic n="TrendingUp" size={20} color={JGREEN} stroke={2} />
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, color: 'var(--ink)' }}>The numbers, one year on</span>
      </div>
      <div style={{ overflow: 'hidden', margin: '0 -22px', touchAction: 'pan-y', cursor: 'grab' }}
      onTouchStart={nOnDown} onTouchEnd={nOnUp} onMouseDown={nOnDown} onMouseUp={nOnUp}>
        <div style={{ display: 'flex', alignItems: 'flex-start', transition: nAnim ? 'transform .6s cubic-bezier(.4,0,.2,1)' : 'none', transform: `translateX(-${nIdx * 100}%)` }}>
          {nSlides.map((c, i) =>
          <div key={i} style={{ flex: '0 0 100%', minWidth: '100%', padding: '0 22px' }}>
              <JNumberCard card={c} accent={active.accent} soft={active.soft} />
            </div>
          )}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 7, justifyContent: 'center', marginTop: 16 }}>
        {d.numbers.map((_, i) =>
        <button key={i} onClick={() => {setNAnim(true);setNIdx(i);}} aria-label={`Show card ${i + 1}`}
        style={{ width: i === nDot ? 22 : 7, height: 7, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 0,
          background: i === nDot ? 'var(--blue)' : 'var(--line-2)', transition: 'width .3s, background .3s' }}></button>
        )}
      </div>

      <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--muted)', marginTop: 18, lineHeight: 1.5, maxWidth: 320, marginLeft: 'auto', marginRight: 'auto' }}>Representative journeys based on typical plan outcomes. Individual results vary.
Your doctor sets goals that are right for you.
      </p>
    </div>);

}

Object.assign(window, { Journeys });