﻿/* =========================================================
   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="Cinco razones honestas">
      <div className="container" style={{ padding: "0px 80px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">Por qué Innovaria</span>
          <h2>Cinco razones para confiarnos tu <span className="hl">venta</span></h2>
          <p>Compromisos firmados que te protegen. Sin tácticas de presión y sin promesas vacías.</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>No cobramos doble</h3>
              <p>El precio anunciado es el precio final. Al comprador no se le añade comisión: lo que ve es lo que paga.</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>Exclusiva compartida MLS</h3>
              <p>Una sola exclusiva, tu casa en toda la red MLS y un único interlocutor para ti.</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} /> Razón estrella · IA</span>
              <div className="diff-center--ia__icon"><Icon name="cpu" size={26} /></div>
              <h3>IA aplicada a vender tu casa</h3>
              <p>Pioneros en aplicar inteligencia artificial al proceso de venta. La IA no sustituye al agente: lo hace más efectivo.</p>
            </div>
            <div className="diff-center--ia__robot">
              <img src="assets/robot-ia.png" alt="Robot IA de Innovaria" 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>Servicios por contrato</h3>
              <p>Todo lo que prometemos va por escrito. Si no cumplimos, la exclusiva no te obliga a ti.</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>Marketing de verdad</h3>
              <p>18 años de experiencia en marketing aplicados a vender: producción, contenido y campañas medibles.</p>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Sec 5: Zonas (tiles con banda navy) ---------- */
const ZONES = [
{ slug: "playa-del-cura", name: "Playa del Cura", count: "12 Propiedades", img: "assets/zone-playa-cura.jpg",
  desc: "Una de las zonas más demandadas de Torrevieja por su cercanía al mar, paseo marítimo, servicios y alta demanda de compradores durante todo el año." },
{ slug: "punta-prima", name: "Punta Prima", count: "8 Propiedades", img: "assets/zone-punta-prima.jpg",
  desc: "Urbanizaciones modernas junto al mar y alta demanda exterior." },
{ slug: "playa-de-la-mata", name: "Playa de la Mata", count: "9 Propiedades", img: "assets/zone-playa-mata.jpg",
  desc: "Playa natural, tranquilidad y compradores internacionales." },
{ slug: "torrevieja-centro", name: "Torrevieja Centro", count: "15 Propiedades", img: "assets/zone-torrevieja-centro.jpeg",
  desc: "Comercios, servicios y alta demanda durante todo el año." },
{ slug: "los-balcones", name: "Los Balcones", count: "6 Propiedades", img: "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=900&q=80",
  desc: "Urbanización residencial con lago natural, parque botánico y excelentes conexiones. Ideal para familias." },
{ slug: "los-frutales", name: "Los Frutales", count: "4 Propiedades", img: "https://images.unsplash.com/photo-1582719508461-905c673771fd?auto=format&fit=crop&w=900&q=80",
  desc: "Zona tranquila al norte de la ciudad con chalets independientes y precios competitivos." }];


