const { PropertyCard, Button, IconButton, Card, Icon, Input, Dialog, Badge } = window.MiradorDesignSystem_4bae5c;

/* ── BACKEND CONTRACT ──────────────────────────────────────────────
   Search → the /compra filter page, same query keys the old site uses.
   Properties → Notion "Propiedades CasaMia" (Estado = publicado).
   Set rest.properties to the worker/endpoint that returns that database as
   JSON and the grid switches from the bundled snapshot to live data. */
const FILEMODE = /\.html$/i.test(location.pathname);
const route = (n) => FILEMODE ? n + '.html' : (n === 'index' ? '/' : '/' + n);

const BACKEND = {
  site: 'https://casamia.ec',
  searchPath: '/compra/',
  searchParams: { location: 'q', type: 'tipo', min: 'pmin', max: 'pmax' },
  rest: { properties: '', posts: '/wp-json/wp/v2/posts?per_page=4&_embed' },
  whatsapp: '593988957054',
  links: {
    compra: route('propiedades'), publicar: route('publicar'),
    creditos: 'https://casamia.ec/creditos-hipotecarios-ecuador/', contacto: route('contacto'),
    novedades: 'https://casamia.ec/novedades-inmobiliarias-quito/',
    facebook: 'https://web.facebook.com/casamia.ec.quito/', instagram: 'https://www.instagram.com/casamia.ecuador/',
    tiktok: 'https://www.tiktok.com/@casamia.ecuador', agencia: 'https://agavemkt.com'
  }
};
const WA = (t) => `https://wa.me/${BACKEND.whatsapp}?text=${encodeURIComponent(t || 'Hola, me gustaría recibir asistencia.')}`;
const TYPES = ['Todos los tipos', 'Casa', 'Departamento', 'Terreno', 'Local comercial', 'Oficina', 'Villa']
  .map(l => ({ value: l === 'Todos los tipos' ? '' : l, label: l }));
const ZONAS = ['Calderón', 'Tumbaco', 'Cumbayá', 'Llano Grande', 'La Ecuatoriana', 'Quito Norte', 'Conocoto', 'Pomasqui', 'Nayón', 'Valle de los Chillos'];
const money = (n) => '$' + Number(n).toLocaleString('es-EC').replace(/,/g, '.');
/* Searches land on the in-project results page, keeping the query keys the old site uses. */
const searchUrl = (o = {}) => {
  const p = BACKEND.searchParams, q = new URLSearchParams();
  if (o.loc) q.set(p.location, o.loc);
  if (o.type) q.set(p.type, o.type);
  if (o.min) q.set(p.min, o.min);
  if (o.max) q.set(p.max, o.max);
  return BACKEND.links.compra + (q.toString() ? '?' + q : '');
};
const go = (url) => window.open(url, '_blank', 'noopener');
const clean = (s = '') => { const d = document.createElement('textarea'); d.innerHTML = s.replace(/<[^>]+>/g, ''); return d.value.replace(/[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}]/gu, '').replace(/\s{2,}/g, ' ').trim(); };

function useRemote(path, map, fallback) {
  const [data, setData] = React.useState(fallback);
  const [live, setLive] = React.useState(false);
  React.useEffect(() => {
    if (!path) return; let alive = true;
    fetch(BACKEND.site + path, { headers: { Accept: 'application/json' } })
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(j => { if (alive && Array.isArray(j) && j.length) { setData(j.map(map)); setLive(true); } })
      .catch(() => {});
    return () => { alive = false; };
  }, [path]);
  return [data, live];
}
const mapPost = (p, i) => ({
  id: String(p.id), url: p.link,
  kicker: (() => { const t = p._embedded?.['wp:term']?.[0]?.[0]?.name; return !t || /uncategorized|sin categor/i.test(t) ? 'Novedades' : t; })(),
  date: new Date(p.date).toLocaleDateString('es-EC', { day: 'numeric', month: 'short', year: 'numeric' }),
  title: clean(p.title?.rendered),
  photoUrl: p._embedded?.['wp:featuredmedia']?.[0]?.source_url || `assets/ph-post-${(i % 3) + 1}.png`
});

