/* global React, LINKS, Icon */
const { useState, useEffect, useRef } = React;

/* ============== Hero (sales-first, social proof) ============== */
function Hero({ t, lang, openModal }) {
  const s = t.social;
  const tItems = t.testimonials.items;
  // short running snippets
  const snippets = tItems.map((x) => ({
    q: x.q.length > 88 ? x.q.slice(0, 85).trim() + "…" : x.q,
    a: x.a, loc: x.loc
  }));
  const runItems = [...snippets, ...snippets];
  const avatars = tItems.slice(0, 4).map((x) => x.a.slice(0, 1));

  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="hero-top">
          <div className="hero-head">
            <span className="hero-badge">{Icon.leaf()}<span className="hb-text">{(() => {
              const ey = t.hero.eyebrow;
              const i = ey.indexOf("Psicoterapia");
              return i > 0
                ? <React.Fragment>{ey.slice(0, i)}<br className="hb-br" />{ey.slice(i)}</React.Fragment>
                : ey;
            })()}</span></span>
            <h1 className="hero-h1">
              {t.hero.title1} <span className="italic">{t.hero.title2}</span>
            </h1>
            <p className="lead hero-sub">
              {t.hero.subA}{" "}
              {t.hero.countries.map((c, i) =>
              <React.Fragment key={i}>
                  <mark className="country-mark">{c}</mark>{i < t.hero.countries.length - 1 ? " " : " "}
                </React.Fragment>
              )}
              {t.hero.subB}
            </p>
            <div className="hero-ctas">
              <a className="btn btn-sage" href="#contacto">{t.hero.cta} {Icon.arrow()}</a>
              <button className="btn btn-ghost" onClick={() => openModal("about")}>{t.hero.aboutBtn}</button>
            </div>
          </div>
          <div className="hero-portrait">
            <img src="assets/foto guillermina con titulo.jpeg" alt="Lic. Guillermina Gómez" loading="eager" style={{ objectFit: "cover" }} />
          </div>
        </div>

        <div className="hero-social">
          {/* rating block — costado */}
          <div className="rating-card">
            <div className="rating-num">{s.ratingValue}</div>
            <div className="rating-stars">
              <span className="stars">{[0, 1, 2, 3, 4].map((i) => <span key={i}>{Icon.star(15)}</span>)}</span>
              <span className="rating-label">{s.ratingLabel}</span>
            </div>
            <div className="rating-foot">
              <div className="rating-avatars">
                {avatars.map((a, i) => <span key={i} className="rav">{a}</span>)}
              </div>
              <span className="rating-count">{s.ratingCount}</span>
            </div>
          </div>

          {/* running testimonials — medio */}
          <div className="running-card">
            <div className="running-head">
              <span className="running-title"><span className="run-dot"></span>{s.running}</span>
              <button className="link-btn" onClick={() => openModal("testimonials")}>
                {s.seeAll} {Icon.arrow("")}
              </button>
            </div>
            <div className="running-viewport">
              <div className="running-track">
                {runItems.map((r, i) =>
                <div key={i} className="run-item">
                    <p className="run-q">"{r.q}"</p>
                    <span className="run-a">— {r.a} <span className="run-loc">· {r.loc}</span></span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* stats band — abajo */}
        <div className="hero-stats">
          <div className="hs-items">
            {s.stats.map((st, i) =>
            <div key={i} className="hs-stat">
                <div className="hs-n">{st.n}</div>
                <div className="hs-l">{st.l}</div>
              </div>
            )}
          </div>
          <button className="link-btn hs-btn" onClick={() => openModal("credentials")}>
            {s.seeList} {Icon.arrow("")}
          </button>
        </div>
      </div>
    </section>);
}

/* ============== Currency toggle ============== */
function CurrencyToggle({ t, cur, setCur, light, hideLabel }) {
  return (
    <div className={`cur-toggle ${light ? "light" : ""} ${hideLabel ? "bare" : ""}`}>
      {!hideLabel && <span className="cur-label">{t.services.curLabel}</span>}
      <div className="cur-seg">
        <button className={cur === "usd" ? "active" : ""} onClick={() => setCur("usd")}>USD</button>
        <button className={cur === "ars" ? "active" : ""} onClick={() => setCur("ars")}>ARS</button>
      </div>
    </div>);
}

