/* =========================================================
   Secciones mid (rev. usuario):
   - Sec 4: Cinco razones honestas (IA en el centro)
   - Sec 5: Zonas
   - Sec 6: CEO Isaac Ruiz (con foto y badges)
   - Sec 7: Viviendas destacadas
   - Sec 8: Propiedades (tabs + grid)
   ========================================================= */

/* ---------- Sec 4: 5 razones honestas — IA en el centro ---------- */
function Differentiators() {
  return (
    <section className="section section--gap60-top" aria-label={t("home.differentiators.aria")}>
      <div className="container" style={{ padding: "0px 80px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">{t("home.differentiators.eyebrow")}</span>
          <h2 dangerouslySetInnerHTML={{ __html: t("home.differentiators.h2_html") }} />
          <p>{t("home.differentiators.intro")}</p>
        </div>

        <div className="diff-layout">
          <div className="diff-col">
            <div className="diff-card">
              <span className="diff-card__num">01</span>
              <div className="diff-card__icon"><Icon name="tag" size={22} /></div>
              <h3>{t("home.differentiators.card1_title")}</h3>
              <p>{t("home.differentiators.card1_desc")}</p>
            </div>
            <div className="diff-card">
              <span className="diff-card__num">02</span>
              <div className="diff-card__icon"><Icon name="network" size={22} /></div>
              <h3>{t("home.differentiators.card2_title")}</h3>
              <p>{t("home.differentiators.card2_desc")}</p>
            </div>
          </div>

          {/* Centro: tarjeta IA (razón estrella) */}
          <a className="diff-center--ia diff-center--ia--link" id="ia" href="ia-aplicada.html">
            <div>
              <span className="badge-ai"><Icon name="sparkles" size={11} /> {t("home.differentiators.ia_badge")}</span>
              <div className="diff-center--ia__icon"><Icon name="cpu" size={26} /></div>
              <h3>{t("home.differentiators.ia_title")}</h3>
              <p>{t("home.differentiators.ia_desc")}</p>
            </div>
            <div className="diff-center--ia__robot">
              <img src="/assets/robot-ia.png" alt={t("home.differentiators.ia_robot_alt")} style={{ width: "329px" }} />
            </div>
          </a>

          <div className="diff-col">
            <div className="diff-card">
              <span className="diff-card__num">03</span>
              <div className="diff-card__icon"><Icon name="file-signature" size={22} /></div>
              <h3>{t("home.differentiators.card3_title")}</h3>
              <p>{t("home.differentiators.card3_desc")}</p>
            </div>
            <div className="diff-card">
              <span className="diff-card__num">04</span>
              <div className="diff-card__icon"><Icon name="megaphone" size={22} /></div>
              <h3>{t("home.differentiators.card4_title")}</h3>
              <p>{t("home.differentiators.card4_desc")}</p>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Sec 5: Zonas (tiles con banda navy) ---------- */
const ZONES = [
{ slug: "playa-del-cura", name: "Playa del Cura", n: 12, img: "/assets/zone-playa-cura.jpg" },
{ slug: "punta-prima", name: "Punta Prima", n: 8, img: "/assets/zone-punta-prima.jpg" },
{ slug: "playa-de-la-mata", name: "Playa de la Mata", n: 9, img: "/assets/zone-playa-mata.jpg" },
{ slug: "torrevieja-centro", name: "Torrevieja Centro", n: 15, img: "/assets/zone-torrevieja-centro.jpeg" },
{ slug: "los-balcones", name: "Los Balcones", n: 6, img: "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=900&q=80" },
{ slug: "los-frutales", name: "Los Frutales", n: 4, img: "https://images.unsplash.com/photo-1582719508461-905c673771fd?auto=format&fit=crop&w=900&q=80" }];


function Zones() {
  const [active, setActive] = useState(0);
  return (
    <section className="section section--cream section--w1400" id="zonas" aria-label={t("home.zones.aria")}>
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">{t("home.zones.eyebrow")}</span>
          <h2 style={{ color: "rgb(20, 28, 20)" }} dangerouslySetInnerHTML={{ __html: t("home.zones.h2_html") }} />
          <p>{t("home.zones.intro")}</p>
        </div>

        <div className="zones-strip" role="tablist">
          {ZONES.map((z, i) => {
            const descKey = "home.zones.desc_" + z.slug.replace(/-/g, "_");
            const countKey = z.n === 1 ? "home.zones.count_one" : "home.zones.count_other";
            return (
              <a
                key={z.name}
                className={"zones-strip__item" + (active === i ? " is-active" : "")}
                href={`zona.html?zona=${z.slug}`}
                role="tab"
                aria-selected={active === i}
                onMouseEnter={() => setActive(i)}
                onFocus={() => setActive(i)}
                style={{ backgroundImage: `url(${z.img})` }}>

                <span className="zones-strip__veil" aria-hidden="true" />
                <span className="zones-strip__corner" aria-hidden="true">
                  <Icon name="arrow-up-right" size={16} />
                </span>
                <div className="zones-strip__body">
                  <span className="zones-strip__count">
                    <span className="zones-strip__count-mark" /> {t(countKey, { n: z.n })}
                  </span>
                  <h3 className="zones-strip__name">{z.name}</h3>
                  <p className="zones-strip__desc">{t(descKey)}</p>
                </div>
                <h3 className="zones-strip__name-vertical" aria-hidden="true">{z.name}</h3>
              </a>);
          })}
        </div>
      </div>
    </section>);

}

/* ---------- Sec 6: CEO Isaac Ruiz ---------- */
function CEOSection() {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el || visible) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setVisible(true);
          obs.disconnect();
        }
      });
    }, { threshold: 0.2 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [visible]);
  return (
    <section ref={ref} className={"section section--no-pad ceo-anim" + (visible ? " is-in" : "")} id="nosotros" aria-label={t("home.ceo.aria")}>
      <div className="container">
        <div className="ceo" style={{ margin: "0px 120px 90px" }}>
          <div className="ceo__media">
            <span className="ceo__bgcircle" aria-hidden="true" />
            <span className="ceo__bgring" aria-hidden="true" />
            <img className="ceo__photo" src="/assets/ceo-isaac.webp" alt={t("home.ceo.photo_alt")} />

            <div className="ceo__badge ceo__badge--happy">
              <img src="/assets/badge-ua.jpg" alt={t("home.ceo.badge_ua_alt")} style={{ width: "185px" }} />
            </div>
            <div className="ceo__badge ceo__badge--safe">
              <img src="/assets/badge-apial.png" alt={t("home.ceo.badge_apial_alt")} style={{ marginLeft: "20px" }} />
              <img src="/assets/badge-raicv.png" alt={t("home.ceo.badge_raicv_alt")} style={{ marginTop: "150px", marginLeft: "10px", width: "110px" }} />
            </div>
            <div className="ceo__badge ceo__badge--google">
              <img src="/assets/badge-crs.png" alt={t("home.ceo.badge_crs_alt")} style={{ padding: "1px", height: "103px", width: "93px" }} />
            </div>
          </div>

          <div className="ceo__content">
            <span className="eyebrow"><span style={{ color: "" }}>{t("home.ceo.eyebrow")}</span></span>
            <h2 style={{
              fontFamily: "var(--font-display)",
              fontWeight: 800,
              fontSize: "clamp(28px, 2.4vw + 0.5rem, 42px)",
              lineHeight: 1.1,
              letterSpacing: "-0.025em",

              margin: "14px 0 24px", color: "rgb(20, 28, 20)"
            }} dangerouslySetInnerHTML={{ __html: t("home.ceo.h2_html") }} />
            <p className="pq-founder__quote">
              {t("home.ceo.quote")}
            </p>
            <div className="pq-founder__author">
              <strong style={{ color: "rgb(20, 28, 20)" }}>Isaac Ruiz</strong>
              <span>{t("home.ceo.author_role")}</span>
            </div>

            <div className="ceo__credentials">
              <div className="ceo__credential" style={{ color: "rgb(20, 28, 20)" }}>
                <span className="ceo__credential-icon"><Icon name="graduation-cap" size={14} /></span>
                {t("home.ceo.cred_ua")}
              </div>
              <div className="ceo__credential" style={{ color: "rgb(20, 28, 20)" }}>
                <span className="ceo__credential-icon"><Icon name="award" size={14} /></span>
                {t("home.ceo.cred_crs")}
              </div>
              <div className="ceo__credential" style={{ color: "rgb(20, 28, 20)" }}>
                <span className="ceo__credential-icon"><Icon name="badge-check" size={14} /></span>
                {t("home.ceo.cred_apial")}
              </div>
            </div>

            <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 24 }}>
              <Button variant="primary" iconRight="arrow-right" as="a" href="#valoracion">
                {t("home.ceo.cta_talk")}
              </Button>
              <Button variant="ghost" icon="phone" as="a" href="tel:+34604494089">
                604 49 40 89
              </Button>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Property card ---------- */