function Zones() {
  const [active, setActive] = useState(0);
  return (
    <section className="section section--cream section--w1400" id="zonas" aria-label="Zonas destacadas">
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">Zonas destacadas</span>
          <h2 style={{ color: "rgb(20, 28, 20)" }}>Explora <span className="hl">Torrevieja</span></h2>
          <p>Trabajamos donde vivimos. Cuatro zonas, una sola ciudad y un equipo que la conoce calle a calle.</p>
        </div>

        <div className="zones-strip" role="tablist">
          {ZONES.map((z, i) =>
          <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" /> {z.count}
                </span>
                <h3 className="zones-strip__name">{z.name}</h3>
                <p className="zones-strip__desc">{z.desc}</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="CEO Isaac Ruiz">
      <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="Isaac Ruiz, CEO de Innovaria, con una casa en miniatura" />

            <div className="ceo__badge ceo__badge--happy">
              <img src="assets/badge-ua.jpg" alt="Titulado por la Universidad de Alicante" style={{ width: "185px" }} />
            </div>
            <div className="ceo__badge ceo__badge--safe">
              <img src="assets/badge-apial.png" alt="APIAL" style={{ marginLeft: "20px" }} />
              <img src="assets/badge-raicv.png" alt="RAICV 2926" style={{ marginTop: "150px", marginLeft: "10px", width: "110px" }} />
            </div>
            <div className="ceo__badge ceo__badge--google">
              <img src="assets/badge-crs.png" alt="Certified Residential Specialist (CRS)" style={{ padding: "1px", height: "103px", width: "93px" }} />
            </div>
          </div>

          <div className="ceo__content">
            <span className="eyebrow"><span style={{ color: "" }}>Quién está detrás</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)"
            }}>Isaac Ruiz. 18 años de <span className="hl" style={{ color: "rgb(8, 56, 26)" }}>marketing</span> aplicados a vender.</h2>
            <p className="pq-founder__quote">
              "Llevo 18 años en marketing y 7 en el sector inmobiliario. Innovaria nace de ver cómo se podía hacer mucho mejor. Estrategia, datos y trato cercano. Sin atajos."
            </p>
            <div className="pq-founder__author">
              <strong style={{ color: "rgb(20, 28, 20)" }}>Isaac Ruiz</strong>
              <span>CEO · Fundador de Innovaria</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>
                Titulado por la Universidad de Alicante
              </div>
              <div className="ceo__credential" style={{ color: "rgb(20, 28, 20)" }}>
                <span className="ceo__credential-icon"><Icon name="award" size={14} /></span>
                Formación CRS (Certified Residential Specialist)
              </div>
              <div className="ceo__credential" style={{ color: "rgb(20, 28, 20)" }}>
                <span className="ceo__credential-icon"><Icon name="badge-check" size={14} /></span>
                Colegiado APIAL · RAICV 2926
              </div>
            </div>

            <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 24 }}>
              <Button variant="primary" iconRight="arrow-right" as="a" href="#valoracion">
                ¿Hablamos?
              </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)}` : ""}`;
  return (
    <article className="prop-card">
      <a className="prop-card__media" href={href} aria-label={`Ver ${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} /> {p.tag}</span> :
          p.tag === "Destacado" ?
          <span className="tag tag--green">{p.tag}</span> :
          <span className="tag tag--navy" style={{ backgroundColor: "rgb(42, 158, 71)" }}>{p.tag}</span>
          }
          <span className="tag">En venta</span>
        </div>
        <button
          className="prop-card__fav"
          aria-label="Guardar"
          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} /> {p.beds} hab</span>
          <span className="prop-card__spec"><Icon name="bath" size={14} /> {p.baths} baños</span>
          <span className="prop-card__spec"><Icon name="ruler" size={14} /> {p.area} m²</span>
        </div>
        <div className="prop-card__foot">
          <div className="prop-card__price">{p.price}</div>
          <a className="prop-card__cta" href={href} aria-label={`Ver detalle de ${p.title}`}>
            <Icon name="arrow-up-right" size={16} />
          </a>
        </div>
      </div>
    </article>);

}

/* ---------- Sec 7: Viviendas destacadas ---------- */
const FEATURED = [
{ title: "Villa con vistas al mar en Cabo Roig", 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 },
{ title: "Bungalow reformado a 200 m de la playa", 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 },
{ title: "Ático con terraza panorámica en Torrevieja", location: "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 },
{ title: "Chalet de obra nueva en Punta Prima", 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 },
{ title: "Piso reformado en Playa del Cura", 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 },
{ title: "Villa familiar con piscina privada", 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 }];


function DiscoverSpecial() {
  const VISIBLE = 3;
  const N = FEATURED.length;
  // Cards + VISIBLE clones at the end for seamless loop
  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);
  }, []);

  // Seamless wraparound: when we pass N, snap silently to 0
  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="Viviendas destacadas">
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">Viviendas destacadas</span>
          <h2>Descubre algo <span className="hl">especial</span></h2>
          <p>Selección de la semana. Cada anuncio pasa por nuestro proceso de imagen, copy multilingüe y campañas optimizadas con IA.</p>
        </div>

        <div className="listings-carousel">
          <button className="listings-arrow listings-arrow--left" onClick={prev} aria-label="Anterior">
            <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="Siguiente">
            <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 TABS = ["Todas", "Villas", "Apartamentos", "Áticos", "Bungalows", "Adosados"];

const LISTINGS = [
{ ref: "INV-2001", title: "Villa moderna en Los Balcones", 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", title: "Apartamento luminoso en Punta Prima", 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", title: "Adosado con jardín en Villamartín", 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", title: "Chalet con piscina en Playa Flamenca", 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", title: "Ático con vistas al mar en La Zenia", 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", title: "Bungalow planta baja en Torrevieja", location: "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 }];


function LatestListings() {
  const [tab, setTab] = useState(TABS[0]);
  return (
    <section className="section section--cream section--w1400" id="comprar" aria-label="Propiedades">
      <div className="container" style={{ padding: "0px" }}>
        <div className="section-head">
          <span className="eyebrow eyebrow--center">Cartera actual</span>
          <h2 style={{ color: "rgb(20, 28, 20)" }}>Descubre nuestras últimas <span className="hl">viviendas</span></h2>
          <p>Cartera viva en Torrevieja y Orihuela Costa. Filtra por tipo y encuentra lo que buscas.</p>
        </div>

        <div style={{ display: "flex", justifyContent: "center" }}>
          <div className="tabs" role="tablist">
            {TABS.map((t) =>
            <button
              key={t}
              role="tab"
              aria-selected={tab === t}
              className={"tabs__tab" + (tab === t ? " is-active" : "")}
              onClick={() => setTab(t)}>
              
                {t}
              </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="#">
            Ver más propiedades
          </Button>
        </div>
      </div>
    </section>);

}

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