/* Home, mirrors the preferred v1 single page, inside the multi-page shell. */
const { useRef, useEffect, useState } = React;

const SHOWCASE_LOOP_SEC = 21;

function Hero({ go }) {
  const [slide, setSlide] = useState(0);
  const [prevSlide, setPrevSlide] = useState(null);
  const [dir, setDir] = useState(1);
  const [paused, setPaused] = useState(false);
  const total = 2;
  const AUTO_MS = 5000;
  const portraitRef = useRef(null);
  const teamRef = useRef(null);
  const touchX = useRef(null);
  const slideRef = useRef(0);
  slideRef.current = slide;

  const goTo = (i) => {
    const nextIdx = ((i % total) + total) % total;
    if (nextIdx === slideRef.current) return;
    const forward = (nextIdx - slideRef.current + total) % total;
    const backward = (slideRef.current - nextIdx + total) % total;
    setDir(forward <= backward ? 1 : -1);
    setPrevSlide(slideRef.current);
    setSlide(nextIdx);
  };
  const prev = () => goTo(slideRef.current - 1);
  const next = () => goTo(slideRef.current + 1);

  useEffect(() => {
    if (prevSlide == null) return;
    const id = window.setTimeout(() => setPrevSlide(null), 900);
    return () => window.clearTimeout(id);
  }, [slide, prevSlide]);

  useEffect(() => {
    const sync = () => {
      const photo = portraitRef.current;
      const team = teamRef.current;
      if (!photo || !team) return;
      if (window.matchMedia("(max-width:980px)").matches) {
        team.style.height = "";
        team.style.width = "";
        return;
      }
      const h = Math.round(photo.getBoundingClientRect().height);
      if (h > 0) {
        team.style.height = `${h}px`;
        team.style.width = "auto";
      }
    };
    sync();
    window.addEventListener("resize", sync);
    const img = portraitRef.current;
    if (img && !img.complete) img.addEventListener("load", sync);
    return () => {
      window.removeEventListener("resize", sync);
      if (img) img.removeEventListener("load", sync);
    };
  }, [slide]);

  useEffect(() => {
    if (paused) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = window.setInterval(() => next(), AUTO_MS);
    return () => window.clearInterval(id);
  }, [paused, total]);

  const onTouchStart = (e) => {
    touchX.current = e.changedTouches[0].clientX;
  };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (Math.abs(dx) < 48) return;
    if (dx < 0) next();
    else prev();
  };

  const slideClass = (i) => {
    const parts = ["hero-slide"];
    if (i === 1) parts.push("hero-slide--team");
    if (i === slide) parts.push("is-active");
    if (i === prevSlide) parts.push("is-exit");
    if (dir < 0) parts.push("is-rev");
    return parts.join(" ");
  };

  const teamVisitSteps = [
    { n: 1, title: "Welcomed", text: "Settled in, never a waiting room.", tone: "teal" },
    { n: 2, title: "Heard in full", text: "Symptoms, exam & scans reviewed.", tone: "teal" },
    { n: 3, title: "Dr. Reddy, briefed", text: "Knows your history — no repeating.", tone: "gold" },
    { n: 4, title: "Clear plan", text: "Every option, with real timelines.", tone: "gold" },
  ];

  return (
    <header className="hero">
      <div className="hero-bg" />
      <div
        className="hero-carousel"
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        onFocusCapture={() => setPaused(true)}
        onBlurCapture={(e) => {
          if (!e.currentTarget.contains(e.relatedTarget)) setPaused(false);
        }}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
      >
        <div className="hero-carousel-viewport" aria-live="polite">
          <div className={slideClass(0)} aria-hidden={slide !== 0}>
            <div className="wrap hero-grid">
              <div className="hero-text reveal">
                <Eyebrow>Neuro &amp; Spine Specialist · {CLINIC.city}</Eyebrow>
                <p className="hero-mobile-doctor">{CLINIC.doctor}</p>
                <p className="hero-mobile-title">{CLINIC.doctorTitle}</p>
                <div className="hero-mobile-creds">{CLINIC.creds.map(c => <span key={c}>{c}</span>)}</div>
                <h1>Expert care for the brain, nerve &amp; spine</h1>
                <p className="lede">{CLINIC.tagline}</p>
                <div className="hero-cta">
                  <Btn icon="arrow" onClick={() => go("booking")}>Appointment</Btn>
                  <Btn variant="ghost" onClick={() => go("about")}>Meet the Doctor</Btn>
                </div>
              </div>
              <div className="hero-portrait reveal">
                <picture className="hero-portrait-picture">
                  <source srcSet="dr-reddy-hero.webp?v=232" type="image/webp" />
                  <img ref={portraitRef} className="hero-portrait-photo" src="dr-reddy-hero.png?v=232" alt={CLINIC.doctor} width="1200" height="1700" decoding="async" fetchPriority="high" />
                </picture>
                <div className="hero-portrait-info">
                  <h3>{CLINIC.doctor}</h3>
                  <p>{CLINIC.doctorTitle}</p>
                  <div className="hero-creds">{CLINIC.creds.map(c => <span key={c}>{c}</span>)}</div>
                </div>
              </div>
            </div>
          </div>
          <div className={slideClass(1)} aria-hidden={slide !== 1}>
            <picture className="hero-team-picture">
              <source srcSet="hero-carousel-team.webp?v=164" type="image/webp" />
              <img
                ref={teamRef}
                className="hero-team-banner"
                src="hero-carousel-team.png?v=164"
                alt="Dr. Rajasekhar Reddy and the Neurospine Clinic team"
                width="1600"
                height="899"
                decoding="async"
              />
            </picture>
            <div className="hero-team-panel">
              <div className="hero-team-journey" aria-label="What you'll experience">
                {teamVisitSteps.map(s => {
                  const onLeft = s.n % 2 === 0;
                  const title = (
                    <>
                      <h4>{s.title}</h4>
                      <p>{s.text}</p>
                    </>
                  );
                  return (
                    <div className={"journey-step journey-step--" + s.tone} key={s.n}>
                      <div className="hero-team-journey-copy hero-team-journey-copy--left">
                        {onLeft ? title : null}
                      </div>
                      <div className="journey-dot">{s.n}</div>
                      <div className="hero-team-journey-copy hero-team-journey-copy--right">
                        {onLeft ? null : title}
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="hero-cta">
                <Btn icon="arrow" onClick={() => go("booking")}>Appointment</Btn>
                <Btn variant="light" onClick={() => go("about")}>Meet the Doctor</Btn>
              </div>
            </div>
          </div>
        </div>
        <button type="button" className="hero-carousel-arrow hero-carousel-arrow--prev" aria-label="Previous hero slide" onClick={prev}>
          <Icon name="chevronRight" size={22} style={{ transform: "rotate(180deg)" }} />
        </button>
        <button type="button" className="hero-carousel-arrow hero-carousel-arrow--next" aria-label="Next hero slide" onClick={next}>
          <Icon name="chevronRight" size={22} />
        </button>
        <div className="hero-carousel-dots" role="tablist" aria-label="Hero slides">
          {[0, 1].map(i => (
            <button
              key={i}
              type="button"
              role="tab"
              aria-selected={slide === i}
              aria-label={`Slide ${i + 1}`}
              className={`hero-carousel-dot${slide === i ? " is-active" : ""}`}
              onClick={() => goTo(i)}
            />
          ))}
        </div>
      </div>
    </header>
  );
}

function YashodaMark({ label }) {
  return (
    <span className="yashoda-mark" role="img" aria-label="Yashoda Hospitals">
      <span className="yashoda-mark-row">
        <img className="yashoda-mark-icon" src="yashoda-mark.svg?v=2" alt="" width="100" height="100" decoding="async" />
        <span className="yashoda-mark-name" aria-hidden="true">Yashoda</span>
      </span>
      {label ? <small>{label}</small> : null}
    </span>
  );
}

function ClinicMark({ name, label }) {
  return (
    <span className="clinic-mark" role="img" aria-label={name || "Neurospine Clinic"}>
      <span className="clinic-mark-row">
        <img className="clinic-mark-icon" src="mark-white.png" alt="" width="100" height="100" decoding="async" />
        <span className="clinic-mark-name" aria-hidden="true">{name || "Neurospine clinic"}</span>
      </span>
      {label ? <small>{label}</small> : null}
    </span>
  );
}

function ExperienceMark({ value, label }) {
  return (
    <span className="exp-mark" role="img" aria-label={(value || "") + " years of experience"}>
      <span className="exp-mark-row">
        <img className="exp-mark-icon" src="doctor-exp-icon.png" alt="" width="100" height="100" decoding="async" />
        <Counter value={value} className="em" />
      </span>
      {label ? <small>{label}</small> : null}
    </span>
  );
}

function TrustStrip() {
  return (
    <div className="trust">
      <NeuralCanvas className="fx-layer" base="220,244,239" glow="52,226,216" density={0.7} grid={true} maxLink={108} speed={0.22} />
      <EKG />
      <div className="wrap trust-inner">
        {TRUST.map((t, i) => (
          <div className={"item" + (t.logo ? " item--logo" : "")} key={i}>
            <div className="trust-main">
              {t.logo === "yashoda"
                ? <YashodaMark label={t.label} />
                : t.logo === "clinic"
                ? <ClinicMark name={t.value} label={t.label} />
                : t.logo === "experience"
                ? <ExperienceMark value={t.value} label={t.label} />
                : <>
                    {t.stars ? <Stars /> : (t.em ? <Counter value={t.value} className="em" /> : <b>{t.value}</b>)}
                    <small>{t.label}</small>
                  </>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AboutPreview({ go }) {
  return (
    <section id="about">
      <div className="wrap about-grid">
        <div className="about-text reveal">
          <Eyebrow>About the Doctor</Eyebrow>
          <h2>A steady hand and the time to listen.</h2>
          <p><strong>{CLINIC.doctor}</strong> is among {CLINIC.city}'s leading neurosurgeons, known for combining technical excellence with a calm, reassuring manner that puts patients and families at ease during difficult times.</p>
          <p>His practice covers the full spectrum of brain, nerve and spine conditions, from complex neurosurgical procedures to minimally invasive spine treatment, always guided by what is genuinely best for the patient.</p>
          <div className="about-edu">
            <h3 className="cv-title"><Icon name="cap" size={20} /> Education</h3>
            <ul className="about-edu-list">
              {EDUCATION.map(e => (
                <li key={e.year}>
                  <strong>{e.degree}</strong>, {e.inst} ({e.year})
                  {e.honor && <>, <strong className="edu-honor">🥇 {e.honor}</strong></>}
                </li>
              ))}
            </ul>
          </div>
          <div style={{ marginTop: 24 }}><Btn variant="ghost" icon="arrow" onClick={() => go("about")}>More about Dr. Reddy</Btn></div>
        </div>
        <div className="portrait reveal">
          <img className="portrait-photo" src="dr-reddy.jpg?v=286" alt={CLINIC.doctor} />
          <div className="portrait-scrim" />
          <h3>{CLINIC.doctor}</h3>
          <p>{CLINIC.doctorTitle}</p>
          <div className="creds">{CLINIC.creds.map(c => <span key={c}>{c}</span>)}</div>
        </div>
      </div>
    </section>
  );
}

function CarePreview({ go }) {
  const cards = [
    { icon: "brain", h: "Brain Surgery", p: "Tumours, trauma, hydrocephalus and vascular conditions managed with advanced neurosurgical care." },
    { icon: "spine", h: "Spine Surgery", p: "Spine tumours, TB spine, and spondylodiscitis." },
    { icon: "bolt", h: "Slip Disc & Sciatica", p: "Targeted relief from nerve compression, back and leg pain, surgery only when truly needed." },
    { icon: "clock", h: "Head & Spine Trauma", p: "Prompt, expert management of injuries to the brain, skull and spinal column." },
    { icon: "shield", h: "Minimally Invasive", p: "Keyhole and endoscopic techniques for faster recovery and smaller scars." },
    { icon: "pin", h: "Expert Opinion", p: "Clear, honest guidance when you need certainty before a major decision." },
  ];
  return (
    <section id="conditions" className="soft-bg">
      <div className="wrap">
        <div className="sec-head reveal">
          <Eyebrow>Speciality</Eyebrow>
          <h2>Comprehensive brain &amp; spine care under one expert</h2>
          <p>Select a condition to learn more about the surgeries and conditions Dr. Reddy specialises in.</p>
        </div>
        <div className="card-grid">
          {cards.map((c, i) => (
            <button key={c.h} className="card reveal" onClick={() => go("speciality")}>
              <div className="ic"><Icon name={c.icon} size={26} /></div>
              <h3>{c.h}</h3>
              <p>{c.p}</p>
              <span className="card-link">Learn more <Icon name="arrow" size={15} /></span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

function WhySection({ go }) {
  const pillars = [
    { icon: "star", title: "Expertise", text: "Thousands of brain & spine cases." },
    { icon: "shield", title: "Honesty", text: "Surgery only when truly needed." },
    { icon: "clock", title: "Clarity", text: "Complex conditions, explained simply." },
    { icon: "heart", title: "Care", text: "A calm presence for your family." },
  ];
  const journeySteps = [
    { n: 1, title: "Welcomed", text: "Settled in, never a waiting room.", tone: "teal" },
    { n: 2, title: "Heard in full", text: "Symptoms, exam & scans reviewed.", tone: "teal" },
    { n: 3, title: "Dr. Reddy, briefed", text: "Knows your history — no repeating.", tone: "gold" },
    { n: 4, title: "Clear plan", text: "Every option, with real timelines.", tone: "gold" },
  ];
  const journeyChips = [
    "On-the-day, no surprises",
    "Same team through surgery",
    "Recovery watched closely",
    "Follow-up that stays with you",
  ];

  return (
    <section id="why">
      <div className="wrap">
        <div className="sec-head reveal">
          <Eyebrow>The Patient Experience</Eyebrow>
          <h2>Why patients choose Dr. Reddy.</h2>
          <p>Skilled surgery is only part of the story. Here is how our team works together, the principles that guide every consultation, and what you can expect at each step.</p>
        </div>

        <div className="why-pillars reveal">
          {pillars.map(p => (
            <div className="why-pillar" key={p.title}>
              <div className="why-pillar-icon" aria-hidden="true">
                <Icon name={p.icon} size={24} stroke={1.7} />
              </div>
              <h3>{p.title}</h3>
              <p>{p.text}</p>
            </div>
          ))}
        </div>

        <div className="why-block why-journey reveal">
          <Eyebrow>What you&apos;ll experience</Eyebrow>
          <h3 className="why-journey-title">Care that&apos;s ready before you arrive.</h3>
          <div className="journey-rail">
            {journeySteps.map(s => (
              <div className={"journey-step journey-step--" + s.tone} key={s.n}>
                <div className="journey-dot">{s.n}</div>
                <h4>{s.title}</h4>
                <p>{s.text}</p>
              </div>
            ))}
          </div>
          <div className="journey-chips">
            {journeyChips.map(label => (
              <div className="journey-chip" key={label}>
                <Icon name="check" size={14} stroke={2.4} />
                <span>{label}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="why-foot reveal">
          <Btn variant="ghost" icon="arrow" onClick={() => go("why-us")}>More about our approach</Btn>
        </div>
      </div>
    </section>
  );
}

function Testimonials({ go }) {
  const featured = STORIES.slice(0, 4);
  const moreCount = STORIES.length - featured.length;
  const total = featured.length;
  const [slide, setSlide] = useState(0);
  const touchX = useRef(null);

  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = window.setInterval(() => setSlide((s) => (s + 1) % total), 6500);
    return () => window.clearInterval(id);
  }, [total]);

  const prev = () => setSlide((s) => (s - 1 + total) % total);
  const next = () => setSlide((s) => (s + 1) % total);

  const onTouchStart = (e) => {
    touchX.current = e.changedTouches[0].clientX;
  };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (Math.abs(dx) < 40) return;
    if (dx < 0) next();
    else prev();
  };

  return (
    <section id="stories" className="testi home-stories">
      <div className="aurora" />
      <div className="wrap">
        <div className="sec-head reveal">
          <Eyebrow light>Patient Stories</Eyebrow>
          <h2>In their own words.</h2>
          <p>
            Real experiences shared by patients and families.{" "}
            <button type="button" className="home-stories-inline" onClick={() => go("stories")}>
              Read all patient stories
            </button>
          </p>
        </div>
        <div className="home-story-grid home-story-grid--desktop">
          {featured.map((s, i) => (
            <StoryCard key={i} story={s} readMoreLabel="Read full story" onReadMore={() => go("stories")} />
          ))}
        </div>
        <div className="home-story-carousel" aria-roledescription="carousel" aria-label="Patient stories">
          <div
            className="home-story-carousel-viewport"
            onTouchStart={onTouchStart}
            onTouchEnd={onTouchEnd}
          >
            <div
              className="home-story-carousel-track"
              style={{ transform: `translate3d(-${slide * 100}%,0,0)` }}
            >
              {featured.map((s, i) => (
                <div
                  className={"home-story-carousel-slide" + (i === slide ? " is-active" : "")}
                  key={i}
                  aria-hidden={i !== slide}
                >
                  <StoryCard story={s} readMoreLabel="Read full story" onReadMore={() => go("stories")} />
                </div>
              ))}
            </div>
          </div>
          <button type="button" className="home-story-carousel-arrow home-story-carousel-arrow--prev" aria-label="Previous story" onClick={prev}>
            <Icon name="chevronRight" size={20} style={{ transform: "rotate(180deg)" }} />
          </button>
          <button type="button" className="home-story-carousel-arrow home-story-carousel-arrow--next" aria-label="Next story" onClick={next}>
            <Icon name="chevronRight" size={20} />
          </button>
          <div className="home-story-carousel-dots" role="tablist" aria-label="Story slides">
            {featured.map((_, i) => (
              <button
                key={i}
                type="button"
                role="tab"
                aria-selected={slide === i}
                aria-label={`Story ${i + 1}`}
                className={"home-story-carousel-dot" + (slide === i ? " is-active" : "")}
                onClick={() => setSlide(i)}
              />
            ))}
          </div>
        </div>
        <div className="home-stories-foot reveal">
          <Btn variant="light" icon="arrow" onClick={() => go("stories")}>View all patient stories</Btn>
          {moreCount > 0 &&
            <button type="button" className="home-stories-more" onClick={() => go("stories")}>
              See {moreCount} more {moreCount === 1 ? "story" : "stories"}
            </button>
          }
        </div>
      </div>
    </section>
  );
}

function ReelsSection({ go }) {
  return (
    <section id="video">
      <div className="wrap">
        <div className="sec-head reveal">
          <Eyebrow>Learn &amp; Understand</Eyebrow>
        </div>
        <ReelCarousel />
        <div className="media-yt-cta reveal">
          <Btn href={CLINIC.youtubeUrl} newTab icon="play">Visit our YouTube channel</Btn>
        </div>
      </div>
    </section>
  );
}

function PhotoShowcase() {
  const loop = [...SHOWCASE_PHOTOS, ...SHOWCASE_PHOTOS];
  const innerRef = useRef(null);
  const marqueeRef = useRef(null);

  useEffect(() => {
    const inner = innerRef.current;
    const marquee = marqueeRef.current;
    if (!inner || !marquee) return;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
    if (reduced.matches) return;

    let offset = 0;
    let paused = false;
    let raf = 0;
    let last = performance.now();
    let loopWidth = 0;
    let speed = 0;

    const measure = () => {
      loopWidth = inner.scrollWidth / 2;
      speed = loopWidth > 0 ? loopWidth / SHOWCASE_LOOP_SEC : 0;
    };

    measure();
    const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
    ro?.observe(inner);

    const tick = (now) => {
      const dt = Math.min((now - last) / 1000, 0.05);
      last = now;
      if (!paused && speed > 0) {
        offset += speed * dt;
        if (offset >= loopWidth) offset -= loopWidth;
        inner.style.transform = `translate3d(${-offset}px, 0, 0)`;
      }
      raf = requestAnimationFrame(tick);
    };

    raf = requestAnimationFrame(tick);

    const pause = () => { paused = true; };
    const resume = () => { paused = false; last = performance.now(); };
    marquee.addEventListener("mouseenter", pause);
    marquee.addEventListener("mouseleave", resume);

    return () => {
      cancelAnimationFrame(raf);
      ro?.disconnect();
      marquee.removeEventListener("mouseenter", pause);
      marquee.removeEventListener("mouseleave", resume);
      inner.style.transform = "";
    };
  }, []);

  return (
    <section id="showcase" className="soft-bg">
      <div className="wrap">
        <div className="showcase-marquee reveal" ref={marqueeRef}>
          <div className="showcase-track" role="list" aria-label="Clinic and team photos">
            <div className="showcase-track-inner" ref={innerRef}>
              {loop.map((s, i) => (
                <figure
                  key={`${s.id}-${i}`}
                  className="showcase-item"
                  role="listitem"
                  aria-hidden={i >= SHOWCASE_PHOTOS.length ? "true" : undefined}
                >
                  {s.src
                    ? <img src={s.src} alt="" loading="lazy" />
                    : <Ph label={s.ph} ratio="4 / 3" round={0} className="showcase-ph" />
                  }
                </figure>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Home({ go }) {
  useReveal();
  return (
    <main>
      <Hero go={go} />
      <TrustStrip />
      <AboutPreview go={go} />
      <ReelsSection go={go} />
      <WhySection go={go} />
      <Testimonials go={go} />
      <CarePreview go={go} />
      <LocationsSection go={go} />
      <CTABand go={go} />
    </main>
  );
}

Object.assign(window, { Home, TrustStrip });
