// =============================================================================
// REGUELIN RE — Shared components
// Header, Footer, Logo, MobileNav, PropertyCard, MediaPlaceholder, Icons
// =============================================================================

const { useState, useEffect, useRef, useMemo } = React;

// Programmatic hash navigation -----------------------------------------------
function nav(to) {
  window.location.hash = to;
}
function useHashRoute() {
  const [hash, setHash] = useState(window.location.hash || '#/');
  useEffect(() => {
    const onChange = () => {
      setHash(window.location.hash || '#/');
      window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  return hash.replace(/^#/, '') || '/';
}

// Smart Link — uses hash routing -----
function Link({ to, children, className, style, ariaLabel, ...rest }) {
  const onClick = (e) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey) return;
    if (to.startsWith('http')) return;
    e.preventDefault();
    nav(to);
  };
  return (
    <a href={'#' + to} onClick={onClick} className={className} style={style} aria-label={ariaLabel} {...rest}>
      {children}
    </a>
  );
}

// Logo (clean, architectural — original mark, no recreation of brand wordmark)
function BrandSigil({ size = 30, color }) {
  // R-portal: a thin geometric initial built from rectangles + arc, original
  const c = color || 'var(--color-navy)';
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" aria-hidden="true">
      <rect x="6" y="6" width="48" height="48" fill="none" stroke={c} strokeWidth="1.2" />
      <line x1="18" y1="14" x2="18" y2="46" stroke={c} strokeWidth="1.2" />
      <line x1="18" y1="14" x2="34" y2="14" stroke={c} strokeWidth="1.2" />
      <path d="M34 14 a8 8 0 0 1 0 16 L18 30" fill="none" stroke={c} strokeWidth="1.2" />
      <line x1="28" y1="30" x2="42" y2="46" stroke={c} strokeWidth="1.2" />
      <line x1="6" y1="52" x2="54" y2="52" stroke="var(--color-champagne)" strokeWidth="1.2" />
    </svg>
  );
}

function BrandMark({ ariaLabel = 'Reguelin RE — início', variant = 'dark' }) {
  return (
    <Link to="/" className={'brand-mark brand-mark--img brand-mark--' + variant} ariaLabel={ariaLabel}>
      <img src="logo-horizontal.png" alt="Reguelin RE" className="brand-mark__img" />
    </Link>
  );
}

// Icons (outline, thin, architectural)
function Icon({ name, size = 16, color = 'currentColor' }) {
  const common = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true };
  switch (name) {
    case 'arrow':
      return (<svg {...common}><line x1="4" y1="12" x2="20" y2="12"/><polyline points="14 6 20 12 14 18"/></svg>);
    case 'whatsapp':
      return (<svg {...common}><path d="M3 21l2-6a8 8 0 1 1 4 4z"/><path d="M8.5 11.5c.5 2 2 3.5 4 4l1.5-1.5 2.5 1c-.5 1-1.5 1.5-3 1.5a6 6 0 0 1-6-6c0-1.5.5-2.5 1.5-3l1 2.5z" /></svg>);
    case 'close':
      return (<svg {...common}><line x1="5" y1="5" x2="19" y2="19"/><line x1="19" y1="5" x2="5" y2="19"/></svg>);
    case 'menu':
      return (<svg {...common}><line x1="3" y1="8" x2="21" y2="8"/><line x1="3" y1="16" x2="21" y2="16"/></svg>);
    case 'pin':
      return (<svg {...common}><path d="M12 21s-7-7.5-7-12a7 7 0 1 1 14 0c0 4.5-7 12-7 12z"/><circle cx="12" cy="9" r="2"/></svg>);
    case 'check':
      return (<svg {...common}><polyline points="4 12 10 18 20 6"/></svg>);
    case 'compass':
      return (<svg {...common}><circle cx="12" cy="12" r="9"/><polygon points="12 7 14 12 12 17 10 12" fill={color} stroke="none"/></svg>);
    case 'ruler':
      return (<svg {...common}><rect x="3" y="9" width="18" height="6"/><line x1="7" y1="9" x2="7" y2="12"/><line x1="11" y1="9" x2="11" y2="12"/><line x1="15" y1="9" x2="15" y2="12"/><line x1="19" y1="9" x2="19" y2="12"/></svg>);
    case 'plus':
      return (<svg {...common}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>);
    case 'chevron':
      return (<svg {...common}><polyline points="9 6 15 12 9 18"/></svg>);
    default: return null;
  }
}

// Media placeholder ---------------------------------------------------------
function MediaPlaceholder({ label, dark = false, aspect, style }) {
  return (
    <div className={'placeholder-img' + (dark ? ' placeholder-img--dark' : '')} style={{ aspectRatio: aspect, ...style }}>
      <span>{label}</span>
    </div>
  );
}

