/* eslint-disable react/prop-types */
/**
 * FichaBody · Cuerpo de la ficha de distrito.
 *
 * - Resumen expandido en columna izquierda
 * - Sidebar derecha con datos clave (year, types, region, estado, tags)
 * - Sección "Otros distritos" con 3 cards relacionadas (misma región o tipología)
 * - CTA al ContactSection (en la composición de la página)
 */

const { useMemo: uM_FB } = React;

function FichaBody({ d }) {
  if (!d) return null;
  const all = window.DISTRITOS_DATA || [];

  // Relacionados: mismo region + tipología, hasta 3 distintos al actual
  const related = uM_FB(() => {
    const matches = all.filter(x =>
      x.slug !== d.slug &&
      (x.region === d.region || x.types?.some(t => d.types?.includes(t)))
    );
    // Priorizar: mismo region Y misma tipología primero
    matches.sort((a, b) => {
      const aRegion = a.region === d.region ? 1 : 0;
      const bRegion = b.region === d.region ? 1 : 0;
      const aType   = a.types?.some(t => d.types?.includes(t)) ? 1 : 0;
      const bType   = b.types?.some(t => d.types?.includes(t)) ? 1 : 0;
      return (bRegion + bType) - (aRegion + aType);
    });
    return matches.slice(0, 3);
  }, [d.slug]);

  return (
    <React.Fragment>
      {/* Resumen + Datos clave */}
      <section data-screen-label="02 Ficha Resumen" style={fbStyles.section}>
        <div className="container" style={fbStyles.grid}>
          {/* Resumen */}
          <window.Reveal>
            <div style={fbStyles.col}>
              <span className="eyebrow">RESUMEN</span>
              <p style={fbStyles.lead}>{d.summary}</p>

              {/* Descripción extendida (si existe) */}
              {d.description && (
                <div style={fbStyles.descBlock}>
                  <p style={fbStyles.descText}>{d.description}</p>
                </div>
              )}

              {/* Métricas concretas (si existen) */}
              {d.metrics && d.metrics.length > 0 && (
                <div style={fbStyles.metricsBlock}>
                  <span className="eyebrow" style={fbStyles.subEyebrow}>EN NÚMEROS</span>
                  <dl style={fbStyles.metricsDl}>
                    {d.metrics.map((m, i) => (
                      <div key={i} style={fbStyles.metricRow}>
                        <dt style={fbStyles.metricLabel}>{m.label}</dt>
                        <dd style={fbStyles.metricValue}>{m.value}</dd>
                      </div>
                    ))}
                  </dl>
                </div>
              )}

              {/* Premios y reconocimientos */}
              {d.awards && d.awards.length > 0 && (
                <div style={fbStyles.awardsBlock}>
                  <span className="eyebrow" style={fbStyles.subEyebrow}>RECONOCIMIENTOS</span>
                  <ul style={fbStyles.awardsList}>
                    {d.awards.map((a, i) => (
                      <li key={i} style={fbStyles.awardItem}>
                        <span style={fbStyles.awardDot} aria-hidden="true" />
                        <span>{a}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Publicaciones / referencias externas */}
              {d.publications && d.publications.length > 0 && (
                <div style={fbStyles.pubsBlock}>
                  <span className="eyebrow" style={fbStyles.subEyebrow}>PUBLICADO EN</span>
                  <ul style={fbStyles.pubsList}>
                    {d.publications.map((p, i) => (
                      <li key={i}>
                        <a href={p.url} target="_blank" rel="noopener noreferrer" style={fbStyles.pubLink} data-cursor="link">
                          <window.Icon name="arrow-up-right" size={13} stroke={1.6} />
                          <span>{p.source}</span>
                        </a>
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Fallback note solo si NO hay description (placeholder) */}
              {!d.description && (
                d.verified ? (
                  <p style={fbStyles.note}>
                    Este es uno de los distritos emblemáticos del portafolio Prosperia — el método DIGO® lo estructuró desde la pregunta de demanda, y su evidencia se sigue calibrando contra el resultado real del proyecto.
                  </p>
                ) : (
                  <p style={fbStyles.note}>
                    Este distrito es parte del portafolio +1,900 proyectos originados. La ficha completa con cifras detalladas — superficie, inversión, IRR, mezcla de usos, fases — se compartió bajo confidencialidad con el cliente original. Si quieres más detalle, escríbenos.
                  </p>
                )
              )}
            </div>
          </window.Reveal>

          {/* Datos clave / sidebar */}
          <window.Reveal delay={120}>
            <aside style={fbStyles.sidebar}>
              <span className="eyebrow" style={fbStyles.sbEyebrow}>DATOS CLAVE</span>
              <dl style={fbStyles.dl}>
                <div style={fbStyles.dlRow}>
                  <dt style={fbStyles.dt}>Ubicación</dt>
                  <dd style={fbStyles.dd}>{d.location}</dd>
                </div>
                <div style={fbStyles.dlRow}>
                  <dt style={fbStyles.dt}>Región</dt>
                  <dd style={fbStyles.dd}>{d.region}</dd>
                </div>
                <div style={fbStyles.dlRow}>
                  <dt style={fbStyles.dt}>Año de originación</dt>
                  <dd style={fbStyles.dd}>{d.year}</dd>
                </div>
                <div style={fbStyles.dlRow}>
                  <dt style={fbStyles.dt}>Tipologías</dt>
                  <dd style={fbStyles.dd}>{(d.types || []).join(' · ')}</dd>
                </div>
                <div style={fbStyles.dlRow}>
                  <dt style={fbStyles.dt}>Estado</dt>
                  <dd style={fbStyles.dd}>{d.estado}</dd>
                </div>

                {/* Créditos (si existen) */}
                {d.credits && d.credits.length > 0 && (
                  <div style={fbStyles.dlRow}>
                    <dt style={fbStyles.dt}>Equipo</dt>
                    <dd style={fbStyles.dd}>
                      <ul style={fbStyles.creditsList}>
                        {d.credits.map((c, i) => (
                          <li key={i} style={fbStyles.creditItem}>
                            <span style={fbStyles.creditRole}>{c.role}</span>
                            <span style={fbStyles.creditName}>{c.name}</span>
                          </li>
                        ))}
                      </ul>
                    </dd>
                  </div>
                )}

                {/* Sitio web (si existe) */}
                {d.website && (
                  <div style={fbStyles.dlRow}>
                    <dt style={fbStyles.dt}>Sitio web</dt>
                    <dd style={fbStyles.dd}>
                      <a href={d.website} target="_blank" rel="noopener noreferrer" style={fbStyles.websiteLink} data-cursor="link">
                        <window.Icon name="globe" size={14} stroke={1.6} />
                        <span>{d.website.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '')}</span>
                      </a>
                    </dd>
                  </div>
                )}

                {d.tags && d.tags.length > 0 && (
                  <div style={fbStyles.dlRow}>
                    <dt style={fbStyles.dt}>Tags</dt>
                    <dd style={fbStyles.dd}>
                      <div style={fbStyles.tagWrap}>
                        {d.tags.map(t => (
                          <span key={t} style={fbStyles.tag}>{t}</span>
                        ))}
                      </div>
                    </dd>
                  </div>
                )}
              </dl>

              <div style={fbStyles.sbCta}>
                <a href="/home/Home.html#contacto" className="btn btn-copper" data-cursor="link" style={{ width: '100%', justifyContent: 'center' }}>
                  Hablar de un proyecto similar
                  <window.Icon name="arrow-right" size={16} stroke={1.8} />
                </a>
                <a href="/distritos/Distritos.html" style={fbStyles.sbBack} data-cursor="link">
                  <window.Icon name="arrow-right" size={13} stroke={1.6} style={{ transform: 'rotate(180deg)' }} />
                  <span>Ver todos los distritos</span>
                </a>
              </div>
            </aside>
          </window.Reveal>
        </div>
      </section>

      {/* Otros distritos relacionados */}
      {related.length > 0 && (
        <section data-screen-label="03 Otros Distritos" style={fbStyles.relatedSection}>
          <div className="container">
            <window.Reveal>
              <div style={fbStyles.relatedHeader}>
                <span className="eyebrow">OTROS DISTRITOS</span>
                <h2 style={fbStyles.relatedTitle}>
                  Cerca, o con la misma <span style={fbStyles.relatedTitleSoft}>tesis de demanda.</span>
                </h2>
              </div>
            </window.Reveal>

            <div style={fbStyles.relGrid}>
              {related.map((r, i) => (
                <window.Reveal key={r.slug} delay={i * 90}>
                  <a
                    href={`/distritos/Ficha.html?slug=${r.slug}`}
                    style={fbStyles.relCard}
                    data-cursor="link"
                  >
                    <div style={fbStyles.relImgWrap}>
                      <window.ImagePlaceholder
                        src={r.img}
                        alt={r.name}
                        label={r.name.toUpperCase()}
                        tone={r.tone || 'urban'}
                        ratio="auto"
                        style={{ width: '100%', height: '100%', aspectRatio: 'auto' }}
                        overlay
                        overlayOpacity={0.42}
                      />
                    </div>
                    <div style={fbStyles.relBody}>
                      <div style={fbStyles.relChips}>
                        {(r.types || []).slice(0, 2).map(t => (
                          <span key={t} style={fbStyles.relChip}>{t}</span>
                        ))}
                      </div>
                      <h3 style={fbStyles.relName}>{r.name}</h3>
                      <p style={fbStyles.relLoc}>{r.location}</p>
                    </div>
                    <span style={fbStyles.relArrow}>
                      <window.Icon name="arrow-up-right" size={20} stroke={1.6} />
                    </span>
                  </a>
                </window.Reveal>
              ))}
            </div>
          </div>
        </section>
      )}
    </React.Fragment>
  );
}

const fbStyles = {
  section: {
    background: 'var(--color-cream)',
    paddingTop: 'var(--space-3xl)',
    paddingBottom: 'var(--space-3xl)',
  },
  grid: {
    display: 'grid',
    gridTemplateColumns: '1fr',
    gap: 'var(--space-2xl)',
    alignItems: 'start',
  },
  col: { maxWidth: 720 },
  lead: {
    margin: '20px 0 0',
    fontSize: 'clamp(19px, 1.8vw, 24px)',
    lineHeight: 1.55,
    color: 'var(--color-navy-deep)',
    letterSpacing: '-0.003em',
    textWrap: 'pretty',
  },
  descBlock: { marginTop: 32 },
  descText: {
    margin: 0,
    fontSize: 16,
    lineHeight: 1.75,
    color: 'var(--color-navy-medium)',
    textWrap: 'pretty',
  },
  subEyebrow: { marginBottom: 16, display: 'block' },

  metricsBlock: { marginTop: 40 },
  metricsDl: {
    margin: 0, padding: 0,
    display: 'grid',
    gridTemplateColumns: '1fr',
    gap: 0,
    borderTop: '1px solid rgba(33,52,64,0.12)',
  },
  metricRow: {
    display: 'grid',
    gridTemplateColumns: '1fr auto',
    gap: 16,
    paddingBlock: 14,
    borderBottom: '1px solid rgba(33,52,64,0.08)',
    alignItems: 'baseline',
  },
  metricLabel: {
    margin: 0,
    fontSize: 13, fontWeight: 600,
    color: 'var(--color-navy-medium)',
    letterSpacing: '0.02em',
  },
  metricValue: {
    margin: 0,
    fontSize: 15, fontWeight: 700,
    color: 'var(--color-navy-deep)',
    fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
    textAlign: 'right',
  },

  awardsBlock: { marginTop: 40 },
  awardsList: {
    listStyle: 'none', margin: 0, padding: 0,
    display: 'flex', flexDirection: 'column', gap: 10,
  },
  awardItem: {
    display: 'flex',
    alignItems: 'flex-start',
    gap: 14,
    fontSize: 14,
    lineHeight: 1.55,
    color: 'var(--color-navy-deep)',
  },
  awardDot: {
    width: 6, height: 6, borderRadius: 999,
    background: 'var(--color-copper-fallback)',
    flexShrink: 0,
    marginTop: 8,
  },

  pubsBlock: { marginTop: 40 },
  pubsList: {
    listStyle: 'none', margin: 0, padding: 0,
    display: 'flex', flexDirection: 'column', gap: 8,
  },
  pubLink: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    fontSize: 14, fontWeight: 600,
    color: 'var(--color-copper-fallback)',
    transition: 'gap 220ms ease, color 220ms ease',
  },
  note: {
    margin: '28px 0 0',
    paddingLeft: 20,
    borderLeft: '3px solid var(--color-copper-fallback)',
    fontSize: 15,
    lineHeight: 1.7,
    color: 'var(--color-navy-medium)',
    fontStyle: 'italic',
  },
  sidebar: {
    background: '#fff',
    border: '1px solid rgba(33,52,64,0.1)',
    padding: 'clamp(24px, 3vw, 36px)',
    borderRadius: 2,
    position: 'relative',
  },
  sbEyebrow: { marginBottom: 20, display: 'block' },
  dl: { margin: 0, padding: 0 },
  dlRow: {
    display: 'flex', flexDirection: 'column', gap: 4,
    paddingBlock: 14,
    borderBottom: '1px solid rgba(33,52,64,0.08)',
  },
  dt: {
    margin: 0,
    fontSize: 11, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-navy-medium)',
  },
  dd: {
    margin: 0,
    fontSize: 15,
    color: 'var(--color-navy-deep)',
    fontWeight: 500,
    lineHeight: 1.4,
  },
  tagWrap: { display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 4 },
  tag: {
    fontSize: 10, fontWeight: 700,
    letterSpacing: '0.1em',
    color: 'var(--color-copper-fallback)',
    background: 'rgba(168,107,45,0.08)',
    border: '1px solid rgba(168,107,45,0.25)',
    padding: '3px 8px', borderRadius: 2,
    fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
  },
  creditsList: {
    listStyle: 'none', margin: '4px 0 0', padding: 0,
    display: 'flex', flexDirection: 'column', gap: 8,
  },
  creditItem: {
    display: 'flex', flexDirection: 'column', gap: 2,
  },
  creditRole: {
    fontSize: 10, fontWeight: 700,
    letterSpacing: '0.14em',
    color: 'var(--color-navy-medium)',
    textTransform: 'uppercase',
  },
  creditName: {
    fontSize: 14, fontWeight: 600,
    color: 'var(--color-navy-deep)',
    lineHeight: 1.35,
  },
  websiteLink: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 7,
    fontSize: 14, fontWeight: 600,
    color: 'var(--color-copper-fallback)',
    marginTop: 4,
    wordBreak: 'break-all',
    transition: 'gap 220ms ease',
  },
  sbCta: { marginTop: 28, display: 'flex', flexDirection: 'column', gap: 14 },
  sbBack: {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    color: 'var(--color-navy-medium)',
    fontWeight: 600, fontSize: 13,
    textAlign: 'center', justifyContent: 'center',
    transition: 'color 200ms',
  },

  relatedSection: {
    background: 'var(--color-cream-soft)',
    paddingTop: 'var(--space-3xl)',
    paddingBottom: 'var(--space-3xl)',
  },
  relatedHeader: { maxWidth: 720, marginBottom: 'var(--space-xl)' },
  relatedTitle: {
    margin: '16px 0 0',
    fontWeight: 800,
    fontSize: 'clamp(28px, 3.6vw, 44px)',
    lineHeight: 1.15,
    color: 'var(--color-navy-deep)',
    letterSpacing: '-0.005em',
  },
  relatedTitleSoft: { color: 'var(--color-navy-medium)', fontWeight: 500 },
  relGrid: {
    display: 'grid',
    gridTemplateColumns: '1fr',
    gap: 'var(--space-md)',
  },
  relCard: {
    position: 'relative',
    display: 'flex', flexDirection: 'column',
    background: '#fff',
    border: '1px solid rgba(33,52,64,0.08)',
    borderRadius: 2,
    overflow: 'hidden',
    color: 'inherit',
    textDecoration: 'none',
    transition: 'transform 360ms cubic-bezier(0.16,1,0.3,1), border-color 360ms ease, box-shadow 360ms ease',
  },
  relImgWrap: { position: 'relative', aspectRatio: '4/3', overflow: 'hidden' },
  relBody:    { padding: 24 },
  relChips:   { display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 },
  relChip: {
    fontSize: 10, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-navy-deep)',
    background: 'rgba(33,52,64,0.06)',
    padding: '4px 10px', borderRadius: 2,
  },
  relName: {
    margin: 0,
    fontSize: 20, fontWeight: 800,
    color: 'var(--color-navy-deep)',
    letterSpacing: '-0.005em',
  },
  relLoc: {
    margin: '6px 0 0',
    fontSize: 13,
    color: 'var(--color-navy-medium)',
  },
  relArrow: {
    position: 'absolute', top: 18, right: 18,
    width: 36, height: 36,
    background: 'rgba(255,255,255,0.92)',
    backdropFilter: 'blur(8px)',
    borderRadius: 999,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    color: 'var(--color-navy-deep)',
    transition: 'background 240ms ease, color 240ms ease, transform 240ms ease',
  },
};

const fbMQ = document.createElement('style');
fbMQ.textContent = `
  @media (min-width: 900px) {
    section[data-screen-label="02 Ficha Resumen"] > div {
      grid-template-columns: minmax(0, 1.45fr) minmax(280px, 1fr) !important;
      gap: var(--space-3xl) !important;
    }
  }
  @media (min-width: 700px) {
    section[data-screen-label="03 Otros Distritos"] > div > div:last-child {
      grid-template-columns: 1fr 1fr !important;
    }
  }
  @media (min-width: 1024px) {
    section[data-screen-label="03 Otros Distritos"] > div > div:last-child {
      grid-template-columns: 1fr 1fr 1fr !important;
    }
  }
  section[data-screen-label="03 Otros Distritos"] a[style*="overflow: hidden"]:hover {
    transform: translateY(-3px);
    border-color: rgba(168,107,45,0.4) !important;
    box-shadow: 0 16px 40px rgba(33,52,64,0.08);
  }
  section[data-screen-label="03 Otros Distritos"] a[style*="overflow: hidden"]:hover > span:last-child {
    background: var(--color-copper-fallback) !important;
    color: #fff !important;
    transform: translate(2px, -2px);
  }
  section[data-screen-label="02 Ficha Resumen"] a[style*="margin-top: 0"]:hover {
    color: var(--color-navy-deep) !important;
  }
  section[data-screen-label="02 Ficha Resumen"] a[target="_blank"]:hover {
    gap: 12px !important;
  }
`;
document.head.appendChild(fbMQ);

window.FichaBody = FichaBody;