function Services({ t, cur, setCur }) {
  const items = t.services.items.map((it, idx) => ({ ...it, _idx: idx }));
  const iconFor = (it) => {
    const n = (it.tag + " " + it.name).toLowerCase();
    if (n.includes("solicitado") || n.includes("requested") || n.includes("pareja") || n.includes("couple")) return Icon.couples(26);
    if (n.includes("individual")) return Icon.person(26);
    return Icon.cap(26);
  };
  const isFeatured = (it) => {
    const n = it.tag.toLowerCase();
    return n.includes("solicitado") || n.includes("requested");
  };
  const [active, setActive] = useState(() => {
    const f = items.findIndex(isFeatured);
    return f >= 0 ? f : 0;
  });
  const sv = items[active] || items[0];

  return (
    <section id="servicios">
      <div className="wrap">
        <div className="sec-head-c">
          <h2>{t.services.title}</h2>
          <p className="lead">{t.services.sub}</p>
        </div>

        <div className="svc-tabs" role="tablist">
          {items.map((it, i) =>
          <button
            key={i}
            role="tab"
            aria-selected={active === i}
            className={`svc-tab ${active === i ? "active" : ""}`}
            onClick={() => setActive(i)}>
              <span className="svc-tab-ic">{iconFor(it)}</span>
              <span className="svc-tab-name">{(() => {
                const i = it.name.indexOf("&");
                if (i < 0) return it.name;
                return <React.Fragment>{it.name.slice(0, i + 1)}{" "}<br className="svc-br" />{it.name.slice(i + 1).trimStart()}</React.Fragment>;
              })()}</span>
            </button>
          )}
        </div>

        <div className="svc-panel" key={active}>
          <div className="svc-panel-main">
            {isFeatured(sv) && <span className="svc-panel-tag">{sv.tag}</span>}
            <p className="svc-panel-desc">{sv.desc}</p>
            {sv.bulletsTitle && <span className="pc-sub">{sv.bulletsTitle}</span>}
            <ul className="svc-panel-list">
              {sv.bullets.map((b, j) =>
              <li key={j}><span className="pc-check">{Icon.check(15)}</span>{b}</li>
              )}
            </ul>
            <div className="svc-panel-meta">
              {sv.metaTitle && <span className="pc-meta-title">{sv.metaTitle}</span>}
              <div className="svc-panel-meta-rows">
                {sv.meta.map((md, j) => <span key={j} className="pc-meta-row">{md}</span>)}
              </div>
            </div>
          </div>

          <aside className="svc-panel-aside">
            {sv.pricing ?
            <>
                <div className="svc-cur-row">
                  <CurrencyToggle t={t} cur={cur} setCur={setCur} hideLabel={true} />
                </div>
                <div className="pc-price-first">
                  <span className="pc-price-lbl">{sv.pricing.firstLabel}</span>
                  <span className="pc-price-val">{cur === "ars" && sv.pricing.firstArs != null ? formatArs(sv.pricing.firstArs) : formatPrice(sv.pricing.first, cur)}</span>
                </div>
                <div className="pc-packs">
                  <span className="pc-packs-title">{sv.pricing.packsTitle}</span>
                  {(cur === "ars" && sv.pricing.packsArs ? sv.pricing.packsArs : sv.pricing.packs).map((p, j) => (
                <div key={j} className="pc-pack-row">
                      <span>{p.n} {t.services.sessions}</span>
                      <span className="pc-pack-val">{p.ars != null ? formatArs(p.ars) : formatPrice(p.usd, cur)}</span>
                    </div>
                ))}
                </div>
              </> :
            <div className="pc-price-first">
                <span className="pc-price-val">{t.services.customPrice}</span>
              </div>
            }
            <a href="#contacto" className="pc-cta">{sv.cta} {Icon.arrow()}</a>
          </aside>
        </div>

        <p className="pc-fxnote">{t.services.fxNote}</p>
      </div>
    </section>);
}

