// Home page sections (TypeScript).
// Loaded as a global script — no import/export. Published on window at the end.

const TreatmentCard: React.FC<TreatmentCardProps> = ({ t, onBook }) => {
  const { categories } = window.RIO3_DATA;
  const cat = categories.find((c) => c.id === t.cat);
  return (
    <article className="treat-card">
      <div className="tc-top">
        <span className="tc-cat">{cat ? cat.label : ""}</span>
      </div>
      <h3>{t.name}</h3>
      <p className="tc-desc">{t.summary}</p>
      <div className="tc-foot">
        <span className="tc-duration">{t.duration}</span>
      </div>
    </article>
  );
};

const TreatmentsBlock: React.FC<PageProps> = ({ setPage, onBook }) => {
  const { treatments, featuredIds } = window.RIO3_DATA;
  const featured = featuredIds
    .map((id) => treatments.find((t) => t.id === id))
    .filter(Boolean) as Treatment[];

  return (
    <section className="section" aria-label="Treatments">
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="eyebrow">Treatments</span>
            <h2>A complete <em>integrative</em> toolkit, under one roof.</h2>
          </div>
          <p className="lede">
            Five categories of therapies — sequenced and combined into protocols by
            your clinician. Transparent pricing on all {treatments.length} treatments.
          </p>
        </div>

        <div className="treat-grid">
          {featured.map((t) => (
            <TreatmentCard key={t.id} t={t} onBook={onBook} />
          ))}
        </div>

        <div className="section-more">
          <button className="btn btn-ghost" onClick={() => setPage && setPage("treatments")}>
            See all {treatments.length} treatments <Arrow />
          </button>
        </div>
      </div>
    </section>
  );
};

const ProgramsBlock: React.FC<PageProps> = ({ setPage, onConsult }) => {
  const { programs } = window.RIO3_DATA;
  return (
    <section className="section programs-band" aria-label="Programs">
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="eyebrow">Programs</span>
            <h2>Structured care, <em>start to finish.</em></h2>
          </div>
          <p className="lede">
            Three clinician-guided program tracks — not single sessions, but complete
            courses of care with a protocol, timeline and measurable outcome.
          </p>
        </div>

        <div className="prog-grid">
          {programs.map((p, i) => (
            <article key={p.id} className="prog-card">
              <span className="pc-num">{String(i + 1).padStart(2, "0")}</span>
              <h3>{p.name}</h3>
              <div className="pc-meta">{p.tagline} · {p.duration}</div>
              <p className="pc-desc">{p.description}</p>
              <ul className="pc-tiers">
                {p.tiers.map((t) => (
                  <li key={t.id}>
                    {t.label ? `${t.label} — ${t.name}` : t.name}
                    {t.featured && <span className="pc-flag">Most requested</span>}
                  </li>
                ))}
              </ul>
              <button className="pc-link" onClick={() => setPage && setPage("programs")}>
                View program <Arrow size={12} />
              </button>
            </article>
          ))}
        </div>

        <div className="section-more">
          <button className="btn btn-light" onClick={() => onConsult && onConsult()}>
            Request a consultation <Arrow />
          </button>
          <span className="more-note">Program pricing is tailored — contact us for a quote.</span>
        </div>
      </div>
    </section>
  );
};

