// KSANET — shared web components

// Monograma KSANET — versión brandbook v3 (Tech)
// Marco rectangular abierto + K geométrica con nodo + ticks de medición + nodos en extremos
const KMonogram = ({ size = 32, color = '#8C1E22', accent = '#4a4945', bg = 'transparent' }) => {
  const stroke = Math.max(1.4, size / 80);
  return (
    <svg width={size} height={size} viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
      {bg !== 'transparent' && <rect x="0" y="0" width="200" height="200" fill={bg}/>}
      {/* Outer bracket frame — abierto en TR y BL */}
      <g fill="none" stroke={color} strokeWidth={stroke * 1.05} strokeLinecap="square">
        <path d="M 22 50 L 22 22 L 60 22"/>
        <path d="M 178 22 L 178 50"/>
        <path d="M 178 150 L 178 178 L 140 178"/>
        <path d="M 22 178 L 22 150"/>
      </g>
      {/* Tick marks — medición / rejilla */}
      <g fill={accent} opacity="0.7">
        <rect x="99" y="22" width="2" height="6"/>
        <rect x="99" y="172" width="2" height="6"/>
        <rect x="22" y="99" width="6" height="2"/>
        <rect x="172" y="99" width="6" height="2"/>
      </g>
      {/* La K — trazos rectos */}
      <g fill="none" stroke={color} strokeWidth={stroke * 2.4} strokeLinecap="square" strokeLinejoin="miter">
        <path d="M 66 56 L 66 144"/>
        <path d="M 66 100 L 130 56"/>
        <path d="M 66 100 L 130 144"/>
      </g>
      {/* Nodo en vértice de la K — firma tech */}
      <g>
        <circle cx="66" cy="100" r={stroke * 1.8} fill={color}/>
        <circle cx="66" cy="100" r={stroke * 0.6} fill="#f6f3ee"/>
      </g>
      {/* Nodos en extremos */}
      <circle cx="130" cy="56" r={stroke * 1.2} fill={accent}/>
      <circle cx="130" cy="144" r={stroke * 1.2} fill={accent}/>
    </svg>
  );
};

/* Wordmark: KSANET en Inter Tight, peso medio, tracking ancho, con punto tras la T (brandbook v3) */
const KWordmark = ({ height = 18, color = 'var(--ink)', accent = '#8C1E22' }) => (
  <div style={{ display: 'flex', alignItems: 'baseline', gap: height * 0.18, lineHeight: 1 }}>
    <span style={{
      fontFamily: 'Inter Tight, Inter, sans-serif',
      fontWeight: 500,
      fontSize: height,
      letterSpacing: '0.36em',
      color,
      lineHeight: 1,
      paddingLeft: '0.08em',
    }}>KSANET</span>
    <span style={{
      width: Math.max(2, height * 0.08),
      height: Math.max(2, height * 0.08),
      background: accent,
      display: 'inline-block',
      transform: `translateY(${-height * 0.02}px)`,
    }}></span>
  </div>
);

/* Tagline — brandbook v3 */
const TAGLINE_DEFAULT = 'Una puerta abierta desde 2012';
const KTagline = ({ color = '#6f6660', size = 10, text = TAGLINE_DEFAULT }) => {
  const isLong = (text || '').length > 14;
  const tracking = isLong ? '.22em' : '.42em';
  return (
    <span style={{
      fontFamily: 'JetBrains Mono, monospace',
      fontSize: size,
      letterSpacing: tracking,
      fontWeight: 500,
      textTransform: 'uppercase',
      color,
      whiteSpace: 'nowrap',
    }}>{text}</span>
  );
};

/* Lockup horizontal — monograma + (wordmark sobre tagline) */
const Brand = ({ size = 38, color = 'var(--ink)', linkBase = '', dark = false, tagline = TAGLINE_DEFAULT }) => {
  const ring = dark ? '#f3e8da' : '#8C1E22';
  const accent = dark ? '#b6b3ad' : '#4a4945';
  const ink = dark ? '#f3e8da' : '#0f0d0c';
  const tag = dark ? 'rgba(243,232,218,.6)' : '#6f6660';
  return (
    <a href={linkBase + 'index.html'} className="nav-brand" aria-label="KSANET · Inicio">
      <KMonogram size={size} color={ring} accent={accent}/>
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: Math.max(2, size * 0.14), lineHeight: 1 }}>
        <KWordmark height={size * 0.36} color={ink} accent={ring}/>
        <KTagline color={tag} size={Math.max(8, size * 0.13)} text={tagline}/>
      </div>
    </a>
  );
};