/* ── Header: wordmark, plain text nav, publish CTA, account menu ── */
function Header({ onJoin, savedCount }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const user = React.useMemo(() => { try { return JSON.parse(localStorage.getItem('casamia:user') || 'null'); } catch (e) { return null; } }, []);
  const initials = user?.nombre ? user.nombre.split(' ').filter(Boolean).slice(0, 2).map(w => w[0].toUpperCase()).join('') : null;
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const item = (label, onClick, icon) => (
    <button key={label} onClick={() => { setOpen(false); onClick(); }} className="cm-menu-item">
      <Icon name={icon} size={16} />{label}
    </button>
  );
  return (
    <header className="cm-header">
      <div className="cm-header-in">
        <a href={BACKEND.site} className="cm-logo"><img src="assets/logo-casamia-alpha.png" alt="casamia.ec" /></a>
        <nav className="cm-nav">
          <a href={BACKEND.links.compra}><Icon name="house" size={15} />Propiedades</a>
          <a href={BACKEND.links.creditos}><Icon name="calculator" size={15} />Créditos</a>
          <a href={BACKEND.links.novedades}><Icon name="newspaper" size={15} />Novedades</a>
          <a href={BACKEND.links.contacto}><Icon name="message-circle" size={15} />Contacto</a>
        </nav>
        <div className="cm-header-right" ref={ref}>
          <span className="cm-hide-sm"><Button size="sm" variant="outline" onClick={() => go(BACKEND.links.publicar)}>Publica tu propiedad</Button></span>
          <button className="cm-account" aria-label="Menú de cuenta" aria-expanded={open} onClick={() => setOpen(!open)}>
            <Icon name="menu" size={16} />
            <span className="cm-avatar">{initials || <Icon name="user" size={14} />}</span>
          </button>
          {open ? (
            <div className="cm-menu" role="menu">
              {user ? <div className="cm-menu-head">{user.nombre}</div> : null}
              {item(user ? 'Mi cuenta' : 'Iniciar sesión', () => go(BACKEND.links.publicar), 'user')}
              {item('Publica tu propiedad', () => go(BACKEND.links.publicar), 'key-round')}
              {item(savedCount ? `Guardadas (${savedCount})` : 'Guardadas', () => go(BACKEND.links.compra), 'heart')}
              {item('Créditos hipotecarios', () => go(BACKEND.links.creditos), 'calculator')}
              <div className="cm-menu-sep"></div>
              {item('Trabaja con nosotros', onJoin, 'handshake')}
              {item('Contacto', () => go(BACKEND.links.contacto), 'message-circle')}
            </div>) : null}
        </div>
      </div>
    </header>
  );
}