function PropCard({ p }) {
  const href = `vivienda.html${p.ref ? `?ref=${encodeURIComponent(p.ref)}` : ""}`;
  const tagKey =
    p.tag === "IA optimizado" ? "home.propCard.tag_ai" :
    p.tag === "Destacado" ? "home.propCard.tag_featured" :
    p.tag === "Nuevo" ? "home.propCard.tag_new" :
    null;
  const tagText = tagKey ? t(tagKey) : p.tag;
  return (
    <article className="prop-card">
      <a className="prop-card__media" href={href} aria-label={t("common.card.view_label", { title: p.title })}>
        <img src={p.img} alt={p.title} />
        <div className="prop-card__tags">
          {p.tag === "IA optimizado" ?
          <span className="tag tag--ai"><Icon name="sparkles" size={11} /> {tagText}</span> :
          p.tag === "Destacado" ?
          <span className="tag tag--green">{tagText}</span> :
          <span className="tag tag--navy" style={{ backgroundColor: "rgb(42, 158, 71)" }}>{tagText}</span>
          }
          <span className="tag">{t("home.propCard.tag_sale")}</span>
        </div>
        <button
          className="prop-card__fav"
          aria-label={t("home.propCard.aria_save")}
          onClick={(e) => {e.preventDefault();e.stopPropagation();}}>
          <Icon name="heart" size={16} />
        </button>
      </a>
      <div className="prop-card__body">
        <a className="prop-card__title-link" href={href}>
          <h3 className="prop-card__title">{p.title}</h3>
        </a>
        <div className="prop-card__location"><Icon name="map-pin" size={14} /> {p.location}</div>
        <div className="prop-card__specs">
          <span className="prop-card__spec"><Icon name="bed" size={14} /> {t("home.propCard.spec_beds", { n: p.beds })}</span>
          <span className="prop-card__spec"><Icon name="bath" size={14} /> {t(p.baths === 1 ? "home.propCard.spec_baths_one" : "home.propCard.spec_baths_other", { n: p.baths })}</span>
          <span className="prop-card__spec"><Icon name="ruler" size={14} /> {t("home.propCard.spec_area", { n: p.area })}</span>
        </div>
        <div className="prop-card__foot">
          <div className="prop-card__price">{p.price}</div>
          <a className="prop-card__cta" href={href} aria-label={t("common.card.view_detail", { title: p.title })}>
            <Icon name="arrow-up-right" size={16} />
          </a>
        </div>
      </div>
    </article>);

}

