/* global React */

function LegalModal({ type, onClose }) {
  const t = window.useT();
  const overlayRef = React.useRef(null);

  const avisoSections = [
    { heading: t('footer.legal.aviso.section_0.heading'), body: t('footer.legal.aviso.section_0.body') },
    { heading: t('footer.legal.aviso.section_1.heading'), body: t('footer.legal.aviso.section_1.body') },
    { heading: t('footer.legal.aviso.section_2.heading'), body: t('footer.legal.aviso.section_2.body') },
    { heading: t('footer.legal.aviso.section_3.heading'), body: t('footer.legal.aviso.section_3.body') },
    { heading: t('footer.legal.aviso.section_4.heading'), body: t('footer.legal.aviso.section_4.body') },
  ];

  const privacidadSections = [
    { heading: t('footer.legal.privacidad.section_0.heading'), body: t('footer.legal.privacidad.section_0.body') },
    { heading: t('footer.legal.privacidad.section_1.heading'), body: t('footer.legal.privacidad.section_1.body') },
    { heading: t('footer.legal.privacidad.section_2.heading'), body: t('footer.legal.privacidad.section_2.body') },
    { heading: t('footer.legal.privacidad.section_3.heading'), body: t('footer.legal.privacidad.section_3.body') },
    { heading: t('footer.legal.privacidad.section_4.heading'), body: t('footer.legal.privacidad.section_4.body') },
    { heading: t('footer.legal.privacidad.section_5.heading'), body: t('footer.legal.privacidad.section_5.body') },
    { heading: t('footer.legal.privacidad.section_6.heading'), body: t('footer.legal.privacidad.section_6.body') },
    { heading: t('footer.legal.privacidad.section_7.heading'), body: t('footer.legal.privacidad.section_7.body') },
  ];

  const contentTitle = type === 'aviso' ? t('footer.legal.aviso.title') : t('footer.legal.privacidad.title');
  const sections = type === 'aviso' ? avisoSections : privacidadSections;

  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, []);

  return (
    <div
      ref={overlayRef}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(27,20,16,0.72)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '24px 16px',
        animation: 'legalFadeIn 240ms ease',
      }}>
      <div style={{
        width: '100%', maxWidth: 'min(90vw, 900px)',
        maxHeight: 'min(85vh, 800px)',
        background: 'var(--lr-cal-blanca, #f3eee7)',
        overflowY: 'auto',
        WebkitOverflowScrolling: 'touch',
        position: 'relative',
        animation: 'legalSlideIn 280ms cubic-bezier(.2,.7,.15,1)',
      }}>
        {/* Header */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 10,
          background: 'var(--lr-cal-blanca, #f3eee7)',
          borderBottom: '1px solid rgba(60,40,20,0.14)',
          padding: '24px 32px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div>
            <div style={{
              fontFamily: 'var(--font-ui, Inter, sans-serif)', fontWeight: 700, fontSize: 9,
              letterSpacing: '0.32em', textTransform: 'uppercase',
              color: 'var(--lr-terracota, #b8543a)', marginBottom: 4,
            }}>{t('footer.legal.modal_header_prefix')}</div>
            <h2 style={{
              fontFamily: 'var(--font-display, "Playfair Display", serif)', fontWeight: 400,
              fontSize: 26, lineHeight: 1.1, letterSpacing: '-0.016em',
              color: 'var(--lr-tierra-profunda, #3c2814)', margin: 0,
            }}>{contentTitle}</h2>
          </div>
          <button onClick={onClose} aria-label={t('footer.legal.close')} style={{
            background: 'transparent', border: '1px solid rgba(60,40,20,0.2)',
            width: 36, height: 36, fontSize: 20, cursor: 'pointer',
            color: 'var(--lr-tierra-profunda, #3c2814)',
            flexShrink: 0, marginLeft: 16,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>×</button>
        </div>

        {/* Content */}
        <div style={{ padding: '32px 32px 48px' }}>
          {sections.map((s, i) => (
            <div key={i} style={{
              marginBottom: 32,
              paddingTop: i > 0 ? 28 : 0,
              borderTop: i > 0 ? '1px solid rgba(60,40,20,0.1)' : 'none',
            }}>
              <div style={{
                fontFamily: 'var(--font-ui, Inter, sans-serif)', fontWeight: 700, fontSize: 9,
                letterSpacing: '0.28em', textTransform: 'uppercase',
                color: 'var(--lr-tierra-profunda, #3c2814)', marginBottom: 12,
              }}>{s.heading}</div>
              {s.body.split('\n\n').map((para, j) => (
                <p key={j} style={{
                  fontFamily: 'var(--font-body, Inter, sans-serif)', fontSize: 13.5, lineHeight: 1.72,
                  color: 'var(--lr-tierra-500, #6b4c34)', margin: '0 0 12px',
                  whiteSpace: 'pre-line',
                }}>{para}</p>
              ))}
            </div>
          ))}
          <div style={{
            marginTop: 32, paddingTop: 24,
            borderTop: '1px solid rgba(60,40,20,0.14)',
            fontFamily: 'var(--font-ui, Inter, sans-serif)', fontSize: 10,
            letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'rgba(60,40,20,0.45)',
          }}>{t('footer.legal.last_update')}</div>
        </div>
      </div>
      <style>{`
        @keyframes legalFadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes legalSlideIn { from { opacity: 0; transform: translateY(16px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
    </div>
  );
}

function Footer() {
  const t = window.useT();
  const titleRef = React.useRef(null);
  const subtitleRef = React.useRef(null);
  const [legalModal, setLegalModal] = React.useState(null);

  React.useEffect(() => {
    const fit = () => {
      const t = titleRef.current, s = subtitleRef.current;
      if (!t || !s) return;
      if (!window.matchMedia('(min-width: 769px)').matches) {
        t.style.letterSpacing = '0';
        return;
      }
      t.style.letterSpacing = '0';
      const target = s.getBoundingClientRect().width;
      const natural = t.getBoundingClientRect().width;
      const chars = t.textContent.length - 1;
      if (chars > 0 && target > natural) {
        t.style.letterSpacing = ((target - natural) / chars) + 'px';
      }
    };
    fit();
    window.addEventListener('resize', fit);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  const navigate = (id) => {
    if (id === 'top') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
  };

  const cols = [
    {
      title: t('footer.col.redes.title'),
      items: [
        ['Instagram', 'https://www.instagram.com/eidora.projects'],
        ['LinkedIn', 'https://www.linkedin.com/in/joaquin-prados-cordon/'],
        ['Facebook', 'https://www.facebook.com/profile.php?id=61589526479409'],
      ],
    },
    {
      title: t('footer.col.sistema.title'),
      items: [
        [t('footer.col.sistema.contenido'), null],
        [t('footer.col.sistema.branding'), null],
        [t('footer.col.sistema.publicidad'), null],
      ],
    },
    {
      title: t('footer.col.contacto.title'),
      items: [
        ['info@eidoraprojects.com', 'mailto:info@eidoraprojects.com'],
        ['+34 614 32 55 64', 'tel:+34614325564'],
        ['+34 687 05 25 35', 'tel:+34687052535'],
      ],
    },
  ];

  return (
    <footer className="footer-root" style={{
      background: 'var(--lr-tierra-900)', color: 'var(--lr-cal-blanca)',
      padding: '88px 56px 36px',
      borderTop: '1px solid rgba(243,238,231,0.22)',
    }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div className="footer-grid" style={{
          display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1.2fr', gap: 56,
          paddingBottom: 56, borderBottom: '1px solid rgba(243,238,231,0.18)',
          marginBottom: 28,
        }}>
          {/* Brand block */}
          <div>
            <a ref={titleRef} href="#" onClick={(e) => { e.preventDefault(); navigate('top'); }}
              aria-label={t('footer.brand.aria_label')}
              className="reveal"
              style={{
                fontFamily: 'var(--font-display)', fontWeight: 400,
                fontSize: 'clamp(40px, 10vw, 64px)',
                color: 'var(--lr-cal-blanca)', textDecoration: 'none',
                display: 'inline-block', marginBottom: 8,
                lineHeight: 1, whiteSpace: 'nowrap',
              }}>EIDORA</a>
            <div ref={subtitleRef} className="footer-brand-subtitle" style={{
              display: 'inline-block',
              fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 10,
              letterSpacing: '0.32em', textTransform: 'uppercase',
              color: 'var(--lr-arena-calida)',
              marginBottom: 28,
            }}>{t('footer.brand.subtitle')}</div>
            <p className="footer-brand-p" style={{
              fontFamily: 'var(--font-italic)', fontStyle: 'italic', fontWeight: 400,
              fontSize: 22, lineHeight: 1.4,
              color: 'rgba(243,238,231,0.82)', maxWidth: '34ch', margin: '0 0 28px',
            }}>
              {t('footer.brand.description')}
            </p>
          </div>

          {/* Three nav columns */}
          {cols.map((col, i) => (
            <div key={i}>
              <div style={{
                fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 10,
                letterSpacing: '0.32em', textTransform: 'uppercase',
                color: 'var(--lr-arena-calida)', marginBottom: 20,
                paddingBottom: 12,
                borderBottom: '1px solid rgba(243,238,231,0.18)',
              }}>{col.title}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {col.items.map(([label, target], j) => {
                  const baseStyle = {
                    fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.85,
                    color: 'rgba(243,238,231,0.82)',
                    textDecoration: 'none',
                    transition: 'color 200ms',
                  };
                  if (!target) {
                    return <li key={j} style={baseStyle}>{label}</li>;
                  }
                  if (target.startsWith('mailto:') || target.startsWith('tel:') || target.startsWith('http')) {
                    return (
                      <li key={j}>
                        <a href={target}
                          target={target.startsWith('http') ? '_blank' : undefined}
                          rel={target.startsWith('http') ? 'noopener noreferrer' : undefined}
                          className="footer-link"
                          style={baseStyle}
                          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--lr-cal-blanca)'}
                          onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(243,238,231,0.82)'}
                        >{label}</a>
                      </li>
                    );
                  }
                  return (
                    <li key={j}>
                      <a href={`#${target}`}
                        onClick={(e) => { e.preventDefault(); navigate(target); }}
                        className="footer-link"
                        style={baseStyle}
                        onMouseEnter={(e) => e.currentTarget.style.color = 'var(--lr-cal-blanca)'}
                        onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(243,238,231,0.82)'}
                      >{label}</a>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </div>

        {/* Bottom rule */}
        <div className="footer-bottom" style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: 'var(--font-ui)', fontWeight: 600, fontSize: 10,
          letterSpacing: '0.28em', textTransform: 'uppercase',
          color: 'rgba(243,238,231,0.55)',
          paddingTop: 24,
        }}>
          <span>{t('footer.bottom.copyright')}</span>
          <span className="footer-bottom-links" style={{ display: 'flex', gap: 28 }}>
            <button onClick={() => setLegalModal('aviso')} style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 0,
              fontFamily: 'inherit', fontWeight: 'inherit', fontSize: 'inherit',
              letterSpacing: 'inherit', textTransform: 'inherit',
              color: 'inherit',
            }}>{t('footer.bottom.legal_notice')}</button>
            <button onClick={() => setLegalModal('privacidad')} style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 0,
              fontFamily: 'inherit', fontWeight: 'inherit', fontSize: 'inherit',
              letterSpacing: 'inherit', textTransform: 'inherit',
              color: 'inherit',
            }}>{t('footer.bottom.privacy')}</button>
          </span>
        </div>
      </div>

      {legalModal && <LegalModal type={legalModal} onClose={() => setLegalModal(null)} />}

      <style>{`
        .footer-link {
          position: relative;
          border-bottom: 1px solid transparent;
          transition: border-bottom-color 160ms ease;
        }
        .footer-link:hover,
        .footer-link:focus {
          border-bottom-color: currentColor;
          outline: none;
        }
        @media (max-width: 767px) {
          .footer-root {
            padding: 64px 24px 28px !important;
          }
          .footer-brand-subtitle {
            display: block !important;
          }
          .footer-grid {
            grid-template-columns: repeat(2, 1fr) !important;
            gap: 32px !important;
          }
          .footer-bottom {
            flex-direction: column !important;
            align-items: flex-start !important;
            gap: 16px !important;
          }
          .footer-bottom-links {
            flex-wrap: wrap !important;
            gap: 14px !important;
          }
          .footer-grid a,
          .footer-grid li {
            overflow-wrap: anywhere !important;
          }
        }
        @media (max-width: 479px) {
          .footer-root {
            padding: 48px 16px 24px !important;
          }
          .footer-grid {
            grid-template-columns: 1fr !important;
            gap: 28px !important;
          }
          .footer-brand-p {
            font-size: clamp(16px, 4.4vw, 22px) !important;
          }
          .footer-bottom {
            letter-spacing: 0.16em !important;
            line-height: 1.6 !important;
          }
        }
      `}</style>
    </footer>
  );
}

window.Footer = Footer;