/* ── Functional pill search: same fields and destination as the old page ── */
function SearchPill() {
  const [open, setOpen] = React.useState(null);
  const [loc, setLoc] = React.useState('');
  const [type, setType] = React.useState('');
  const [min, setMin] = React.useState('');
  const [max, setMax] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(null); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  /* While a filter sheet is up, the mobile bottom bar must get out of its way. */
  React.useEffect(() => {
    document.body.classList.toggle('cm-sheet-open', !!open);
    return () => document.body.classList.remove('cm-sheet-open');
  }, [open]);
  const typeLabel = (TYPES.find(t => t.value === type) || TYPES[0]).label;
  const priceLabel = min || max ? [min && 'desde ' + money(min), max && 'hasta ' + money(max)].filter(Boolean).join(' · ') : 'Cualquier precio';
  const seg = (id, label, value, isSet) => (
    <button type="button" onClick={() => setOpen(open === id ? null : id)} className={'cm-seg' + (open === id ? ' is-open' : '')}>
      <span className="cm-seg-label">{label}</span>
      <span className="cm-seg-value" style={{ color: isSet ? 'var(--text-heading)' : 'var(--text-muted)' }}>{value}</span>
    </button>
  );
  const pop = (title, children) => (
    <React.Fragment>
      <div className="cm-pop-scrim" onClick={() => setOpen(null)}></div>
      <div className="cm-pop">
        <div className="cm-pop-head">
          <span>{title}</span>
          <button type="button" aria-label="Cerrar" onClick={() => setOpen(null)}><Icon name="x" size={18} /></button>
        </div>
        {children}
      </div>
    </React.Fragment>
  );
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <form className="cm-search" onSubmit={(e) => { e.preventDefault(); go(searchUrl({ loc: loc.trim(), type, min, max })); }}>
        {seg('loc', 'Ubicación', loc || 'Calderón, Tumbaco, Cumbayá…', !!loc)}
        <span className="cm-seg-div"></span>
        {seg('type', 'Tipo', typeLabel, !!type)}
        <span className="cm-seg-div"></span>
        {seg('price', 'Precio', priceLabel, !!(min || max))}
        <button type="submit" className="cm-search-btn" aria-label="Buscar"><Icon name="search" size={18} />Buscar</button>
      </form>
      {open === 'loc' ? pop('¿Dónde buscas?',
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input autoFocus icon="map-pin" placeholder="Escribe un sector o ciudad" value={loc} onChange={(e) => setLoc(e.target.value)} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {ZONAS.slice(0, 6).map(z => <button key={z} type="button" className={'cm-chip' + (loc === z ? ' is-on' : '')} onClick={() => { setLoc(z); setOpen(null); }}>{z}</button>)}
          </div>
        </div>) : null}
      {open === 'type' ? pop('Tipo de propiedad',
        <div className="cm-type-grid">
          {TYPES.map(t => <button key={t.label} type="button" className={'cm-tile' + (type === t.value ? ' is-on' : '')} onClick={() => { setType(t.value); setOpen(null); }}>{t.label}</button>)}
        </div>) : null}
      {open === 'price' ? pop('Rango de precio',
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Input label="Mínimo" type="number" min="0" step="1000" placeholder="0" value={min} onChange={(e) => setMin(e.target.value)} />
            <Input label="Máximo" type="number" min="0" step="1000" placeholder="500.000" value={max} onChange={(e) => setMax(e.target.value)} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
            <Button variant="ghost" size="sm" onClick={() => { setMin(''); setMax(''); }}>Limpiar</Button>
            <Button size="sm" onClick={() => setOpen(null)}>Aplicar</Button>
          </div>
        </div>) : null}
    </div>
  );
}

/* Financiamiento sets the badge tone — BIESS, Miti-Miti, VIP and banca each read differently. */
const finTone = (f = '') => /vip/i.test(f) ? 'premium' : /biess/i.test(f) ? 'wash' : /miti/i.test(f) ? 'verified' : /banca|privada/i.test(f) ? 'dark' : 'floating';
const finIcon = (f = '') => /vip/i.test(f) ? 'shield-check' : /biess/i.test(f) ? 'badge-check' : /miti/i.test(f) ? 'handshake' : 'landmark';

function PropCard({ p, saved, onSave, onOpen }) {
  const fotos = p.fotos || [];
  const [i, setI] = React.useState(0);
  const step = (d) => (e) => { e.stopPropagation(); e.preventDefault(); setI((i + d + fotos.length) % fotos.length); };
  const meta = [p.habitaciones && p.habitaciones + ' dorm', p.banos && p.banos + ' baños', p.area && Math.round(p.area) + ' m²'].filter(Boolean).join(' · ');
  return (
    <article className="cm-card" onClick={onOpen}>
      <div className="cm-card-photo">
        <img src={fotos[i]} alt={p.titulo} loading="lazy" />
        {p.financiamiento ? <span className="cm-card-badge"><Badge tone={finTone(p.financiamiento)} icon={finIcon(p.financiamiento)}>{p.financiamiento}</Badge></span> : null}
        <span className="cm-card-heart">
          <IconButton icon="heart" variant="overlay" size={32} active={saved} label="Guardar" onClick={(e) => { e.stopPropagation(); onSave(); }} />
        </span>
        {fotos.length > 1 ? (
          <React.Fragment>
            <button className="cm-arrow is-prev" aria-label="Foto anterior" onClick={step(-1)}><Icon name="chevron-left" size={16} /></button>
            <button className="cm-arrow is-next" aria-label="Siguiente foto" onClick={step(1)}><Icon name="chevron-right" size={16} /></button>
            <span className="cm-dots">{fotos.map((_, k) => <span key={k} className={k === i ? 'is-on' : ''} onClick={(e) => { e.stopPropagation(); setI(k); }}></span>)}</span>
          </React.Fragment>) : null}
      </div>
      <div className="cm-card-body">
        <span className="cm-card-title">{p.titulo}</span>
        <span className="cm-card-sub">{p.sector}, {p.ciudad}</span>
        <span className="cm-card-sub">{meta}</span>
        <span className="cm-card-price">{money(p.precio)}</span>
      </div>
    </article>
  );
}