/* ============== Manifesto ============== */
function Manifesto({ t, lang }) {
  const bgUrl = "https://images.unsplash.com/photo-1621933339571-a38230d0d974?w=1800&q=80&auto=format&fit=crop";
  return (
    <section className="manifesto">
      <div className="manifesto-bg" style={{ backgroundImage: `url(${bgUrl})` }}></div>
      <div className="manifesto-overlay"></div>
      <div className="wrap manifesto-inner">
        <span className="eyebrow">{lang === "es" ? "Mi enfoque" : "My approach"}</span>
        <p className="manifesto-quote">
          {lang === "es" ?
          <>Una terapia que <em>acompaña</em> y brinda herramientas para el cambio.</> :
          <>Therapy that <em>walks with you</em> and offers tools for change.</>}
        </p>
        <span className="manifesto-attr">Lic. Guillermina Gómez · MP 47.834</span>
      </div>
    </section>);
}

/* ============== Media strip (apariciones) ============== */
function MediaStrip({ t, lang }) {
  const [video, setVideo] = useState(null);
  const items = t.media.items;
  const loop = [...items, ...items];

  useEffect(() => {
    if (!video) return;
    const onKey = (e) => {if (e.key === "Escape") setVideo(null);};
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {document.removeEventListener("keydown", onKey);document.body.style.overflow = "";};
  }, [video]);

  return (
    <section className="mstrip" id="medios">
      <div className="wrap mstrip-head">
        <div>
          <h2>{t.media.title}</h2>
        </div>
        <p className="lead">{t.media.sub}</p>
      </div>

      <div className="mstrip-rail">
        <div className="mstrip-track">
          {loop.map((v, i) =>
          <button key={i} className={`mcard ${v.pending ? "mcard-pending" : ""}`} onClick={() => v.pending ? null : setVideo(v)} aria-label={v.title}>
              <div className="mcard-thumb">
                {v.pending ?
                <span className="mcard-soon">{lang === "es" ? "Próximamente" : "Coming soon"}</span> :
                <>
                  <video className="mcard-vid" src={v.src + "#t=0.5"} preload="metadata" muted playsInline></video>
                  <span className="mcard-shade"></span>
                  <span className="mcard-play">{Icon.play(16)}</span>
                </>
                }
                <span className="mcard-kind">{v.kind}</span>
                {v.duration && <span className="mcard-dur">{v.duration}</span>}
              </div>
              <div className="mcard-meta">
                <span className="mcard-src">{v.source}</span>
                <span className="mcard-title">{v.title}</span>
                {v.city && <span className="mcard-city">{v.city}</span>}
              </div>
            </button>
          )}
        </div>
      </div>

      {video &&
      <div className="vfs-overlay" onClick={() => setVideo(null)}>
          <button className="vfs-back" onClick={() => setVideo(null)}>{Icon.chev("left")} {lang === "es" ? "Volver a la web" : "Back to site"}</button>
          <div className="vfs-inner" onClick={(e) => e.stopPropagation()}>
            <div className="vfs-video">
              <button className="vfs-close" onClick={() => setVideo(null)} aria-label={lang === "es" ? "Cerrar" : "Close"}>{Icon.close(20)}</button>
              <video className="vfs-player" src={video.src} controls autoPlay playsInline></video>
            </div>
            <div className="vfs-info">
              <span className="vfs-src">{video.source}{video.city ? " · " + video.city : ""}</span>
              <h3>{video.title}</h3>
            </div>
          </div>
        </div>
      }
    </section>);
}