/* ---------- Sec 7: Viviendas destacadas ---------- */
const FEATURED = [
{ titleKey: "home.properties.f1_title", location: "Cabo Roig, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1613490493576-7fde63acd811?auto=format&fit=crop&w=900&q=80",
  tag: "Destacado", price: "895.000 €", beds: 4, baths: 3, area: 280 },
{ titleKey: "home.properties.f2_title", location: "La Zenia, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?auto=format&fit=crop&w=900&q=80",
  tag: "Nuevo", price: "265.000 €", beds: 3, baths: 2, area: 95 },
{ titleKey: "home.properties.f3_title", locationKey: "home.properties.loc_torrevieja_centro",
  img: "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=900&q=80",
  tag: "IA optimizado", price: "320.000 €", beds: 2, baths: 2, area: 110 },
{ titleKey: "home.properties.f4_title", location: "Punta Prima, Torrevieja",
  img: "https://images.unsplash.com/photo-1564013799919-ab600027ffc6?auto=format&fit=crop&w=900&q=80",
  tag: "Destacado", price: "650.000 €", beds: 4, baths: 3, area: 210 },
{ titleKey: "home.properties.f5_title", location: "Playa del Cura, Torrevieja",
  img: "https://images.unsplash.com/photo-1493809842364-78817add7ffb?auto=format&fit=crop&w=900&q=80",
  tag: "Nuevo", price: "215.000 €", beds: 2, baths: 1, area: 82 },
{ titleKey: "home.properties.f6_title", location: "Playa de la Mata, Torrevieja",
  img: "https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=900&q=80",
  tag: "IA optimizado", price: "535.000 €", beds: 5, baths: 3, area: 245 }].map((p) => ({
    ...p,
    title: t(p.titleKey),
    location: p.locationKey ? t(p.locationKey) : p.location
  }));