function Section({ title, sub, link, href, children }) {
  return (
    <section className="cm-section">
      <div className="cm-section-head">
        <div>
          <h2>{title}</h2>
          {sub ? <p>{sub}</p> : null}
        </div>
        {link ? <a href={href} target="_blank" rel="noopener" className="cm-section-link">{link}</a> : null}
      </div>
      {children}
    </section>
  );
}

function JoinDialog({ open, onClose }) {
  const [role, setRole] = React.useState('agente');
  const [form, setForm] = React.useState({ nombre: '', email: '', tel: '', msg: '' });
  const [err, setErr] = React.useState({});
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [open]);
  if (!open) return null;
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = () => {
    const e = {};
    if (!form.nombre.trim()) e.nombre = 'Escribe tu nombre completo';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Escribe un correo válido';
    if (form.tel && form.tel.replace(/\D/g, '').length < 9) e.tel = 'Ingresa 10 dígitos';
    setErr(e);
    if (!Object.keys(e).length) {
      try { localStorage.setItem('casamia:user', JSON.stringify({ nombre: form.nombre })); } catch (x) {}
      /* Aviso por Resend: el equipo recibe la solicitud con rol, teléfono y nota. */
      if (window.API) API.post('contacto', {
        nombre: form.nombre, email: form.email || 'sin-correo@casamia.ec', tel: form.tel,
        motivo: 'Quiero trabajar con casamia.ec · ' + (form.rol || 'sin rol'),
        mensaje: form.msg || 'Solicitud enviada desde el diálogo «Trabaja con nosotros».'
      }).catch(() => {});
      setSent(true);
    }
  };
  const roleCard = (id, icon, title, sub) => (
    <button type="button" onClick={() => setRole(id)} className={'cm-role' + (role === id ? ' is-on' : '')}>
      <Icon name={icon} size={22} />
      <span>
        <span className="cm-role-t">{title}</span>
        <span className="cm-role-s">{sub}</span>
      </span>
    </button>
  );
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 80 }}>
      <Dialog open onClose={onClose} width={560} title={sent ? 'Solicitud enviada' : 'Trabaja con nosotros'}
        footer={sent ? <Button block onClick={onClose}>Cerrar</Button> : <Button block onClick={submit}>Enviar solicitud</Button>}>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '16px 0 8px' }}>
            <Icon name="check-circle" size={36} style={{ color: 'var(--verified)' }} />
            <h3 style={{ marginTop: 12, fontSize: 'var(--fs-display-sm)', fontWeight: 600, color: 'var(--text-heading)' }}>Recibimos tu solicitud</h3>
            <p style={{ marginTop: 6, fontSize: 'var(--fs-body-md)', color: 'var(--text-muted)' }}>El equipo de casamia.ec revisa tu información y te escribe en menos de 24 horas.</p>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ fontSize: 'var(--fs-body-md)', color: 'var(--text-muted)' }}>Selecciona cómo quieres colaborar con casamia.ec</p>
            <div className="cm-roles">
              {roleCard('agente', 'handshake', 'Agente vendedor', 'Vendo propiedades y gano comisiones')}
              {roleCard('proyecto', 'building-2', 'Proyecto inmobiliario', 'Tengo un proyecto para comercializar')}
            </div>
            <Input label="Nombre completo" placeholder="Tu nombre y apellido" value={form.nombre} onChange={set('nombre')} error={err.nombre} />
            <Input label="Email" type="email" placeholder="tucorreo@ejemplo.com" value={form.email} onChange={set('email')} error={err.email} />
            <Input label="Teléfono / WhatsApp" placeholder="0988957054" value={form.tel} onChange={set('tel')} error={err.tel} hint="Te escribimos por WhatsApp" />
            <Input label="Cuéntanos sobre ti" placeholder="Zonas donde trabajas, experiencia, proyecto…" value={form.msg} onChange={set('msg')} />
          </div>
        )}
      </Dialog>
    </div>
  );
}