/* ============== Process (compact, horizontal) ============== */
function Process({ t }) {
  const [active, setActive] = useState(0);
  const n = t.process.steps.length;

  useEffect(() => {
    const id = setInterval(() => setActive((a) => (a + 1) % n), 2400);
    return () => clearInterval(id);
  }, [n]);

  return (
    <section id="proceso" className="proceso">
      <div className="wrap">
        <div className="proceso-grid">
          <div className="proceso-head">
            <h2>{t.process.title}</h2>
          </div>
          <div className="proceso-steps">
            {t.process.steps.map((s, i) =>
            <div key={i} className={`pstep${i === active ? " active" : ""}${i < active ? " done" : ""}`}>
                <span className="pstep-fill"></span>
                <span className="pstep-n">{s.n}</span>
                <div className="pstep-body">
                  <h3>{s.t}</h3>
                  <p>{s.d}</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);
}

/* ============== FAQ + Agenda (combined) ============== */
function FaqBook({ t, lang, cur, setCur }) {
  const [openIdx, setOpenIdx] = useState(0);
  const waMsg = lang === "es" ?
  "Hola Guillermina, me gustaría agendar mi primera cita." :
  "Hi Guillermina, I'd like to book my first session.";
  const waHref = `https://wa.me/${LINKS.whatsapp}?text=${encodeURIComponent(waMsg)}`;
  const mailHref = `mailto:${LINKS.email}?subject=${encodeURIComponent(lang === "es" ? "Consulta — primera cita" : "Inquiry — first session")}`;

  return (
    <section className="fb" id="contacto">
      <div className="wrap fb-grid">
        {/* FAQ side */}
        <div className="fb-faq" id="faq">
          <h2>{t.faq.title}</h2>
          <div className="faq-list">
            {t.faq.items.map((q, i) =>
            <div key={i} className={`faq-item ${openIdx === i ? "open" : ""}`}>
                <button className="faq-q" onClick={() => setOpenIdx(openIdx === i ? -1 : i)}>
                  <span>{q.q}</span>
                  <span className="faq-toggle">{Icon.plus()}</span>
                </button>
                <div className="faq-a">
                  <p>{q.a}</p>
                  {q.type === "pricing" &&
                <div className="faq-pricing">
                      <CurrencyToggle t={t} cur={cur} setCur={setCur} />
                      <div className="fp-table">
                        {(cur === "ars" && q.pricing.firstArs ? q.pricing.firstArs : q.pricing.first).map((p, k) =>
                    <div key={k} className="fp-row fp-first">
                            <span>{p.label}</span><span className="fp-val">{p.ars != null ? formatArs(p.ars) : formatPrice(p.usd, cur)}</span>
                          </div>
                    )}
                        {(cur === "ars" && q.pricing.packsArs ? q.pricing.packsArs : q.pricing.packs).map((p, k) =>
                    <div key={k} className="fp-row">
                            <span>{p.label}</span><span className="fp-val">{p.ars != null ? formatArs(p.ars) : formatPrice(p.usd, cur)}</span>
                          </div>
                    )}
                      </div>
                      <span className="fp-note">{t.services.fxNote}</span>
                    </div>
                }
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Agenda side */}
        <div className="fb-book">
          <h2>{t.contact.title}</h2>
          <p className="lead fb-sub">{t.contact.sub}</p>

          <a className="cc cc-primary" href={waHref} target="_blank" rel="noopener noreferrer">
            <div className="cc-icon cc-icon-wa">{Icon.wa(26)}</div>
            <div className="cc-body">
              <span className="cc-lbl">{lang === "es" ? "Más rápido" : "Fastest"}</span>
              <h3>{lang === "es" ? "Escribime por WhatsApp" : "Message me on WhatsApp"}</h3>
              <span className="cc-mono">{t.contact.side.phone}</span>
            </div>
            <span className="cc-arr">{Icon.arrow("")}</span>
          </a>

          <a className="cc" href={mailHref}>
            <div className="cc-icon">{Icon.mail(22)}</div>
            <div className="cc-body">
              <span className="cc-lbl">Email</span>
              <h3>{lang === "es" ? "Escribime un mail" : "Send me an email"}</h3>
              <span className="cc-mono">{LINKS.email}</span>
            </div>
            <span className="cc-arr">{Icon.arrow("")}</span>
          </a>

          <div className="fb-meta">
            <div><span className="cm-lbl">{lang === "es" ? "Horarios" : "Hours"}</span><span className="cm-val">{t.contact.side.hours}</span></div>
            <div><span className="cm-lbl">{lang === "es" ? "Husos" : "Zones"}</span><span className="cm-val">{t.contact.side.zones}</span></div>
            <div><span className="cm-lbl">{lang === "es" ? "Idiomas" : "Languages"}</span><span className="cm-val">{lang === "es" ? "Español" : "Spanish"}</span></div>
            <div><span className="cm-lbl">{lang === "es" ? "Modalidad" : "Format"}</span><span className="cm-val">100% online</span></div>
          </div>
        </div>
      </div>
    </section>);
}

Object.assign(window, { Hero, Services, Manifesto, MediaStrip, Process, FaqBook });