/* global React, ReactDOM, TRINITY */
const { useState, useEffect, useRef, useContext, createContext, useMemo, useCallback } = React;

// ============= LANGUAGE CONTEXT =============
const LangCtx = createContext({ lang: "es", setLang: () => {} });
window.LangCtx = LangCtx;

function LangProvider({ children, initial = "es" }) {
  const [lang, setLang] = useState(initial);
  useEffect(() => {
    document.documentElement.lang = lang;
  }, [lang]);
  return React.createElement(LangCtx.Provider, { value: { lang, setLang } }, children);
}

// Hook → fetches localized string from {es, en} obj
function useT() {
  const { lang } = useContext(LangCtx);
  return (m) => {
    if (!m) return "";
    if (typeof m === "string") return m;
    if (Array.isArray(m)) return m.map((x) => (typeof x === "string" ? x : x[lang] || x.en)).join(" ");
    if (typeof m === "object" && (m.es !== undefined || m.en !== undefined)) return m[lang] || m.en || "";
    return String(m);
  };
}

// ============= REVEAL ON SCROLL =============
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === "undefined") {
      el.classList.add("in");
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -80px 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

// ============= ICONS (minimal, accessible inline SVG, no slop) =============
const Icon = ({ name, size = 20, stroke = 1.5 }) => {
  const common = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round",
    "aria-hidden": "true",
  };
  switch (name) {
    case "arrow-right":
      return <svg {...common}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case "arrow-left":
      return <svg {...common}><path d="M19 12H5M11 18l-6-6 6-6"/></svg>;
    case "phone":
      return <svg {...common}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>;
    case "mail":
      return <svg {...common}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></svg>;
    case "map-pin":
      return <svg {...common}><path d="M20 10c0 7-8 12-8 12s-8-5-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg>;
    case "clock":
      return <svg {...common}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>;
    case "star":
      return <svg {...common} fill="currentColor" stroke="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>;
    case "integrated":
      return <svg {...common}><circle cx="6" cy="6" r="3"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="18" r="3"/><path d="M9 6h6M9 18h6M6 9v6M18 9v6"/></svg>;
    case "evidence":
      return <svg {...common}><path d="M9 12l2 2 4-4"/><circle cx="12" cy="12" r="10"/></svg>;
    case "tech":
      return <svg {...common}><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></svg>;
    case "heart":
      return <svg {...common}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>;
    case "check":
      return <svg {...common}><path d="M20 6 9 17l-5-5"/></svg>;
    case "globe":
      return <svg {...common}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>;
    default: return null;
  }
};

// ============= LANGUAGE TOGGLE =============
function LangToggle() {
  const { lang, setLang } = useContext(LangCtx);
  return (
    <div className="lang-toggle" role="group" aria-label="Language selector">
      <button
        type="button"
        aria-pressed={lang === "es"}
        className={lang === "es" ? "active" : ""}
        onClick={() => setLang("es")}
      >ES</button>
      <button
        type="button"
        aria-pressed={lang === "en"}
        className={lang === "en" ? "active" : ""}
        onClick={() => setLang("en")}
      >EN</button>
    </div>
  );
}

// ============= HEADER =============
function Header({ active, onJump }) {
  const T = useT();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => { document.body.style.overflow = open ? "hidden" : ""; }, [open]);

  const nav = [
    { id: "services", label: TRINITY.ui.services },
    { id: "about", label: TRINITY.ui.about },
    { id: "testimonials", label: TRINITY.ui.testimonials },
    { id: "faq", label: TRINITY.ui.faq },
    { id: "contact", label: TRINITY.ui.contact },
  ];

  const handleJump = (id) => (e) => {
    e.preventDefault();
    setOpen(false);
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 72;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <>
      <header className={`site-header ${scrolled ? "scrolled" : ""}`}>
        <div className="container header-inner">
          <a href="#home" className="brand" onClick={handleJump("home")} aria-label="Trinity Comprehensive Healthcare home">
            <span className="brand-mark" aria-hidden="true">
              <img src="assets/favicon.svg" alt="" />
            </span>
            <span className="brand-text">
              <span>Trinity</span>
              <small>Comprehensive Health Care</small>
            </span>
          </a>

          <nav className="nav-desktop" aria-label="Primary">
            {nav.map((n) => (
              <a key={n.id} href={`#${n.id}`}
                 className={`nav-link ${active === n.id ? "active" : ""}`}
                 onClick={handleJump(n.id)}>
                {T(n.label)}
              </a>
            ))}
          </nav>

          <div className="header-actions">
            <LangToggle />
            <a href="#contact" onClick={handleJump("contact")} className="btn btn-primary book-btn">
              {T(TRINITY.ui.book)}
              <Icon name="arrow-right" size={14}/>
            </a>
            <button
              type="button"
              aria-label={open ? T(TRINITY.ui.closeMenu) : T(TRINITY.ui.menu)}
              aria-expanded={open}
              className={`menu-btn ${open ? "open" : ""}`}
              onClick={() => setOpen((v) => !v)}
            >
              <span></span>
            </button>
          </div>
        </div>
      </header>

      <div className={`mobile-menu ${open ? "open" : ""}`} role="dialog" aria-modal="true" aria-label="Site navigation">
        <nav aria-label="Mobile">
          {nav.map((n) => (
            <a key={n.id} href={`#${n.id}`} onClick={handleJump(n.id)}>{T(n.label)}</a>
          ))}
        </nav>
        <div className="mm-foot">
          <a href={TRINITY.contact.phoneHref}>{TRINITY.contact.phone}</a>
          <span>{TRINITY.contact.address}</span>
        </div>
      </div>
    </>
  );
}