function App() {
  const [join, setJoin] = React.useState(false);
  const [saved, setSaved] = React.useState(() => { try { return JSON.parse(localStorage.getItem('casamia:saved') || '{}'); } catch (e) { return {}; } });
  const [props_, live] = useRemote(BACKEND.rest.properties, (p) => p, window.CASAMIA_PROPERTIES);
  const [posts] = useRemote(BACKEND.rest.posts, mapPost, window.CASAMIA_POSTS);
  const toggleSave = (id) => setSaved(s => { const n = { ...s, [id]: !s[id] }; try { localStorage.setItem('casamia:saved', JSON.stringify(n)); } catch (e) {} return n; });
  const savedCount = Object.values(saved).filter(Boolean).length;
  React.useEffect(() => {
    setSeo({
      title: 'casamia.ec — Casas y departamentos en venta en Quito',
      description: 'Portal inmobiliario en Ecuador: casas, departamentos y terrenos en venta y arriendo en Quito y los valles. Precios reales, fotos y contacto directo. Financiamiento BIESS, VIP, Miti-Miti y banca privada.',
      canonical: SEO.site + SEO.paths.inicio,
      keywords: 'casas en venta Quito, departamentos en venta Quito, terrenos Quito, inmobiliaria Ecuador, BIESS, crédito VIP'
    });
    jsonLd('organizacion', orgLd());
    jsonLd('sitio', siteLd());
  }, []);
  React.useEffect(() => { if (props_?.length) jsonLd('destacadas', itemListLd(props_.slice(0, 8), 'Propiedades destacadas en casamia.ec', SEO.paths.inicio)); }, [props_]);
  /* The float only appears once the hero search pill is scrolled past, so it never covers a CTA. */
  const [waOn, setWaOn] = React.useState(false);
  React.useEffect(() => {
    const el = document.querySelector('.cm-search-wrap');
    const onScroll = () => {
      const footer = document.querySelector('.cm-footer');
      const pastHero = !el || el.getBoundingClientRect().bottom < 0;
      const beforeFooter = !footer || footer.getBoundingClientRect().top > window.innerHeight - 40;
      setWaOn(pastHero && beforeFooter);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); };
  }, []);

  return (
    <div>
      <Header onJoin={() => setJoin(true)} savedCount={savedCount} />

      <section className="cm-hero-wrap">
        <div className="cm-hero">
          <img src="assets/ph-hero.png" alt="" />
          <div className="cm-hero-copy">
            <h1>Encuentra tu próxima casa en Quito</h1>
            <p>Casas, departamentos y terrenos publicados por propietarios y constructoras, con precio y financiamiento claros.</p>
          </div>
        </div>
        <div className="cm-search-wrap"><SearchPill /></div>
      </section>

      <Section title="Propiedades destacadas" sub="Las últimas propiedades publicadas en casamia.ec" link="Ver todas" href={BACKEND.links.compra}>
        <div className="cm-grid-4">
          {props_.slice(0, 8).map(p => (
            <PropCard key={p.id} p={p} saved={!!saved[p.id]} onSave={() => toggleSave(p.id)}
              onOpen={() => go(searchUrl({ loc: p.sector, type: p.tipo }))} />
          ))}
        </div>
      </Section>

      <Section title="Cómo empezar">
        <div className="cm-grid-4 cm-starts">
          {[
            { icon: 'house', t: 'Compra tu hogar', d: 'Casas, departamentos y terrenos en Quito y los valles, con fotos y precio publicados.', cta: 'Explorar', href: BACKEND.links.compra, primary: true },
            { icon: 'key-round', t: 'Vende tu propiedad', d: 'Publica tu propiedad en casamia.ec y la revisamos antes de que salga al portal.', cta: 'Publicar', href: BACKEND.links.publicar },
            { icon: 'message-circle', t: 'Contacta a un agente', d: 'Escribe por WhatsApp y un asesor de casamia.ec te acompaña en el proceso de compra.', cta: 'Escribir', href: WA() },
            { icon: 'calculator', t: 'Calcula tu crédito', d: 'Revisa tasas, plazos y cuotas de BIESS, VIP, Miti-Miti y banca privada.', cta: 'Calcular', href: BACKEND.links.creditos }
          ].map(c => (
            <Card key={c.t} interactive style={{ display: 'flex', flexDirection: 'column', gap: 10, minHeight: 196 }}>
              <Icon name={c.icon} size={24} />
              <span style={{ fontSize: 'var(--fs-display-sm)', fontWeight: 600, color: 'var(--text-heading)' }}>{c.t}</span>
              <p style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--text-muted)' }}>{c.d}</p>
              <span style={{ marginTop: 'auto' }}><Button size="sm" variant={c.primary ? 'primary' : 'outline'} onClick={() => go(c.href)}>{c.cta}</Button></span>
            </Card>
          ))}
        </div>
      </Section>

      <Section title="Por qué casamia.ec">
        <div className="cm-why">
          {[
            { icon: 'dollar-sign', t: 'Publicar es gratis', d: 'Subes tu propiedad desde el portal y nuestro equipo la revisa antes de publicarla.' },
            { icon: 'calculator', t: 'Financiamiento claro', d: 'Cada anuncio indica si aplica a BIESS, crédito VIP, Miti-Miti o banca privada.' },
            { icon: 'phone', t: 'Un asesor te responde', d: 'Escribes por WhatsApp al +593 98 895 7054 y te contesta una persona del equipo.' }
          ].map(f => (
            <div key={f.t} className="cm-why-item">
              <Icon name={f.icon} size={22} />
              <span className="cm-why-t">{f.t}</span>
              <p>{f.d}</p>
            </div>
          ))}
        </div>
      </Section>

      <Section title="Busca por zona" sub="Los sectores donde más se publica en Quito">
        <div className="cm-zones">
          {ZONAS.map(z => (
            <a key={z} href={searchUrl({ loc: z })} target="_blank" rel="noopener" className="cm-zone">
              <Icon name="map-pin" size={16} />{z}
            </a>
          ))}
        </div>
      </Section>

      <Section title="Créditos hipotecarios">
        <div className="cm-credit">
          <div className="cm-credit-hero">
            <img src="assets/ph-credito.png" alt="" />
            <div className="cm-credit-copy">
              <span className="cm-credit-title">BIESS, crédito VIP, Miti-Miti y banca privada</span>
              <span><Button pill size="sm" onClick={() => go(BACKEND.links.creditos)}>Ver opciones</Button></span>
            </div>
          </div>
          <Card interactive style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Icon name="calculator" size={24} />
            <span style={{ fontSize: 'var(--fs-display-sm)', fontWeight: 600, color: 'var(--text-heading)' }}>Simula tu cuota</span>
            <p style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--text-muted)' }}>Revisa montos, plazos y tasas vigentes antes de reservar una casa.</p>
            <a href={BACKEND.links.creditos} target="_blank" rel="noopener" style={{ marginTop: 'auto', fontSize: 'var(--fs-body-sm)' }}>Ver créditos</a>
          </Card>
          <Card interactive style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Icon name="message-circle" size={24} />
            <span style={{ fontSize: 'var(--fs-display-sm)', fontWeight: 600, color: 'var(--text-heading)' }}>¿Dudas con tu crédito?</span>
            <p style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--text-muted)' }}>Cuéntanos tu caso por WhatsApp y te decimos qué opciones tienes.</p>
            <a href={WA('Hola, tengo dudas sobre el crédito hipotecario.')} target="_blank" rel="noopener" style={{ marginTop: 'auto', fontSize: 'var(--fs-body-sm)' }}>Escribir por WhatsApp</a>
          </Card>
        </div>
      </Section>

      <Section title="Novedades inmobiliarias" sub="Lo último del mercado inmobiliario en Quito" link="Ver todas" href={BACKEND.links.novedades}>
        <div className="cm-grid-4 cm-posts">
          {posts.slice(0, 4).map(n => (
            <a key={n.id} href={n.url} target="_blank" rel="noopener" className="cm-post">
              <div className="cm-post-img"><img src={n.photoUrl} alt="" /></div>
              <span className="cm-post-meta">{n.kicker} · {n.date}</span>
              <span className="cm-post-title">{n.title}</span>
            </a>
          ))}
        </div>
      </Section>

      <footer className="cm-footer">
        <div className="cm-footer-in">
          <div className="cm-footer-brand">
            <img src="assets/logo-casamia-alpha.png" alt="casamia.ec" />
            <p className="cm-footer-tag">Tu hogar ideal en minutos.</p>
            <a className="cm-footer-wa" href={WA()} target="_blank" rel="noopener"><Icon name="message-circle" size={15} />+593 98 895 7054</a>
          </div>
          {[
            { t: 'Propiedades', l: [['Comprar', BACKEND.links.compra], ['Vender', BACKEND.links.publicar], ['Créditos hipotecarios', BACKEND.links.creditos]] },
            { t: 'Empresa', l: [['Contacto', BACKEND.links.contacto], ['Novedades', BACKEND.links.novedades]] },
            { t: 'Contacto', l: [['hola@casamia.ec', 'mailto:hola@casamia.ec'], ['Quito, Ecuador', BACKEND.links.contacto]] }
          ].map(c => (
            <div key={c.t}>
              <div className="cm-footer-h">{c.t}</div>
              <ul className="cm-footer-list">
                {c.l.map(([label, href]) => <li key={label}><a href={href} target="_blank" rel="noopener">{label}</a></li>)}
                {c.t === 'Empresa' ? <li><a href="#" onClick={(e) => { e.preventDefault(); setJoin(true); }}>Trabaja con nosotros</a></li> : null}
              </ul>
            </div>
          ))}
        </div>
        <div className="cm-footer-legal">
          <span>© 2026 casamia.ec</span>
          <span className="cm-footer-social">
            <a href={BACKEND.links.facebook} target="_blank" rel="noopener" aria-label="Facebook"><Icon name="facebook" size={16} /></a>
            <a href={BACKEND.links.instagram} target="_blank" rel="noopener" aria-label="Instagram"><Icon name="instagram" size={16} /></a>
            <a href={BACKEND.links.tiktok} target="_blank" rel="noopener" aria-label="TikTok"><Icon name="music-2" size={16} /></a>
          </span>
          <a className="cm-agency" href={BACKEND.links.agencia} target="_blank" rel="noopener" aria-label="agave">agave<i>.</i></a>
        </div>
      </footer>

      <a className={"cm-wa" + (waOn ? " is-on" : "")} href={WA()} target="_blank" rel="noopener" aria-label="Escríbenos por WhatsApp">
        <Icon name="message-circle" size={18} />WhatsApp
      </a>

      <div className="cm-bar">
        <nav className="cm-bar-main">
          <a href={BACKEND.links.compra} target="_blank" rel="noopener"><Icon name="search" size={19} />Explorar</a>
          <a href={BACKEND.links.creditos} target="_blank" rel="noopener"><Icon name="calculator" size={19} />Créditos</a>
          <a href={BACKEND.links.publicar} target="_blank" rel="noopener"><Icon name="key-round" size={19} />Publicar</a>
        </nav>
        <a className="cm-bar-wa" href={WA()} target="_blank" rel="noopener" aria-label="Escríbenos por WhatsApp"><Icon name="message-circle" size={22} /></a>
      </div>

      <JoinDialog open={join} onClose={() => setJoin(false)} />
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