const Header = ({ active, base = '' }) => {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  const links = [
    { k: 'home', label: 'Inicio', href: base + 'index.html' },
    { k: 'promociones', label: 'Promociones', href: base + 'promociones.html' },
    { k: 'cooperativa', label: 'Cooperativa', href: base + 'cooperativa.html' },
    { k: 'guia', label: 'Guía del socio', href: base + 'guia.html' },
    { k: 'plataforma', label: 'Plataforma KSA', href: base + 'plataforma.html' },
    { k: 'calculadora', label: 'Calculadora', href: base + 'calculadora.html' },
    { k: 'contacto', label: 'Contacto', href: base + 'contacto.html' },
  ];
  return (
    <header className="nav">
      <div className="nav-inner">
        <Brand linkBase={base} />
        <nav className="nav-links" aria-label="Principal">
          {links.map(l => (
            <a key={l.k} className={'nav-link' + (active === l.k ? ' active' : '')} href={l.href}>{l.label}</a>
          ))}
        </nav>
        <a className="nav-cta" href={base + 'plataforma.html'}>Acceso socio →</a>
        <button className={'nav-burger ' + (open ? 'open' : '')} onClick={() => setOpen(!open)} aria-label="Menú">
          <span></span><span></span><span></span>
        </button>
      </div>
      {open && (
        <>
          <div className="nav-mobile-backdrop" onClick={() => setOpen(false)}></div>
          <nav className="nav-mobile-drawer" aria-label="Móvil">
            {links.map(l => (
              <a key={l.k} className={'nav-mobile-link' + (active === l.k ? ' active' : '')} href={l.href} onClick={() => setOpen(false)}>{l.label}</a>
            ))}
            <a className="nav-mobile-link" href={base + 'plataforma.html'} onClick={() => setOpen(false)} style={{ color: 'var(--brand)', marginTop: 16 }}>Acceso socio →</a>
          </nav>
        </>
      )}
    </header>
  );
};

const Footer = ({ base = '' }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 22 }}>
            <KMonogram size={42} color="#f3e8da" accent="#b6b3ad"/>
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 6, lineHeight: 1 }}>
              <KWordmark height={16} color="#f3e8da" accent="#f3e8da"/>
              <KTagline color="rgba(243,232,218,.62)" size={9} text="Una puerta abierta desde 2012"/>
            </div>
          </div>
          <p style={{ color: 'rgba(230, 224, 211, 0.78)', fontSize: 14, lineHeight: 1.6, maxWidth: 360, margin: 0 }}>
            Gestora profesional de cooperativas de viviendas. Más de 25.000 viviendas entregadas, 400 cooperativas y 40 años en el sector.
          </p>
          <p style={{ color: 'var(--silver)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontFamily: 'var(--mono)', marginTop: 28 }}>
            Miembros fundadores AGV
          </p>
        </div>
        <div>
          <h4>Navegación</h4>
          <ul>
            <li><a href={base + 'index.html'}>Inicio</a></li>
            <li><a href={base + 'promociones.html'}>Promociones</a></li>
            <li><a href={base + 'cooperativa.html'}>Cooperativa</a></li>
            <li><a href={base + 'plataforma.html'}>Plataforma KSA</a></li>
            <li><a href={base + 'calculadora.html'}>Calculadora</a></li>
            <li><a href={base + 'contacto.html'}>Contacto</a></li>
          </ul>
        </div>
        <div>
          <h4>Contacto</h4>
          <ul>
            <li>+34 916 666 608</li>
            <li><a href="mailto:hola@ksanet.es">hola@ksanet.es</a></li>
            <li style={{ color: 'rgba(230, 224, 211, 0.78)' }}>Calle Marie Curie, 7<br/>Edificio Beta, oficina 3.3<br/>28521 Rivas-Vaciamadrid</li>
          </ul>
        </div>
        <div>
          <h4>Legal</h4>
          <ul>
            <li><a href="#">Términos de uso</a></li>
            <li><a href="#">Privacidad</a></li>
            <li><a href="#">Política de cookies</a></li>
            <li><a href="#">AGV</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 KSANET · Brandbook 3.0</span>
        <span>La gestora con plataforma. La plataforma con cuarenta años.</span>
      </div>
    </div>
  </footer>
);

// Reveal hook
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// Architectural placeholder when no photo
const ArchPlaceholder = ({ tone = 'var(--paper-2)', accent = 'var(--brand)', label }) => (
  <div style={{ position: 'absolute', inset: 0, background: tone, overflow: 'hidden' }}>
    <svg viewBox="0 0 600 450" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
         style={{ position: 'absolute', inset: 0, opacity: 0.32 }}>
      {/* facade grid */}
      {Array.from({ length: 14 }).map((_, c) =>
        Array.from({ length: 8 }).map((_, r) => (
          <rect key={c + '-' + r}
                x={50 + c * 38} y={50 + r * 42}
                width={28} height={32}
                fill="none" stroke={accent} strokeWidth="1"/>
        ))
      )}
      <line x1="0" y1="386" x2="600" y2="386" stroke={accent} strokeWidth="1.2"/>
    </svg>
    {label && (
      <div style={{
        position: 'absolute', bottom: 18, left: 22,
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.2em',
        textTransform: 'uppercase', color: 'var(--muted)',
      }}>{label}</div>
    )}
  </div>
);

Object.assign(window, { KMonogram, KWordmark, KTagline, Brand, Header, Footer, useReveal, ArchPlaceholder });