// Header --------------------------------------------------------------------
function Header({ route }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => { setMobileOpen(false); }, [route]);
  // navigation: Sobre · Serviços · Conteúdos · Contato — NO /imoveis link
  const items = [
    { to: '/', label: 'Home' },
    { to: '/sobre', label: 'Sobre' },
    { to: '/servicos', label: 'Serviços' },
    { to: '/imoveis', label: 'Portfólio' },
    { to: '/conteudos', label: 'Conteúdos' },
    { to: '/contato', label: 'Contato' },
  ];
  const isActive = (to) => route === to || route.startsWith(to + '/');
  return (
    <header className="site-header">
      <div className="container site-header__inner">
        <BrandMark />
        <nav className="primary-nav" aria-label="Navegação principal">
          {items.map((it) => (
            <Link key={it.to} to={it.to} className={isActive(it.to) ? 'is-active' : ''}>{it.label}</Link>
          ))}
        </nav>
        <a className="nav-cta" href={whatsappURL('Olá, gostaria de iniciar uma conversa preliminar com a equipe.')} target="_blank" rel="noopener">
          Iniciar uma conversa
        </a>
        <button className="menu-btn" aria-label="Abrir menu" onClick={() => setMobileOpen(true)}>
          <Icon name="menu" size={22} />
        </button>
      </div>
      {mobileOpen && (
        <div className="mobile-nav" role="dialog" aria-modal="true" aria-label="Menu de navegação">
          <div className="mobile-nav__head">
            <span style={{ fontFamily: 'var(--font-display)', color: 'var(--color-champagne)', letterSpacing: '0.22em', fontSize: 12, textTransform: 'uppercase' }}>Menu</span>
            <button className="mobile-nav__close" aria-label="Fechar menu" onClick={() => setMobileOpen(false)}><Icon name="close" size={22} /></button>
          </div>
          {items.map((it) => (
            <Link key={it.to} to={it.to}>{it.label}</Link>
          ))}
          <div style={{ marginTop: 32 }}>
            <a className="btn btn--gold" href={whatsappURL('Olá, gostaria de iniciar uma conversa.')} target="_blank" rel="noopener">
              Iniciar uma conversa <Icon name="arrow" size={14} />
            </a>
          </div>
        </div>
      )}
    </header>
  );
}