// ============= HERO =============
function Hero() {
  const T = useT();
  const ref = useReveal();
  const { lang } = useContext(LangCtx);
  const titleLines = TRINITY.hero.title[lang] || TRINITY.hero.title.en;
  const emWord = (TRINITY.hero.titleEm[lang] || TRINITY.hero.titleEm.en).trim();

  // Render last word as italic serif accent
  const renderLine = (line, isLast) => {
    if (!isLast) return line;
    const idx = line.toLowerCase().lastIndexOf(emWord.toLowerCase());
    if (idx === -1) return line;
    return (
      <>
        {line.slice(0, idx)}
        <span className="serif-em">{line.slice(idx, idx + emWord.length)}</span>
        {line.slice(idx + emWord.length)}
      </>
    );
  };

  return (
    <section id="home" className="container">
      <div className="hero reveal" ref={ref}>
        <div className="hero-grid">
          <div>
            <span className="eyebrow"><span className="dot"></span> {T(TRINITY.hero.eyebrow)}</span>
            <h1 style={{ marginTop: "var(--s-4)" }}>
              {titleLines.map((line, i) => (
                <span key={i} style={{ display: "block" }}>
                  {renderLine(line, i === titleLines.length - 1)}
                </span>
              ))}
            </h1>
            <p className="hero-sub">{T(TRINITY.hero.sub)}</p>

            <div className="hero-cta">
              <a href="#contact" className="btn btn-primary"
                 onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth", block: "start" }); }}>
                {T(TRINITY.ui.book)} <Icon name="arrow-right" size={14}/>
              </a>
              <a href={TRINITY.contact.phoneHref} className="btn btn-ghost">
                <Icon name="phone" size={14}/> {TRINITY.contact.phone}
              </a>
            </div>

            <div className="hero-meta">
              {TRINITY.hero.meta.map((m, i) => (
                <span key={i} className="hero-meta-item"><span className="ico"></span> {T(m)}</span>
              ))}
            </div>
          </div>

          <div className="hero-visual">
            <img src="assets/hero-image.png" alt={T({ es: "Equipo médico de Trinity con paciente en consulta", en: "Trinity medical team with patient during consultation" })} loading="eager"/>
            <div className="hero-stat-card top">
              <span className="big">4.9★</span>
              <span className="lbl">{T({ es: "Promedio paciente", en: "Patient avg." })}</span>
            </div>
          </div>
        </div>

        <div className="trust-strip" style={{ marginTop: "var(--s-7)" }}>
          {TRINITY.trust.map((tr, i) => (
            <div key={i} className="trust-item">
              <span className="num">{tr.num}</span>
              <span className="lbl">{T(tr.lbl)}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============= SECTION HEAD helper =============
function SectionHead({ eyebrow, title, sub, split = true }) {
  const T = useT();
  const { lang } = useContext(LangCtx);
  const lines = title?.[lang] || title?.en || [];
  return (
    <div className={`s-head ${split ? "split" : ""}`}>
      <div>
        {eyebrow && <span className="eyebrow"><span className="dot"></span> {T(eyebrow)}</span>}
        <h2 style={{ marginTop: "var(--s-3)" }}>
          {lines.map((l, i) => {
            // italicize middle line if 3 lines
            if (lines.length === 3 && i === 1) return <span key={i} style={{ display: "block" }}><span className="em">{l}</span></span>;
            return <span key={i} style={{ display: "block" }}>{l}</span>;
          })}
        </h2>
      </div>
      {sub && <p>{T(sub)}</p>}
    </div>
  );
}

// ============= SERVICE PILLARS =============
function Pillars() {
  const T = useT();
  const ref = useReveal();
  return (
    <section id="services" className="container section reveal" ref={ref}>
      <SectionHead eyebrow={TRINITY.pillars.eyebrow} title={TRINITY.pillars.title} sub={TRINITY.pillars.sub}/>
      <div className="pillars">
        {TRINITY.pillars.items.map((p, i) => (
          <article key={i} className="pillar" tabIndex="0">
            <span className="pillar-num">{p.num}</span>
            <h3>{T(p.title)}</h3>
            <p>{T(p.body)}</p>
            <div className="pillar-tags">
              {p.tags.map((tg, j) => <span key={j}>{T(tg)}</span>)}
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

// ============= FEATURED TREATMENTS =============
function Featured() {
  const T = useT();
  const ref = useReveal();
  return (
    <section className="container section reveal" ref={ref}>
      <div className="duo-band">
        <div className="duo-img">
          <img src="assets/gallery-image-1.png" alt={T({ es: "Tratamiento de estética médica", en: "Medical aesthetic treatment" })} loading="lazy"/>
          <span className="tag">{T({ es: "Estética médica", en: "Medical aesthetics" })}</span>
        </div>
        <div className="duo-img tall">
          <img src="assets/contact-page.png" alt={T({ es: "Recepción bilingüe de Trinity", en: "Trinity bilingual reception" })} loading="lazy"/>
          <span className="tag">{T({ es: "Bienvenida bilingüe", en: "Bilingual welcome" })}</span>
        </div>
      </div>
      <SectionHead eyebrow={TRINITY.featured.eyebrow} title={TRINITY.featured.title} sub={TRINITY.featured.sub}/>
      <div className="featured-list">
        {TRINITY.featured.items.map((f) => (
          <div key={f.n} className="feat-row">
            <span className="feat-num">{f.n}</span>
            <div>
              <div className="feat-name">{T(f.name)}</div>
              <div className="feat-cat" style={{ marginTop: "0.4em" }}>{T(f.cat)}</div>
            </div>
            <p className="feat-desc">{T(f.desc)}</p>
            <span className="feat-cat" style={{ display: "inline-flex", alignItems: "center", gap: "0.4em" }}>
              <Icon name="clock" size={14}/> {T(f.time)}
            </span>
            <a href="#contact" className="feat-cta"
               onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth" }); }}>
              {T({ es: "Reservar", en: "Book" })} <Icon name="arrow-right" size={12}/>
            </a>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============= ABOUT / DOCTOR =============
function About() {
  const T = useT();
  const ref = useReveal();
  return (
    <section id="about" className="container section reveal" ref={ref}>
      <div className="about-block">
        <div className="about-portrait">
          <img src="assets/about-us.png" alt={T({ es: "Equipo médico de Trinity Comprehensive", en: "Trinity Comprehensive medical team" })} loading="lazy"/>
        </div>
        <div className="about-text">
          <span className="eyebrow"><span className="dot"></span> {T(TRINITY.about.eyebrow)}</span>
          <h2 style={{ marginTop: "var(--s-3)" }}>{T({
            es: "Una práctica donde la medicina, la regeneración y la estética se hablan.",
            en: "A practice where medicine, regeneration, and aesthetics talk to each other.",
          })}</h2>
          <p className="quote">{T(TRINITY.about.quote)}</p>
          <p className="desc">{T(TRINITY.about.desc)}</p>
          <div className="about-attrib-list">
            {TRINITY.about.team.map((member, i) => (
              <div key={i} className="about-attrib">
                <span className="avatar">{member.avatar}</span>
                <div>
                  <div className="name">{member.name}</div>
                  <div className="role">{T(member.role)}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============= WHY US =============
function WhyUs() {
  const T = useT();
  const ref = useReveal();
  return (
    <section className="container section-tight reveal" ref={ref}>
      <SectionHead eyebrow={TRINITY.why.eyebrow} title={TRINITY.why.title}/>
      <div className="why-grid">
        {TRINITY.why.items.map((w, i) => (
          <div key={i} className="why-card">
            <div className="why-icon"><Icon name={w.icon} size={22}/></div>
            <h3>{T(w.title)}</h3>
            <p>{T(w.body)}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============= TESTIMONIALS CAROUSEL =============
function Testimonials() {
  const T = useT();
  const ref = useReveal();
  const [idx, setIdx] = useState(0);
  const items = TRINITY.testimonials.items;
  const prev = () => setIdx((i) => (i - 1 + items.length) % items.length);
  const next = () => setIdx((i) => (i + 1) % items.length);

  useEffect(() => {
    const timer = setInterval(() => setIdx((i) => (i + 1) % items.length), 7000);
    return () => clearInterval(timer);
  }, [items.length]);

  return (
    <section id="testimonials" className="container section reveal" ref={ref}>
      <div className="testi-wrap">
        <div className="testi-photo" aria-hidden="true">
          <img src="assets/services.png" alt="" loading="lazy"/>
        </div>
        <div className="testi-content">
        <div className="testi-head">
          <div>
            <span className="eyebrow" style={{ color: "var(--accent-2)" }}>
              <span className="dot" style={{ background: "var(--warm-gold)" }}></span> {T(TRINITY.testimonials.eyebrow)}
            </span>
            <h2 style={{ marginTop: "var(--s-3)", fontSize: "var(--fs-2xl)" }}>
              {(TRINITY.testimonials.title[useContext(LangCtx).lang] || TRINITY.testimonials.title.en).map((l, i, arr) => (
                <span key={i} style={{ display: "block" }}>
                  {arr.length === 3 && i === 1 ? <span style={{ fontFamily: "'Instrument Serif', serif", fontStyle: "italic", fontWeight: 400, color: "var(--warm-gold)" }}>{l}</span> : l}
                </span>
              ))}
            </h2>
          </div>
          <div className="testi-controls">
            <button type="button" onClick={prev} aria-label="Previous testimonial"><Icon name="arrow-left" size={18}/></button>
            <button type="button" onClick={next} aria-label="Next testimonial"><Icon name="arrow-right" size={18}/></button>
          </div>
        </div>

        <div style={{ overflow: "hidden" }}>
          <div className="testi-track" style={{ transform: `translateX(-${idx * 100}%)` }}>
            {items.map((t2, i) => (
              <div key={i} className="testi-card">
                <div className="testi-stars" aria-label={`${t2.rating} out of 5`}>
                  {Array.from({ length: t2.rating }).map((_, j) => <Icon key={j} name="star" size={16}/>)}
                </div>
                <p className="testi-quote">{T(t2.quote)}</p>
                <div className="testi-by">
                  <span className="av">{T(t2.name).charAt(0)}</span>
                  <div>
                    <div className="nm">{T(t2.name)}</div>
                    <div className="tx">{T(t2.treatment)} · {T(t2.loc)}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: "flex", gap: "0.4em", marginTop: "var(--s-5)" }} role="tablist">
          {items.map((_, i) => (
            <button key={i} role="tab" aria-selected={i === idx} aria-label={`Slide ${i+1}`}
                    onClick={() => setIdx(i)}
                    style={{
                      width: i === idx ? "2em" : "0.6em", height: "0.4em",
                      borderRadius: "999em",
                      background: i === idx ? "var(--surface)" : "rgba(255,255,255,.3)",
                      transition: "all 320ms cubic-bezier(.2,.7,.2,1)",
                      minHeight: "auto",
                    }}/>
          ))}
        </div>
        </div>
      </div>
    </section>
  );
}

// ============= FAQ =============
function FAQ() {
  const T = useT();
  const ref = useReveal();
  const [cat, setCat] = useState("general");
  const [openIdx, setOpenIdx] = useState(0);

  const items = TRINITY.faq.items.filter((it) => it.cat === cat);

  return (
    <section id="faq" className="container section reveal" ref={ref}>
      <SectionHead eyebrow={TRINITY.faq.eyebrow} title={TRINITY.faq.title}/>
      <div className="faq-grid">
        <div className="faq-cats" role="tablist" aria-label="FAQ categories">
          {TRINITY.faq.cats.map((c) => (
            <button key={c.id}
                    role="tab"
                    aria-selected={c.id === cat}
                    className={c.id === cat ? "active" : ""}
                    onClick={() => { setCat(c.id); setOpenIdx(0); }}>
              {T(c.label)}
            </button>
          ))}
        </div>
        <div className="faq-list">
          {items.length === 0 && (
            <p style={{ color: "var(--muted)", padding: "var(--s-4) 0" }}>
              {T({ es: "Próximamente más preguntas.", en: "More questions coming soon." })}
            </p>
          )}
          {items.map((it, i) => {
            const open = openIdx === i;
            return (
              <div key={i} className={`faq-item ${open ? "open" : ""}`}>
                <button className="faq-q" aria-expanded={open} onClick={() => setOpenIdx(open ? -1 : i)}>
                  <span>{T(it.q)}</span>
                  <span className="plus" aria-hidden="true">+</span>
                </button>
                <div className="faq-a" role="region">
                  <p>{T(it.a)}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ============= CTA BANNER =============
function CTABanner() {
  const T = useT();
  const ref = useReveal();
  const { lang } = useContext(LangCtx);
  const lines = TRINITY.cta.title[lang] || TRINITY.cta.title.en;
  return (
    <section className="container reveal" ref={ref}>
      <div className="cta-banner">
        <div>
          <h2>
            {lines.map((l, i, arr) => (
              <span key={i} style={{ display: "block" }}>
                {arr.length === 3 && i === 1 ? <span className="em">{l}</span> : l}
              </span>
            ))}
          </h2>
          <p>{T(TRINITY.cta.sub)}</p>
        </div>
        <div className="actions">
          <a href="#contact" className="btn btn-primary"
             onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth" }); }}>
            {T(TRINITY.ui.book)} <Icon name="arrow-right" size={14}/>
          </a>
          <a href={TRINITY.contact.phoneHref} className="btn btn-ghost">
            <Icon name="phone" size={14}/> {T(TRINITY.ui.call)}
          </a>
        </div>
      </div>
    </section>
  );
}

// ============= CONTACT =============
function ContactSection() {
  const T = useT();
  const ref = useReveal();
  const [form, setForm] = useState({ name: "", email: "", phone: "", interest: "", message: "" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const { lang } = useContext(LangCtx);

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = TRINITY.contactSection.errors.name;
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = TRINITY.contactSection.errors.email;
    if (!form.phone.trim()) e.phone = TRINITY.contactSection.errors.phone;
    if (!form.interest) e.interest = TRINITY.contactSection.errors.interest;
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setSent(true);
    setTimeout(() => { setSent(false); setForm({ name: "", email: "", phone: "", interest: "", message: "" }); }, 4200);
  };

  const onField = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  return (
    <section id="contact" className="container section reveal" ref={ref}>
      <SectionHead eyebrow={TRINITY.contactSection.eyebrow} title={TRINITY.contactSection.title} sub={TRINITY.contactSection.sub}/>

      <div className="contact-block">
        <div className="contact-info">
          <div className="map-block" aria-label={T({ es: "Mapa de la ubicación", en: "Location map" })}>
            <iframe
              title={T({ es: "Mapa de Trinity Comprehensive Health Care", en: "Trinity Comprehensive Health Care location map" })}
              src="https://www.google.com/maps?q=7000+SW+97th+Avenue+Suite+110+Miami+FL+33173&output=embed"
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              style={{ border: 0, width: "100%", height: "100%", display: "block" }}
            />
          </div>

          <div>
            <div className="contact-line">
              <span className="lbl">{T({ es: "Dirección", en: "Address" })}</span>
              <span className="val">
                {TRINITY.contact.addressLines.map((l, i) => <div key={i}>{l}</div>)}
              </span>
            </div>
            <div className="contact-line">
              <span className="lbl">{T({ es: "Teléfono", en: "Phone" })}</span>
              <span className="val"><a href={TRINITY.contact.phoneHref}>{TRINITY.contact.phone}</a></span>
            </div>
            <div className="contact-line">
              <span className="lbl">{T({ es: "Email", en: "Email" })}</span>
              <span className="val" style={{ wordBreak: "break-all" }}><a href={`mailto:${TRINITY.contact.email}`}>{TRINITY.contact.email}</a></span>
            </div>
            <div className="contact-line">
              <span className="lbl">{T({ es: "Horarios", en: "Hours" })}</span>
              <span className="val" style={{ fontSize: "var(--fs-sm)" }}>
                {(TRINITY.contact.hoursLines[lang] || TRINITY.contact.hoursLines.en).map((l, i) => <div key={i}>{l}</div>)}
              </span>
            </div>
          </div>
        </div>

        <form className="contact-form" onSubmit={submit} noValidate>
          <h3 style={{ fontSize: "var(--fs-lg)", letterSpacing: "-0.02em" }}>{T(TRINITY.contactSection.formTitle)}</h3>
          <p style={{ fontSize: "var(--fs-sm)", color: "var(--muted)", marginTop: "calc(-1 * var(--s-2))" }}>
            {T(TRINITY.contactSection.formSub)}
          </p>

          {sent && (
            <div className="form-success">
              <Icon name="check" size={16}/> {T(TRINITY.contactSection.success)}
            </div>
          )}

          <div className={`field ${errors.name ? "error" : ""}`}>
            <label htmlFor="f-name">{T(TRINITY.contactSection.labels.name)}</label>
            <input id="f-name" type="text" value={form.name} onChange={onField("name")} autoComplete="name"/>
            {errors.name && <span className="field-err">{T(errors.name)}</span>}
          </div>

          <div className="row-2">
            <div className={`field ${errors.email ? "error" : ""}`}>
              <label htmlFor="f-email">{T(TRINITY.contactSection.labels.email)}</label>
              <input id="f-email" type="email" value={form.email} onChange={onField("email")} autoComplete="email"/>
              {errors.email && <span className="field-err">{T(errors.email)}</span>}
            </div>
            <div className={`field ${errors.phone ? "error" : ""}`}>
              <label htmlFor="f-phone">{T(TRINITY.contactSection.labels.phone)}</label>
              <input id="f-phone" type="tel" value={form.phone} onChange={onField("phone")} autoComplete="tel"/>
              {errors.phone && <span className="field-err">{T(errors.phone)}</span>}
            </div>
          </div>

          <div className={`field ${errors.interest ? "error" : ""}`}>
            <label htmlFor="f-int">{T(TRINITY.contactSection.labels.interest)}</label>
            <select id="f-int" value={form.interest} onChange={onField("interest")}>
              <option value="">{T(TRINITY.contactSection.labels.placeholderInterest)}</option>
              {TRINITY.contactSection.interests.map((i) => (
                <option key={i.v} value={i.v}>{T(i.l)}</option>
              ))}
            </select>
            {errors.interest && <span className="field-err">{T(errors.interest)}</span>}
          </div>

          <div className="field">
            <label htmlFor="f-msg">{T(TRINITY.contactSection.labels.message)}</label>
            <textarea id="f-msg" rows="4" value={form.message} onChange={onField("message")}/>
          </div>

          <button type="submit" className="btn btn-primary" style={{ marginTop: "var(--s-2)", alignSelf: "flex-start" }}>
            {T(TRINITY.contactSection.submit)} <Icon name="arrow-right" size={14}/>
          </button>
        </form>
      </div>
    </section>
  );
}

// ============= FOOTER =============
function Footer() {
  const T = useT();
  const year = new Date().getFullYear();
  return (
    <footer className="site-foot">
      <div className="container">
        <div className="foot-grid">
          <div className="foot-brand">
            <div className="brand">
              <span className="brand-mark" aria-hidden="true">
                <img src="assets/favicon.svg" alt="" />
              </span>
              <span className="brand-text">
                <span>Trinity</span>
                <small style={{ color: "rgba(255,255,255,.5)" }}>Comprehensive Health Care</small>
              </span>
            </div>
            <p>{T(TRINITY.business.tagline)}</p>
          </div>
          <div className="foot-col">
            <h4>{T(TRINITY.ui.services)}</h4>
            <ul>
              {TRINITY.pillars.items.map((p, i) => (
                <li key={i}><a href="#services" onClick={(e) => { e.preventDefault(); document.getElementById("services")?.scrollIntoView({ behavior: "smooth" }); }}>{T(p.title)}</a></li>
              ))}
            </ul>
          </div>
          <div className="foot-col">
            <h4>{T({ es: "Práctica", en: "Practice" })}</h4>
            <ul>
              <li><a href="#about" onClick={(e) => { e.preventDefault(); document.getElementById("about")?.scrollIntoView({ behavior: "smooth" }); }}>{T(TRINITY.ui.about)}</a></li>
              <li><a href="#testimonials" onClick={(e) => { e.preventDefault(); document.getElementById("testimonials")?.scrollIntoView({ behavior: "smooth" }); }}>{T(TRINITY.ui.testimonials)}</a></li>
              <li><a href="#faq" onClick={(e) => { e.preventDefault(); document.getElementById("faq")?.scrollIntoView({ behavior: "smooth" }); }}>{T(TRINITY.ui.faq)}</a></li>
              <li><a href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth" }); }}>{T(TRINITY.ui.contact)}</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h4>{T({ es: "Visítenos", en: "Visit" })}</h4>
            <ul>
              <li>{TRINITY.contact.addressLines[0]}</li>
              <li>{TRINITY.contact.addressLines[1]}</li>
              <li><a href={TRINITY.contact.phoneHref}>{TRINITY.contact.phone}</a></li>
              <li><a href={`mailto:${TRINITY.contact.email}`} style={{ wordBreak: "break-all" }}>{TRINITY.contact.email}</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© {year} Trinity Comprehensive Health Care, Inc. {T({ es: "Todos los derechos reservados.", en: "All rights reserved." })}</span>
          <div className="links">
            <a href="#">{T({ es: "Privacidad", en: "Privacy" })}</a>
            <a href="#">{T({ es: "Términos", en: "Terms" })}</a>
            <a href="#">{T({ es: "Cookies", en: "Cookies" })}</a>
            <a href="#">{T({ es: "Accesibilidad", en: "Accessibility" })}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ============= TWEAKS PANEL =============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "warm",
  "accent": "blue",
  "density": "default",
  "lang": "es"
}/*EDITMODE-END*/;

function TweaksUI() {
  const { setLang, lang } = useContext(LangCtx);
  if (!window.useTweaks || !window.TweaksPanel) return null;
  const [tw, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    document.body.dataset.theme = tw.theme;
    document.body.dataset.accent = tw.accent;
    document.body.dataset.density = tw.density;
  }, [tw.theme, tw.accent, tw.density]);

  useEffect(() => {
    if (tw.lang && tw.lang !== lang) setLang(tw.lang);
    // eslint-disable-next-line
  }, [tw.lang]);

  const { TweaksPanel, TweakSection, TweakRadio } = window;

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Language" />
      <TweakRadio
        label="Lang"
        value={tw.lang}
        onChange={(v) => setTweak("lang", v)}
        options={[
          { value: "es", label: "ES" },
          { value: "en", label: "EN" },
        ]}
      />
      <TweakSection label="Surface" />
      <TweakRadio
        label="Theme"
        value={tw.theme}
        onChange={(v) => setTweak("theme", v)}
        options={[
          { value: "warm", label: "Warm" },
          { value: "clinical", label: "Clinical" },
          { value: "botanical", label: "Botanic" },
        ]}
      />
      <TweakRadio
        label="Accent"
        value={tw.accent}
        onChange={(v) => setTweak("accent", v)}
        options={[
          { value: "blue", label: "Blue" },
          { value: "teal", label: "Teal" },
          { value: "green", label: "Green" },
        ]}
      />
      <TweakSection label="Layout" />
      <TweakRadio
        label="Density"
        value={tw.density}
        onChange={(v) => setTweak("density", v)}
        options={[
          { value: "compact", label: "Compact" },
          { value: "default", label: "Default" },
          { value: "spacious", label: "Spacious" },
        ]}
      />
    </TweaksPanel>
  );
}

// ============= ROOT =============
function ActiveSectionTracker({ onChange }) {
  useEffect(() => {
    const ids = ["home", "services", "about", "testimonials", "faq", "contact"];
    const els = ids.map((id) => document.getElementById(id)).filter(Boolean);
    if (els.length === 0) return;
    const io = new IntersectionObserver(
      (entries) => {
        const vis = entries.filter((e) => e.isIntersecting).sort((a, b) => b.intersectionRatio - a.intersectionRatio);
        if (vis[0]) onChange(vis[0].target.id);
      },
      { threshold: [0.25, 0.5, 0.75], rootMargin: "-80px 0px -50% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [onChange]);
  return null;
}

function App() {
  const [active, setActive] = useState("home");
  return (
    <LangProvider initial="es">
      <a href="#main" className="skip-link">Skip to main content</a>
      <Header active={active} />
      <ActiveSectionTracker onChange={setActive} />
      <main id="main">
        <Hero />
        <Pillars />
        <Featured />
        <About />
        <WhyUs />
        <Testimonials />
        <FAQ />
        <CTABanner />
        <ContactSection />
      </main>
      <Footer />
      <TweaksUI />
    </LangProvider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