const TestimonialsBlock: React.FC = () => {
  const { testimonials } = window.RIO3_DATA;
  const total = testimonials.length;
  // pos 1..total are real slides; 0 = clone of last, total+1 = clone of first
  const [pos, setPos] = React.useState(1);
  const [animated, setAnimated] = React.useState(true);
  const [paused, setPaused] = React.useState(false);

  const slides = [testimonials[total - 1], ...testimonials, testimonials[0]];
  const dotIdx = ((pos - 1) % total + total) % total;

  const go = (dir: number) => { setPaused(true); setAnimated(true); setPos((p) => p + dir); };

  const onTransitionEnd = () => {
    if (pos <= 0) { setAnimated(false); setPos(total); }
    else if (pos >= total + 1) { setAnimated(false); setPos(1); }
  };

  React.useEffect(() => {
    if (!animated) requestAnimationFrame(() => requestAnimationFrame(() => setAnimated(true)));
  }, [animated]);

  React.useEffect(() => {
    if (paused) return;
    const t = setInterval(() => { setAnimated(true); setPos((p) => p + 1); }, 8000);
    return () => clearInterval(t);
  }, [dotIdx, paused]);

  return (
    <section className="section testimonials" aria-label="Patient reviews">
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="eyebrow">Patient stories</span>
            <h2>In their <em>own words.</em></h2>
          </div>
          <p className="lede">Real Google reviews from Rio3 patients.</p>
        </div>
        <div className="testi-carousel">
          <div className="testi-track-wrap">
            <div
              className="testi-track"
              style={{
                transform: `translateX(-${pos * 100}%)`,
                transition: animated ? "transform 1.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)" : "none",
              }}
              onTransitionEnd={onTransitionEnd}
            >
              {slides.map((t, i) => (
                <div key={i} className="testi">
                  <div className="stars" aria-label={`${t.stars} out of 5 stars`}>{"★".repeat(t.stars)}</div>
                  <blockquote>“{t.quote}”</blockquote>
                  <div className="testi-foot">
                    <span className="name">{t.name}</span>
                    <span className="testi-src">Google review</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="testi-controls">
            <button className="testi-btn" onClick={() => go(-1)} aria-label="Previous review">&#8592;</button>
            <div className="testi-dots">
              {testimonials.map((_, i) => (
                <button
                  key={i}
                  className={`testi-dot${i === dotIdx ? " active" : ""}`}
                  onClick={() => { setPaused(true); setAnimated(true); setPos(i + 1); }}
                  aria-label={`Review ${i + 1}`}
                />
              ))}
            </div>
            <button className="testi-btn" onClick={() => go(1)} aria-label="Next review">&#8594;</button>
          </div>
        </div>
      </div>
    </section>
  );
};

const LocationBlock: React.FC<PageProps> = ({ onBook }) => {
  const { brand, hours } = window.RIO3_DATA;
  return (
    <section className="section location" id="visit" aria-label="Location and hours">
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="eyebrow">Visit</span>
            <h2>Find us in <em>Deerfield Beach.</em></h2>
          </div>
          <p className="lede">
            On Federal Highway, a short drive from Boca Raton, Pompano Beach and
            Fort Lauderdale. Free parking on site — Suite 205, second floor.
          </p>
        </div>
        <div className="location-grid">
          <div>
            <div className="map-frame">
              <MapPlaceholder />
            </div>
            <AppleMapsLink />
          </div>
          <div className="location-info">
            <div className="loc-address">
              <div className="loc-street">{brand.address}</div>
              <div className="loc-city">{brand.city}</div>
              <div className="loc-contacts">
                <a href={`tel:${brand.phone}`}>{brand.phone}</a>
                <a href={`mailto:${brand.email}`}>{brand.email}</a>
              </div>
            </div>
            <h3 className="hours-title">Hours</h3>
            <ul className="hours">
              {hours.map((h) => (
                <li key={h.day} className={h.closed ? "closed" : ""}>
                  <span className="day">{h.day}</span>
                  <span>{h.open}</span>
                </li>
              ))}
            </ul>
            <button className="btn btn-primary" onClick={() => onBook && onBook("consultation")}>
              Book a visit <Arrow />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
};

const CtaBand: React.FC<PageProps> = ({ onBook }) => {
  const { brand } = window.RIO3_DATA;
  return (
    <section className="cta-band" aria-label="Get in touch">
      <div className="shell">
        <div className="cta-band-inner">
          <div>
            <h2>Ready when <em>you</em> are.</h2>
            <p>Start with a 90-minute intake — history, vitals and a protocol built for you.</p>
          </div>
          <div className="cta-band-actions">
            <button className="btn btn-light" onClick={() => onBook && onBook("consultation")}>
              Book a visit <Arrow />
            </button>
            <a className="cta-band-phone" href={`tel:${brand.phone}`}>or call {brand.phone}</a>
          </div>
        </div>
      </div>
    </section>
  );
};

const Home: React.FC<HomeProps> = ({ setPage, onBook, onConsult }) => (
  <>
    <Hero setPage={setPage} onBook={onBook} />
    <Marquee />
    <TreatmentsBlock setPage={setPage} onBook={onBook} />
    <ProgramsBlock setPage={setPage} onConsult={onConsult} />
    <TestimonialsBlock />
    <LocationBlock onBook={onBook} />
    <CtaBand onBook={onBook} />
  </>
);

Object.assign(window, { Home, TreatmentCard, TestimonialsBlock, CtaBand });