// Footer --------------------------------------------------------------------
function Footer() {
  return (
    <footer className="site-footer">
      <div className="pattern-diag">
        <div className="container">
          <div className="footer-grid">
            <div>
              <div style={{ marginBottom: 24 }}>
                <Link to="/" className="brand-mark brand-mark--img brand-mark--light" ariaLabel="Reguelin RE — início">
                  <img src="logo-horizontal.png" alt="Reguelin RE" className="brand-mark__img" />
                </Link>
              </div>
              <p className="footer-tagline">Assessoria imobiliária com diligência integral.</p>
            </div>
            <div>
              <h5>Navegação</h5>
              <Link to="/sobre">Sobre</Link>
              <Link to="/servicos">Serviços</Link>
              <Link to="/imoveis">Portfólio</Link>
              <Link to="/conteudos">Conteúdos</Link>
              <Link to="/contato">Contato</Link>
            </div>
            <div>
              <h5>Direto</h5>
              <a href={whatsappURL('Olá, gostaria de conversar.')} target="_blank" rel="noopener">WhatsApp</a>
              <Link to="/contato">Formulário</Link>
              <a href="mailto:contato@reguelin.com.br">contato@reguelin.com.br</a>
            </div>
            <div>
              <h5>Redes</h5>
              <a href="#" rel="noopener">LinkedIn</a>
              <a href="#" rel="noopener">Instagram</a>
            </div>
          </div>
          <div className="footer-bottom">
            <span>Creci-PR F57061 · Curitiba / PR</span>
            <span className="mono" style={{ opacity: .7 }}>© {new Date().getFullYear()} REGUELIN RE</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Property Card ------------------------------------------------------------
function PropertyCard({ property, variant = 'md', index }) {
  const cover = property.images.find(i => i.isCover) || property.images[0];
  const ddDone = property.dueDiligence.documentationStatus === 'completa';
  const cls = variant === 'lg' ? 'property-card property-card--lg' : variant === 'sm' ? 'property-card property-card--sm' : 'property-card property-card--md';
  const placeholderLabel = `Foto · ${typeLabel(property.type)} · ${property.neighborhood}`;
  return (
    <Link to={`/imoveis/${property.slug}`} className={cls}>
      <div className="property-card__media">
        <MediaPlaceholder label={placeholderLabel} />
        <div className="property-card__meta-top">
          <span className="tag-pill tag-pill--gold">
            {String(index ?? property.featuredOrder ?? 1).padStart(2,'0')} · {typeLabel(property.type)}
          </span>
          {property.status === 'reservado' && <span className="tag-pill">Em negociação</span>}
          {property.status === 'vendido' && <span className="tag-pill">Negociado</span>}
        </div>
      </div>
      <div className="property-card__body">
        <div className="property-card__title-block">
          <div className="property-card__locality">{property.neighborhood} · {property.city}</div>
          <h3 className="property-card__title">{property.title}</h3>
          <p className="property-card__sub">{property.subtitle}</p>
        </div>
        <div className="property-card__price">
          <span className="label">{property.priceLabel ? 'Condição' : 'Valor de referência'}</span>
          {fmtBRL(property.price, property.priceLabel)}
        </div>
      </div>
      <div className="property-card__specs">
        {property.areaTotal > 0 && <span><strong>{property.areaTotal.toLocaleString('pt-BR')} m²</strong>Área total</span>}
        {property.areaBuilt > 0 && <span><strong>{property.areaBuilt.toLocaleString('pt-BR')} m²</strong>Área construída</span>}
        {property.bedrooms > 0 && <span><strong>{property.bedrooms}</strong>Dormitórios</span>}
        {property.suites > 0 && <span><strong>{property.suites}</strong>Suítes</span>}
        {property.parkingSpots > 0 && <span><strong>{property.parkingSpots}</strong>Vagas</span>}
        <span style={{ marginLeft: 'auto', color: ddDone ? 'var(--color-champagne)' : 'var(--color-fossil-soft)' }}>
          <strong style={{ color: ddDone ? 'var(--color-champagne)' : 'var(--color-fossil)' }}>{ddStatusLabel(property.dueDiligence.documentationStatus)}</strong>
          Dossiê
        </span>
      </div>
    </Link>
  );
}

// Reveal-on-scroll wrapper — contained, respects reduced motion
function Reveal({ children, delay = 0, as = 'div', className, style }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const node = ref.current;
    if (!node) { setShown(true); return; }
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce || typeof IntersectionObserver === 'undefined') { setShown(true); return; }
    // Safety net: if IO never fires (e.g. iframe / virtual scroll), reveal after a short delay
    const fallback = setTimeout(() => setShown(true), 400);
    const io = new IntersectionObserver(entries => {
      entries.forEach(en => { if (en.isIntersecting) { setShown(true); io.disconnect(); clearTimeout(fallback); } });
    }, { threshold: 0.01, rootMargin: '0px 0px -5% 0px' });
    io.observe(node);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, []);
  const Tag = as;
  const baseStyle = {
    opacity: shown ? 1 : 0,
    transform: shown ? 'translateY(0)' : 'translateY(14px)',
    transition: `opacity 600ms cubic-bezier(0.22, 0.61, 0.36, 1) ${delay}ms, transform 600ms cubic-bezier(0.22, 0.61, 0.36, 1) ${delay}ms`,
  };
  return <Tag ref={ref} className={className} style={{ ...baseStyle, ...style }}>{children}</Tag>;
}

// Skip link
function SkipLink() {
  return (
    <a href="#main-content" style={{
      position: 'absolute', left: 16, top: 16,
      transform: 'translateY(-200%)',
      background: 'var(--color-navy)', color: 'var(--color-offwhite)',
      padding: '12px 16px', textDecoration: 'none',
      fontFamily: 'var(--font-body)', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
      zIndex: 9999, transition: 'transform 200ms ease',
    }} onFocus={(e)=>{ e.currentTarget.style.transform='translateY(0)';}}
    onBlur={(e)=>{ e.currentTarget.style.transform='translateY(-200%)';}}>
      Ir para o conteúdo
    </a>
  );
}

// Floating WhatsApp
function WhatsAppFloat({ message = 'Olá, gostaria de iniciar uma conversa.' }) {
  return (
    <a
      className="whatsapp-float"
      href={whatsappURL(message)}
      target="_blank"
      rel="noopener"
      aria-label="Conversar pelo WhatsApp"
      style={{
        position: 'fixed', right: 24, bottom: 24, zIndex: 40,
        width: 56, height: 56,
        background: 'var(--color-navy)',
        border: '1px solid var(--color-champagne)',
        color: 'var(--color-champagne)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        textDecoration: 'none',
        transition: 'background 200ms ease, color 200ms ease',
      }}
      onMouseEnter={(e)=>{ e.currentTarget.style.background='var(--color-champagne)'; e.currentTarget.style.color='var(--color-navy)'; }}
      onMouseLeave={(e)=>{ e.currentTarget.style.background='var(--color-navy)'; e.currentTarget.style.color='var(--color-champagne)'; }}
    >
      <Icon name="whatsapp" size={22} color="currentColor" />
    </a>
  );
}

Object.assign(window, {
  nav, useHashRoute, Link, BrandSigil, BrandMark, Icon, MediaPlaceholder,
  Header, Footer, PropertyCard, Reveal, SkipLink, WhatsAppFloat,
});