function DiscoverSpecial() {
  const VISIBLE = 3;
  const N = FEATURED.length;
  const items = [...FEATURED, ...FEATURED.slice(0, VISIBLE)];

  const [start, setStart] = useState(0);
  const [withTransition, setWithTransition] = useState(true);
  const viewportRef = useRef(null);
  const [cardW, setCardW] = useState(0);
  const gap = 28;

  useEffect(() => {
    const update = () => {
      if (!viewportRef.current) return;
      const w = viewportRef.current.offsetWidth;
      const perView =
      window.innerWidth >= 1100 ? VISIBLE :
      window.innerWidth >= 700 ? 2 : 1;
      setCardW((w - gap * (perView - 1)) / perView);
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);

  useEffect(() => {
    if (start === N) {
      const t = setTimeout(() => {
        setWithTransition(false);
        setStart(0);
      }, 500);
      return () => clearTimeout(t);
    }
    if (!withTransition) {
      const t = setTimeout(() => setWithTransition(true), 50);
      return () => clearTimeout(t);
    }
  }, [start, withTransition]);

  const next = () => {
    if (!withTransition) return;
    setStart((s) => Math.min(s + 1, N));
  };
  const prev = () => {
    if (!withTransition) return;
    if (start === 0) {
      setWithTransition(false);
      setStart(N);
      setTimeout(() => {
        setWithTransition(true);
        setStart(N - 1);
      }, 60);
    } else {
      setStart((s) => s - 1);
    }
  };

  const trackOffset = -start * (cardW + gap);
  const activeDot = start % N;

  return (
    <section className="section section--w1400" aria-label={t("home.discoverSpecial.aria")}>
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">{t("home.discoverSpecial.eyebrow")}</span>
          <h2 dangerouslySetInnerHTML={{ __html: t("home.discoverSpecial.h2_html") }} />
          <p>{t("home.discoverSpecial.intro")}</p>
        </div>

        <div className="listings-carousel">
          <button className="listings-arrow listings-arrow--left" onClick={prev} aria-label={t("common.action.prev")}>
            <Icon name="arrow-left" size={18} />
          </button>

          <div className="listings-viewport" ref={viewportRef}>
            <div
              className="listings-track"
              style={{
                transform: `translateX(${trackOffset}px)`,
                transition: withTransition ? "transform 480ms cubic-bezier(0.16, 1, 0.3, 1)" : "none"
              }}>

              {items.map((p, i) =>
              <div key={i} className="listings-slide" style={{ width: cardW > 0 ? cardW + "px" : "100%" }}>
                  <PropCard p={p} />
                </div>
              )}
            </div>
          </div>

          <button className="listings-arrow listings-arrow--right" onClick={next} aria-label={t("common.action.next")}>
            <Icon name="arrow-right" size={18} />
          </button>
        </div>

        <div className="carousel__dots">
          {FEATURED.map((_, i) =>
          <span key={i} className={"carousel__dot" + (i === activeDot ? " is-active" : "")} />
          )}
        </div>
      </div>
    </section>);

}

/* ---------- Sec 8: Propiedades (tabs + grid) ---------- */
const TAB_KEYS = [
  { key: "all", i18n: "home.latestListings.tab_all" },
  { key: "villas", i18n: "home.latestListings.tab_villas" },
  { key: "apartments", i18n: "home.latestListings.tab_apartments" },
  { key: "penthouses", i18n: "home.latestListings.tab_penthouses" },
  { key: "bungalows", i18n: "home.latestListings.tab_bungalows" },
  { key: "townhouses", i18n: "home.latestListings.tab_townhouses" }
];

const LISTINGS = [
{ ref: "INV-2001", titleKey: "home.properties.l1_title", location: "Los Balcones, Torrevieja",
  img: "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=900&q=80",
  tag: "Destacado", price: "560.000 €", beds: 4, baths: 3, area: 220 },
{ ref: "INV-2002", titleKey: "home.properties.l2_title", location: "Punta Prima, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1502672023488-70e25813eb80?auto=format&fit=crop&w=900&q=80",
  tag: "Nuevo", price: "189.000 €", beds: 2, baths: 1, area: 78 },
{ ref: "INV-2003", titleKey: "home.properties.l3_title", location: "Villamartín, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1568605114967-8130f3a36994?auto=format&fit=crop&w=900&q=80",
  tag: "IA optimizado", price: "298.000 €", beds: 3, baths: 2, area: 130 },
{ ref: "INV-2004", titleKey: "home.properties.l4_title", location: "Playa Flamenca, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1600585154526-990dced4db0d?auto=format&fit=crop&w=900&q=80",
  tag: "Destacado", price: "725.000 €", beds: 5, baths: 4, area: 310 },
{ ref: "INV-2005", titleKey: "home.properties.l5_title", location: "La Zenia, Orihuela Costa",
  img: "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=900&q=80",
  tag: "Nuevo", price: "395.000 €", beds: 3, baths: 2, area: 125 },
{ ref: "INV-2006", titleKey: "home.properties.l6_title", locationKey: "home.properties.loc_torrevieja",
  img: "https://images.unsplash.com/photo-1600585154363-67eb9e2e2099?auto=format&fit=crop&w=900&q=80",
  tag: "IA optimizado", price: "165.000 €", beds: 2, baths: 1, area: 70 }].map((p) => ({
    ...p,
    title: t(p.titleKey),
    location: p.locationKey ? t(p.locationKey) : p.location
  }));


function LatestListings() {
  const [tab, setTab] = useState(TAB_KEYS[0].key);
  return (
    <section className="section section--cream section--w1400" id="comprar" aria-label={t("home.latestListings.aria")}>
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">{t("home.latestListings.eyebrow")}</span>
          <h2 style={{ color: "rgb(20, 28, 20)" }} dangerouslySetInnerHTML={{ __html: t("home.latestListings.h2_html") }} />
          <p>{t("home.latestListings.intro")}</p>
        </div>

        <div style={{ display: "flex", justifyContent: "center" }}>
          <div className="tabs" role="tablist">
            {TAB_KEYS.map((tk) =>
            <button
              key={tk.key}
              role="tab"
              aria-selected={tab === tk.key}
              className={"tabs__tab" + (tab === tk.key ? " is-active" : "")}
              onClick={() => setTab(tk.key)}>

                {t(tk.i18n)}
              </button>
            )}
          </div>
        </div>

        <div className="listings">
          {LISTINGS.map((p, i) => <PropCard key={i} p={p} />)}
        </div>

        <div className="center-cta">
          <Button variant="primary" iconRight="arrow-right" as="a" href="#">
            {t("home.latestListings.cta_more")}
          </Button>
        </div>
      </div>
    </section>);

}

Object.assign(window, { Differentiators, Zones, CEOSection, DiscoverSpecial, LatestListings, PropCard });
