// BRODNET — site completo com app, canais TV e adicionais
const { useState, useEffect, useRef } = React;
const { useSiteData } = window.BrodnetData;

function useWindowWidth() {
  const getWidth = () => (typeof window === 'undefined' ? 1280 : window.innerWidth);
  const [width, setWidth] = useState(getWidth);

  useEffect(() => {
    const onResize = () => setWidth(getWidth());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  return width;
}

function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    const obs = new IntersectionObserver(([e]) => {if (e.isIntersecting) {el.classList.add('in');obs.disconnect();}}, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}
const Reveal = ({ children, delay = 0, ...rest }) => {
  const ref = useReveal();
  return <div ref={ref} className="reveal" style={{ transitionDelay: `${delay}ms`, ...rest.style }}>{children}</div>;
};

const cleanText = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();
const money = (value) => Number(value || 0).toFixed(2);
const siteUrl = (data) => (data?.seo?.siteUrl || 'https://brodnet.com.br').replace(/\/+$/, '');
const SERVICE_ROUTES = {
  '/internet/': {
    section: 'internet',
    title: 'Internet fibra BrodNet | Planos de internet residencial',
    description: 'Planos de internet fibra BrodNet com ate 600 mega, Wi-Fi 5G gratis, instalacao rapida e suporte humano.',
  },
  '/tv/': {
    section: 'tv',
    title: 'TV por assinatura BrodNet | Pacotes Essencial e Full',
    description: 'TV BrodNet pela internet com pacotes Essencial e Full, mais de 45 ou 110 canais, TV Globo e canais adicionais.',
  },
  '/telefone-fixo/': {
    section: 'fone',
    title: 'Telefone fixo BrodNet | Planos de telefonia fixa',
    description: 'Planos de telefone fixo BrodNet com ligacoes ilimitadas para fixos do Brasil, identificador de chamadas e caixa postal.',
  },
  '/telefonia-4g-5g/': {
    section: 'movel',
    title: 'Telefonia 4G/5G BrodNet | Planos moveis com internet',
    description: 'Planos de telefonia movel BrodNet 4G/5G com internet, ligacoes ilimitadas, WhatsApp gratis e cobertura nacional.',
  },
  '/app/': {
    section: 'app',
    title: 'App do Assinante BrodNet | Segunda via, chamados e atendimento',
    description: 'Acesse o app do assinante BrodNet para segunda via de boleto, abertura de chamados tecnicos, atendimento e servicos online.',
  },
};

function getRoutePath() {
  const path = window.location.pathname.replace(/\/index\.html$/, '/');
  return path.endsWith('/') ? path : `${path}/`;
}

function getRouteConfig() {
  return SERVICE_ROUTES[getRoutePath()] || null;
}

function routeUrl(data, path) {
  return `${siteUrl(data)}${path === '/' ? '/' : path}`;
}

function assetUrl(value, data, absolute = false) {
  const raw = cleanText(value);
  if (!raw) return '';
  if (/^(https?:|data:|blob:)/i.test(raw)) return raw;
  const path = raw.startsWith('/') ? raw : `/${raw.replace(/^\/+/, '')}`;
  return absolute ? `${siteUrl(data)}${path}` : path;
}

function upsertMeta(selector, attrs) {
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement('meta');
    document.head.appendChild(el);
  }
  Object.entries(attrs).forEach(([key, value]) => el.setAttribute(key, value));
}

function upsertLink(rel, href) {
  let el = document.head.querySelector(`link[rel="${rel}"]`);
  if (!el) {
    el = document.createElement('link');
    el.setAttribute('rel', rel);
    document.head.appendChild(el);
  }
  el.setAttribute('href', href);
}

function structuredDataImage(data) {
  return assetUrl(
    data.seo?.image ||
    data.brand?.logoImage ||
    data.seo?.favicon ||
    '/favicon.svg',
    data,
    true
  );
}

function merchantOfferPolicy(data) {
  return {
    shippingDetails: {
      '@type': 'OfferShippingDetails',
      shippingDestination: {
        '@type': 'DefinedRegion',
        addressCountry: 'BR',
      },
      shippingRate: {
        '@type': 'MonetaryAmount',
        value: '0.00',
        currency: 'BRL',
      },
      deliveryTime: {
        '@type': 'ShippingDeliveryTime',
        handlingTime: {
          '@type': 'QuantitativeValue',
          minValue: 0,
          maxValue: 0,
          unitCode: 'DAY',
        },
        transitTime: {
          '@type': 'QuantitativeValue',
          minValue: 0,
          maxValue: 0,
          unitCode: 'DAY',
        },
      },
    },
    hasMerchantReturnPolicy: {
      '@type': 'MerchantReturnPolicy',
      applicableCountry: 'BR',
      returnPolicyCategory: 'https://schema.org/MerchantReturnNotPermitted',
    },
  };
}

function planProduct(plan, category, data, extra = {}) {
  const url = routeUrl(data, extra.path || '/');
  const description = cleanText(extra.description || plan.description || (plan.benefits || []).join(', '));
  const image = structuredDataImage(data);
  return {
    '@type': 'Product',
    name: cleanText(plan.name),
    category,
    brand: { '@type': 'Brand', name: data.brand?.name || 'BrodNet' },
    description,
    image,
    url,
    aggregateRating: {
      '@type': 'AggregateRating',
      ratingValue: '5',
      bestRating: '5',
      worstRating: '1',
      ratingCount: '1',
      reviewCount: '1',
    },
    review: {
      '@type': 'Review',
      author: {
        '@type': 'Organization',
        name: data.brand?.name || 'BrodNet',
      },
      reviewBody: description || `${cleanText(plan.name)} BrodNet com atendimento local e suporte humano.`,
      reviewRating: {
        '@type': 'Rating',
        ratingValue: '5',
        bestRating: '5',
        worstRating: '1',
      },
    },
    offers: {
      '@type': 'Offer',
      priceCurrency: 'BRL',
      price: money(plan.price),
      availability: 'https://schema.org/InStock',
      url,
      ...merchantOfferPolicy(data),
    },
  };
}

function buildStructuredData(data) {
  const base = siteUrl(data);
  const logo = assetUrl(data.brand?.logoImage || '/favicon.svg', data, true);
  const graph = [
    {
      '@type': ['Organization', 'LocalBusiness'],
      '@id': `${base}/#organization`,
      name: data.brand?.name || 'BrodNet',
      url: base,
      logo,
      telephone: data.contact?.phone,
      email: data.contact?.email,
      address: cleanText(data.contact?.address || 'BrodNet'),
      sameAs: [data.social?.instagram, data.social?.facebook, data.social?.youtube, data.social?.linkedin].filter(Boolean),
    },
    {
      '@type': 'WebSite',
      '@id': `${base}/#website`,
      url: base,
      name: data.brand?.name || 'BrodNet',
      description: data.seo?.description,
      publisher: { '@id': `${base}/#organization` },
    },
    {
      '@type': 'BreadcrumbList',
      itemListElement: [
        ['Inicio', `${base}/`],
        ['Internet', routeUrl(data, '/internet/')],
        ['TV', routeUrl(data, '/tv/')],
        ['Telefone Fixo', routeUrl(data, '/telefone-fixo/')],
        ['Telefonia 4G/5G', routeUrl(data, '/telefonia-4g-5g/')],
      ].map(([name, item], index) => ({ '@type': 'ListItem', position: index + 1, name, item })),
    },
    ...(data.plans || []).map(p => planProduct(p, 'Internet fibra', data, { path: '/internet/', description: `${p.speed} mega de internet fibra. ${(p.benefits || []).join(', ')}` })),
    ...(data.tvPlans || []).map(p => planProduct(p, 'TV por assinatura', data, { path: '/tv/', description: `${p.channelsLabel || ''} para assistir via internet. ${p.description || ''}` })),
    ...(data.phonePlans || []).map(p => planProduct(p, 'Telefonia fixa', data, { path: '/telefone-fixo/' })),
    ...(data.mobilePlans || []).map(p => planProduct(p, 'Telefonia 4G/5G', data, { path: '/telefonia-4g-5g/', description: `${p.data || 0}GB de internet movel. ${(p.benefits || []).join(', ')}` })),
  ];
  return { '@context': 'https://schema.org', '@graph': graph };
}

const SeoManager = ({ data }) => {
  useEffect(() => {
    const seo = data.seo || {};
    const base = siteUrl(data);
    const route = getRouteConfig();
    const title = route?.title || seo.title || `${data.brand?.name || 'BrodNet'} | Internet fibra, TV, telefone e 4G`;
    const description = route?.description || seo.description || 'Planos BrodNet com internet fibra, TV por assinatura, telefonia fixa e 4G.';
    const canonicalUrl = route ? routeUrl(data, getRoutePath()) : `${base}/`;
    const image = assetUrl(seo.image || data.brand?.logoImage || '/favicon.svg', data, true);
    const favicon = assetUrl(seo.favicon || '/favicon.svg', data);
    document.title = title;
    upsertMeta('meta[name="description"]', { name: 'description', content: description });
    upsertMeta('meta[name="keywords"]', { name: 'keywords', content: seo.keywords || '' });
    upsertMeta('meta[name="robots"]', { name: 'robots', content: seo.robots || 'index,follow' });
    upsertMeta('meta[property="og:title"]', { property: 'og:title', content: title });
    upsertMeta('meta[property="og:description"]', { property: 'og:description', content: description });
    upsertMeta('meta[property="og:type"]', { property: 'og:type', content: 'website' });
    upsertMeta('meta[property="og:url"]', { property: 'og:url', content: canonicalUrl });
    upsertMeta('meta[property="og:image"]', { property: 'og:image', content: image });
    upsertMeta('meta[name="twitter:card"]', { name: 'twitter:card', content: 'summary_large_image' });
    upsertLink('canonical', canonicalUrl);
    upsertLink('icon', favicon);

    let script = document.getElementById('brodnet-jsonld');
    if (!script) {
      script = document.createElement('script');
      script.type = 'application/ld+json';
      script.id = 'brodnet-jsonld';
      document.head.appendChild(script);
    }
    script.textContent = JSON.stringify(buildStructuredData(data));
  }, [data]);
  return null;
};

function loadGtag(measurementId) {
  if (!measurementId || !/^G-[A-Z0-9]+$/i.test(measurementId)) return false;
  window.dataLayer = window.dataLayer || [];
  window.gtag = window.gtag || function(){ window.dataLayer.push(arguments); };
  if (!document.getElementById('brodnet-gtag')) {
    const script = document.createElement('script');
    script.id = 'brodnet-gtag';
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`;
    document.head.appendChild(script);
  }
  window.gtag('js', new Date());
  window.gtag('config', measurementId, {
    page_title: document.title,
    page_location: window.location.href,
    send_page_view: true,
  });
  return true;
}

function trackEvent(name, params = {}) {
  if (typeof window.gtag === 'function') {
    window.gtag('event', name, {
      page_path: window.location.pathname + window.location.search + window.location.hash,
      ...params,
    });
  }
}

const AnalyticsManager = ({ data }) => {
  const analytics = data.analytics || {};
  const measurementId = cleanText(analytics.measurementId);

  useEffect(() => {
    if (!analytics.enabled || !measurementId) return;
    if (!loadGtag(measurementId)) return;
    window.brodnetTrack = trackEvent;
    const params = new URLSearchParams(window.location.search);
    trackEvent('traffic_source_detected', {
      event_category: 'acquisition',
      source_referrer: document.referrer || 'direct',
      utm_source: params.get('utm_source') || '',
      utm_medium: params.get('utm_medium') || '',
      utm_campaign: params.get('utm_campaign') || '',
    });
  }, [analytics.enabled, measurementId]);

  useEffect(() => {
    if (!analytics.enabled || !analytics.trackClicks) return;
    const onClick = (event) => {
      const target = event.target.closest?.('a, button, [role="button"]');
      if (!target) return;
      const section = target.closest('section[id]')?.id || target.getAttribute('href')?.replace('#', '') || 'global';
      const label = cleanText(target.getAttribute('aria-label') || target.innerText || target.title || target.href || target.type).slice(0, 120);
      trackEvent('site_click', {
        event_category: 'engagement',
        click_text: label,
        click_url: target.href || target.getAttribute('href') || '',
        section_id: section,
        element_tag: target.tagName.toLowerCase(),
      });
    };
    document.addEventListener('click', onClick, true);
    return () => document.removeEventListener('click', onClick, true);
  }, [analytics.enabled, analytics.trackClicks]);

  useEffect(() => {
    if (!analytics.enabled || !analytics.trackSections) return;
    const seen = new Set();
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting || seen.has(entry.target.id)) return;
        seen.add(entry.target.id);
        trackEvent('section_view', {
          event_category: 'engagement',
          section_id: entry.target.id,
          section_title: cleanText(entry.target.querySelector('h1,h2')?.innerText || entry.target.id).slice(0, 120),
        });
      });
    }, { threshold: 0.45 });
    document.querySelectorAll('section[id]').forEach(section => observer.observe(section));
    return () => observer.disconnect();
  }, [analytics.enabled, analytics.trackSections, data]);

  useEffect(() => {
    if (!analytics.enabled || !analytics.trackTime) return;
    const started = Date.now();
    const marks = [15, 30, 60, 120, 300];
    const timers = marks.map(seconds => setTimeout(() => {
      trackEvent('time_engaged', { event_category: 'engagement', seconds_engaged: seconds });
    }, seconds * 1000));
    const onLeave = () => {
      trackEvent('session_duration', {
        event_category: 'engagement',
        seconds_engaged: Math.round((Date.now() - started) / 1000),
      });
    };
    window.addEventListener('pagehide', onLeave);
    return () => {
      timers.forEach(clearTimeout);
      window.removeEventListener('pagehide', onLeave);
    };
  }, [analytics.enabled, analytics.trackTime]);

  return null;
};

const Marquee = ({ items, bg = 'var(--ink)', color = 'var(--yellow)', speed = 30 }) => {
  const content =
  <div style={{ display: 'flex', alignItems: 'center', gap: 40, padding: '0 20px', flexShrink: 0 }}>
      {items.map((t, i) =>
    <React.Fragment key={i}>
          <span className="display" style={{ fontSize: 'clamp(36px, 5.5vw, 72px)', whiteSpace: 'nowrap' }}>{t}</span>
          <span style={{ fontSize: 28, color: 'var(--red)' }}>★</span>
        </React.Fragment>
    )}
    </div>;

  return (
    <div style={{ background: bg, color, padding: '18px 0', overflow: 'hidden', borderTop: '3px solid var(--ink)', borderBottom: '3px solid var(--ink)' }}>
      <div style={{ display: 'flex', animation: `marquee ${speed}s linear infinite`, width: 'max-content' }}>{content}{content}</div>
    </div>);

};

// Logo visual BrodNet — usa imagem se configurada, senão SVG
const BrodnetLogo = ({ data, size = 44 }) => {
  const logoImg = assetUrl(data?.brand?.logoImage, data);
  if (logoImg) {
    return <img src={logoImg} alt={data?.brand?.logoText || 'BrodNet'} style={{ height: size, maxWidth: size * 5, objectFit: 'contain' }} />;
  }
  return (
    <svg width={size * 3.5} height={size} viewBox="0 0 220 60" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect width="60" height="60" rx="12" fill="#000080" />
      <circle cx="30" cy="44" r="4" fill="#ffbf00" />
      <path d="M20 36 a14 14 0 0 1 20 0" stroke="#ffbf00" strokeWidth="4" strokeLinecap="round" fill="none" />
      <path d="M12 27 a24 24 0 0 1 36 0" stroke="white" strokeWidth="3.5" strokeLinecap="round" fill="none" opacity="0.8" />
      <path d="M4 18 a34 34 0 0 1 52 0" stroke="white" strokeWidth="3" strokeLinecap="round" fill="none" opacity="0.35" />
      <text x="72" y="43" fontFamily="Arial Black, Archivo Black, sans-serif" fontWeight="900" fontSize="32" letterSpacing="-1" fill="#000080">BROD</text>
      <text x="150" y="43" fontFamily="Arial Black, Archivo Black, sans-serif" fontWeight="900" fontSize="32" letterSpacing="-1" fill="#990000">NET</text>
    </svg>);

};

// Upload de logo — só no modo edição
const LogoUpload = ({ data }) => {
  const ctx = window.BrodnetEdit?.useEdit?.();
  const ref = useRef(null);
  if (!ctx || !ctx.isEditMode) return null;
  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => ctx.updatePath('brand.logoImage', e.target.result);
    reader.readAsDataURL(file);
  };
  return (
    <div style={{ position: 'absolute', bottom: -36, left: 0, display: 'flex', gap: 6 }}>
      <input ref={ref} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => handleFile(e.target.files[0])} />
      <button onClick={() => ref.current.click()} style={{ background: 'var(--yellow)', color: 'var(--ink)', border: '2px solid var(--ink)', padding: '4px 10px', fontSize: 10, fontWeight: 800, cursor: 'pointer', fontFamily: 'JetBrains Mono, monospace' }}>
        📷 TROCAR LOGO
      </button>
      {data?.brand?.logoImage &&
      <button onClick={() => ctx.updatePath('brand.logoImage', '')} style={{ background: 'white', color: 'var(--red)', border: '2px solid var(--red)', padding: '4px 10px', fontSize: 10, fontWeight: 800, cursor: 'pointer' }}>✕</button>
      }
    </div>);

};

// Logo na nav — imagem se configurada, senão SVG
const NavLogo = ({ data }) => {
  const ctx = window.BrodnetEdit?.useEdit?.();
  const logoImg = assetUrl(data?.brand?.logoImage, data);
  const fileRef = useRef(null);
  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => ctx?.updatePath('brand.logoImage', e.target.result);
    reader.readAsDataURL(file);
  };
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
      <a href="/" style={{ textDecoration: 'none', display: 'flex', alignItems: 'center' }}>
        {logoImg
          ? <img src={logoImg} alt={data?.brand?.name || 'BrodNet'} style={{ height: 48, maxWidth: 220, objectFit: 'contain' }}/>
          : <BrodnetLogo data={data} size={44}/>
        }
      </a>
      {/* Botão trocar logo — só no modo edição */}
      {ctx?.isEditMode && (
        <div style={{ position: 'absolute', top: '100%', left: 0, zIndex: 200, display: 'flex', gap: 4, marginTop: 4 }}>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }}
            onChange={e => handleFile(e.target.files[0])}/>
          <button onClick={() => fileRef.current.click()} style={{
            background: 'var(--yellow)', color: 'var(--ink)', border: '2px solid var(--ink)',
            padding: '4px 10px', fontSize: 10, fontWeight: 800, cursor: 'pointer', whiteSpace: 'nowrap',
            fontFamily: 'JetBrains Mono, monospace',
          }}>📷 TROCAR LOGO</button>
          {logoImg && (
            <button onClick={() => ctx.updatePath('brand.logoImage', '')} style={{
              background: 'white', color: 'var(--red)', border: '2px solid var(--red)',
              padding: '4px 8px', fontSize: 10, fontWeight: 800, cursor: 'pointer',
            }}>✕</button>
          )}
        </div>
      )}
    </div>
  );
};

const Nav = ({ data }) => {
  const width = useWindowWidth();
  const compact = width < 1180;
  const iconOnly = width < 980;
  const mobile = width < 760;
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => { if (!mobile) setMenuOpen(false); }, [mobile]);
  const assinarHref = `https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`;
  const whatsIcon = <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.501-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347zM12.05 21.785h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884z" /></svg>;

  const navItems = [
  { href: '/internet/', label: 'Internet', icon: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M5 12.55a11 11 0 0 1 14.08 0" /><path d="M1.42 9a16 16 0 0 1 21.16 0" /><path d="M8.53 16.11a6 6 0 0 1 6.95 0" /><circle cx="12" cy="20" r="1" fill="currentColor" /></svg> },
  { href: '/tv/', label: 'TV', icon: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="2" y="5" width="20" height="13" rx="2" /><path d="M8 21h8M12 18v3" /></svg> },
  { href: '/telefone-fixo/', label: 'Telefone', icon: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.13 12a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 2.98 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 21 17z" /></svg> },
  { href: '/telefonia-4g-5g/', label: '4G/5G', icon: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="5" y="2" width="14" height="20" rx="2" /><path d="M12 18h.01" /><path d="M9 7h6" /></svg> },
  { href: '/app/', label: 'App', icon: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M12 2v6M12 16v6M2 12h6M16 12h6M4.93 4.93l4.24 4.24M14.83 14.83l4.24 4.24M4.93 19.07l4.24-4.24M14.83 9.17l4.24-4.24" /></svg> }];


  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      background: 'var(--blue)', borderBottom: '3px solid var(--ink)',
    }}>
      <div style={{
        maxWidth: 1400, margin: '0 auto', padding: mobile ? '0 14px' : '0 24px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: 72,
        gap: 12,
      }}>
        <NavLogo data={data}/>

        {mobile ? (
          /* Botão hambúrguer (mobile) */
          <button aria-label="Menu" onClick={() => setMenuOpen(o => !o)} style={{
            background: 'var(--red)', color: 'white', border: '3px solid var(--ink)', boxShadow: '3px 3px 0 var(--ink)',
            width: 46, height: 46, display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', flexShrink: 0, padding: 0,
          }}>
            {menuOpen
              ? <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              : <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>}
          </button>
        ) : (
          /* Nav desktop com ícones grandes */
          <nav style={{ display: 'flex', gap: 4, alignItems: 'center', minWidth: 0 }}>
            {navItems.map((item) => (
              <a key={item.href} href={item.href} style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                padding: compact ? '6px 10px' : '8px 16px', textDecoration: 'none', color: 'white',
                borderRadius: 10, transition: 'background 150ms',
                minWidth: iconOnly ? 40 : 64,
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.12)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span style={{ color: 'var(--yellow)' }}>{item.icon}</span>
                {!iconOnly && <span className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'white', whiteSpace: 'nowrap' }}>
                  {item.label.toUpperCase()}
                </span>}
              </a>
            ))}
            <a href={assinarHref} target="_blank" rel="noopener" style={{
              marginLeft: compact ? 4 : 12,
              background: 'var(--red)', color: 'white', textDecoration: 'none',
              padding: compact ? '12px 14px' : '14px 22px', fontWeight: 800, fontSize: compact ? 12 : 14,
              border: '3px solid var(--ink)', display: 'flex', alignItems: 'center', gap: 8,
              boxShadow: '4px 4px 0 var(--ink)', flexShrink: 0,
            }}>
              {whatsIcon}ASSINAR
            </a>
          </nav>
        )}
      </div>

      {/* Menu dropdown (mobile) */}
      {mobile && menuOpen && (
        <div style={{ background: 'var(--blue)', borderTop: '2px solid rgba(255,255,255,0.18)', borderBottom: '3px solid var(--ink)', padding: '6px 14px 16px' }}>
          {navItems.map((item) => (
            <a key={item.href} href={item.href} onClick={() => setMenuOpen(false)} style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: '14px 6px', textDecoration: 'none', color: 'white',
              borderBottom: '1px solid rgba(255,255,255,0.1)',
            }}>
              <span style={{ color: 'var(--yellow)', display: 'flex' }}>{item.icon}</span>
              <span className="mono" style={{ fontSize: 14, fontWeight: 700, letterSpacing: '0.08em' }}>{item.label.toUpperCase()}</span>
            </a>
          ))}
          <a href={assinarHref} target="_blank" rel="noopener" onClick={() => setMenuOpen(false)} style={{
            marginTop: 14, background: 'var(--red)', color: 'white', textDecoration: 'none',
            padding: '16px', fontWeight: 800, fontSize: 15, border: '3px solid var(--ink)', boxShadow: '4px 4px 0 var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          }}>
            {whatsIcon}ASSINAR AGORA
          </a>
        </div>
      )}
    </header>);

};


// ============================================================
// HERO ART SLIDE — banner desenhado em HTML (sem imagem, sem
// distorção; textos/preços editáveis pelo admin). Tipografia em
// vw para escalar proporcionalmente em qualquer largura.
// ============================================================
const HeroArtSlide = ({ slide }) => {
  const bg = slide.bg || '#0a0a14';
  const fg = slide.fg || '#fffaf0';
  const badgeBg = slide.badgeBg || '#ffbf00';
  const badgeFg = slide.badgeFg || '#0a0a14';
  const t1c = slide.title1Color || fg;
  const t2c = slide.title2Color || '#ffbf00';
  const stBg = slide.stickerBg || '#ffbf00';
  const stFg = slide.stickerFg || '#0a0a14';
  const stShadow = slide.stickerShadow || '#0a0a14';
  const tScale = slide.titleScale || 1;
  const hasPrice = slide.price !== undefined && slide.price !== null && slide.price !== '';
  const [pInt, pCents] = hasPrice ? Number(slide.price).toFixed(2).split('.') : ['', ''];
  const width = useWindowWidth();
  const isMobile = width < 700;
  const monoSm = { fontSize: isMobile ? 10 : 'clamp(9px,1.25vw,24px)', fontWeight: 700, letterSpacing: '0.12em' };
  return (
    <div style={{ position: 'absolute', inset: 0, background: bg, color: fg, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', borderRadius: '50%', width: '32vw', height: '32vw', right: '-9vw', top: '-12vw', background: t2c, opacity: 0.12 }}/>
      <div style={{ position: 'absolute', borderRadius: '50%', width: '16vw', height: '16vw', left: '54%', bottom: '-7vw', background: badgeBg, opacity: 0.12 }}/>
      {!isMobile && (
        <div className="mono" style={{ ...monoSm, position: 'absolute', top: 'clamp(10px,2.6vw,50px)', right: 'clamp(16px,6.2vw,120px)', color: t2c }}>★ BRODNET</div>
      )}
      <div style={{
        position: 'relative', display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        alignItems: isMobile ? 'flex-start' : 'center',
        justifyContent: 'center',
        gap: isMobile ? 12 : 'clamp(16px,4vw,80px)',
        padding: isMobile ? '18px 24px 34px' : '0 clamp(20px,6.2vw,120px)',
        height: '100%', boxSizing: 'border-box',
      }}>
        <div style={{ flex: isMobile ? 'none' : 1, minWidth: 0 }}>
          {slide.badge && (
            <div className="mono" style={{ ...monoSm, display: 'inline-block', background: badgeBg, color: badgeFg, padding: isMobile ? '3px 8px' : 'clamp(3px,0.5vw,10px) clamp(6px,1vw,20px)', marginBottom: isMobile ? 8 : 'clamp(8px,1.5vw,30px)' }}>{slide.badge}</div>
          )}
          <div className="display" style={{ fontSize: isMobile ? `clamp(22px, ${8 * tScale}vw, ${Math.round(34 * tScale)}px)` : `clamp(20px, ${5.9 * tScale}vw, ${Math.round(118 * tScale)}px)`, whiteSpace: 'nowrap' }}>
            <span style={{ color: t1c }}>{slide.title1}</span>
            {slide.title2 && (<React.Fragment><br/><span style={{ color: t2c }}>{slide.title2}</span></React.Fragment>)}
          </div>
          {slide.subtitle && (
            <div style={{ fontSize: isMobile ? 12 : 'clamp(11px,1.65vw,32px)', fontWeight: 700, marginTop: isMobile ? 8 : 'clamp(8px,1.25vw,24px)' }}>{slide.subtitle}</div>
          )}
          {slide.ctaEnabled && slide.ctaText && (
            <a
              href={slide.ctaLink || '#internet'}
              className="mono"
              style={{
                display: 'inline-block', textDecoration: 'none',
                background: slide.ctaBg || '#0a0a14',
                color: slide.ctaFg || '#fffaf0',
                border: `${isMobile ? '2px' : 'clamp(2px,0.26vw,5px)'} solid #0a0a14`,
                boxShadow: isMobile ? `4px 4px 0 ${slide.ctaShadow || badgeBg}` : `clamp(4px,0.62vw,12px) clamp(4px,0.62vw,12px) 0 ${slide.ctaShadow || badgeBg}`,
                fontWeight: 700, letterSpacing: '0.08em',
                fontSize: isMobile ? 11 : 'clamp(10px,1.3vw,26px)',
                padding: isMobile ? '9px 16px' : 'clamp(8px,1.35vw,26px) clamp(14px,2.4vw,46px)',
                marginTop: isMobile ? 14 : 'clamp(12px,1.9vw,36px)',
              }}
            >{slide.ctaText}</a>
          )}
        </div>
        {hasPrice && (
          <div style={{ flexShrink: 0, transform: isMobile ? 'rotate(-2deg)' : 'rotate(4deg)', alignSelf: isMobile ? 'flex-start' : 'center' }}>
            <div style={{
              background: stBg, color: stFg, textAlign: 'center',
              border: `${isMobile ? '2px' : 'clamp(2px,0.31vw,6px)'} solid ${stFg}`,
              boxShadow: isMobile ? `4px 4px 0 ${stShadow}` : `clamp(5px,0.83vw,16px) clamp(5px,0.83vw,16px) 0 ${stShadow}`,
              padding: isMobile ? '6px 14px' : 'clamp(10px,2.4vw,46px) clamp(12px,2.9vw,56px)',
              display: isMobile ? 'flex' : 'block', alignItems: 'baseline', gap: isMobile ? 8 : 0,
            }}>
              <div className="mono" style={{ ...monoSm, fontSize: isMobile ? 9 : monoSm.fontSize, letterSpacing: '0.1em' }}>{slide.priceLabel || 'A PARTIR DE'}</div>
              <div className="display" style={{ fontSize: isMobile ? 26 : 'clamp(22px,6.2vw,120px)', margin: '0.06em 0' }}>R${pInt}<span style={{ fontSize: '0.5em' }}>,{pCents}</span></div>
              <div className="mono" style={{ ...monoSm, fontSize: isMobile ? 9 : monoSm.fontSize, letterSpacing: '0.1em' }}>{slide.priceSuffix || 'POR MÊS'}</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ============================================================
// HERO SLIDER — full-screen, auto-play, transições configuráveis
// ============================================================
const Hero = ({ data }) => {
  const slides = (data.heroSlides && data.heroSlides.length)
    ? data.heroSlides
    : [{ id: 'main', image: data.images?.hero || '' }];

  const transition = data.heroTransition || 'fade';
  const intervalSec = data.heroInterval || 5;
  const width = useWindowWidth();

  // Proporção do banner: detecta automaticamente da imagem, usa heroAspect como fallback
  const configuredAspect = data.heroAspect || 35; // % configurado no admin
  const [naturalAspect, setNaturalAspect] = useState(null); // detectado da imagem
  const effectiveAspect = naturalAspect || configuredAspect;
  const heroMaxH = width < 768
    ? `${Math.min(effectiveAspect * 1.4, 72)}vw`
    : `min(${effectiveAspect}vw, calc(100vh - 72px))`;
  const heroMinH = width < 768 ? 220 : 320;

  // Detecta proporção da imagem do slide atual para ajustar altura
  const detectAspect = (src) => {
    if (!src) return;
    const img = new Image();
    img.onload = () => {
      if (img.naturalWidth && img.naturalHeight) {
        const ratio = (img.naturalHeight / img.naturalWidth) * 100;
        setNaturalAspect(Math.round(ratio * 10) / 10);
      }
    };
    img.src = src;
  };

  const [current, setCurrent] = useState(0);
  const [prev, setPrev] = useState(null);
  const [animDir, setAnimDir] = useState(1); // 1 = forward, -1 = backward
  const timerRef = useRef(null);

  const goTo = (i, dir = 1) => {
    if (i === current) return;
    setPrev(current);
    setAnimDir(dir);
    setCurrent(i);
    setTimeout(() => setPrev(null), 700);
  };

  const next = () => goTo((current + 1) % slides.length, 1);
  const goBack = () => goTo((current - 1 + slides.length) % slides.length, -1);

  useEffect(() => {
    if (slides.length < 2) return;
    clearInterval(timerRef.current);
    timerRef.current = setInterval(next, intervalSec * 1000);
    return () => clearInterval(timerRef.current);
  }, [current, slides.length, intervalSec]);

  // Detecta proporção do primeiro slide com imagem ao montar/trocar slides
  useEffect(() => {
    const firstWithImage = slides.find(s => s.image);
    if (firstWithImage) detectAspect(firstWithImage.image);
  }, [slides.map(s => s.image).join('|')]);

  // Gera estilos de transição por tipo
  const getStyle = (isCurrent, isPrev) => {
    const base = {
      position: 'absolute', inset: 0,
      width: '100%', height: '100%',
      objectFit: 'cover', objectPosition: 'center top',
    };
    if (transition === 'fade') return {
      ...base,
      opacity: isCurrent ? 1 : isPrev ? 0 : 0,
      transition: isCurrent || isPrev ? 'opacity 700ms ease-in-out' : 'none',
    };
    if (transition === 'slide') {
      const tx = isCurrent ? '0%' : isPrev ? `${-100 * animDir}%` : `${100 * animDir}%`;
      return {
        ...base,
        transform: `translateX(${tx})`,
        transition: isCurrent || isPrev ? 'transform 650ms cubic-bezier(.4,0,.2,1)' : 'none',
      };
    }
    if (transition === 'zoom') return {
      ...base,
      opacity: isCurrent ? 1 : isPrev ? 0 : 0,
      transform: isCurrent ? 'scale(1)' : isPrev ? 'scale(1.08)' : 'scale(0.95)',
      transition: isCurrent || isPrev ? 'opacity 700ms ease, transform 700ms ease' : 'none',
    };
    return { ...base, opacity: isCurrent ? 1 : 0 };
  };

  const slide = slides[current] || {};
  const hasImage = !!(slides.some(s => s.image || s.type === 'art'));

  return (
    <section id="top" style={{
      position: 'relative', overflow: 'hidden',
      height: heroMaxH, minHeight: heroMinH,
      width: '100%', marginTop: 72,
    }}>
      {/* Fundo fallback */}
      {!hasImage && (
        <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(135deg, var(--blue) 0%, #1a005e 55%, var(--red) 100%)` }}>
          <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0, opacity: 0.07 }}>
            <defs><pattern id="dots2" width="30" height="30" patternUnits="userSpaceOnUse"><circle cx="15" cy="15" r="2" fill="white"/></pattern></defs>
            <rect width="100%" height="100%" fill="url(#dots2)"/>
          </svg>
        </div>
      )}

      {/* Slides empilhados */}
      {slides.map((s, i) => {
        const isCurrent = i === current;
        const isPrev = i === prev;
        if (s.type === 'art') {
          return (
            <div key={s.id || i} style={getStyle(isCurrent, isPrev)}>
              <HeroArtSlide slide={s}/>
            </div>
          );
        }
        if (!s.image) return null;
        const imgStyle = getStyle(isCurrent, isPrev);
        return (
          <img key={s.id || i} src={s.image} alt={s.label || ''} style={imgStyle}/>
        );
      })}

      {/* Overlay */}
      {!hasImage && (
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.1)' }}/>
      )}

      {/* Upload (modo edição) */}
      <HeroBannerUpload data={data}/>

      {/* Dots de navegação */}
      {slides.length > 1 && (
        <div style={{
          position: 'absolute', bottom: 22, left: '50%', transform: 'translateX(-50%)',
          display: 'flex', gap: 8, zIndex: 10,
        }}>
          {slides.map((_, i) => (
            <button key={i} onClick={() => { clearInterval(timerRef.current); goTo(i, i > current ? 1 : -1); }} style={{
              width: i === current ? 28 : 10, height: 10, borderRadius: 100,
              border: '2px solid rgba(255,255,255,0.7)',
              background: i === current ? 'var(--yellow)' : 'transparent',
              cursor: 'pointer', padding: 0, transition: 'all 350ms ease',
            }}/>
          ))}
        </div>
      )}

      {/* Setas (ocultas no mobile — navegação pelos dots) */}
      {slides.length > 1 && width >= 700 && (<>
        <button onClick={() => { clearInterval(timerRef.current); goBack(); }} style={{
          position: 'absolute', left: 20, top: '50%', transform: 'translateY(-50%)', zIndex: 10,
          width: 44, height: 44, border: '2px solid rgba(255,255,255,0.5)',
          background: 'rgba(0,0,0,0.3)', color: 'white', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
        }}>←</button>
        <button onClick={() => { clearInterval(timerRef.current); next(); }} style={{
          position: 'absolute', right: 20, top: '50%', transform: 'translateY(-50%)', zIndex: 10,
          width: 44, height: 44, border: '2px solid rgba(255,255,255,0.5)',
          background: 'rgba(0,0,0,0.3)', color: 'white', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
        }}>→</button>
      </>)}
    </section>
  );
};

// Barra de CTAs abaixo do hero (quando há imagem de banner)
const HeroCtaBar = ({ data }) => {
  const hero = data.hero || {};
  const width = useWindowWidth();
  const isNarrow = width < 980;
  // Exibe a barra se qualquer slide tiver imagem ou for banner editável
  const hasImage = !!(data.heroSlides?.some(s => s.image || s.type === 'art') || data.images?.hero);
  if (!hasImage) return null;
  return (
    <div style={{
      background: 'var(--ink)', borderBottom: '3px solid var(--ink)',
      padding: '18px clamp(24px,5vw,60px)',
      display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
    }}>
      <EditableLink
        path="hero.ctaHref" label="Link — Botão principal (barra hero)"
        href={data.hero?.ctaHref || '#internet'} style={{
        background: 'var(--yellow)', color: 'var(--ink)', textDecoration: 'none',
        padding: '15px 28px', fontWeight: 800, fontSize: 16,
        border: '3px solid var(--bg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        boxShadow: '4px 4px 0 rgba(255,255,255,0.25)',
        minHeight: 56, whiteSpace: 'nowrap',
        flex: width < 560 ? '1 1 100%' : '0 0 auto',
      }}>
        {hero.ctaPrimary || 'VER OS PLANOS'} ↓
      </EditableLink>
      <EditableLink
        path="hero.ctaSecondaryHref" label="Link — Botão WhatsApp (hero)"
        href={data.hero?.ctaSecondaryHref || `https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#queroconectar')}`}
        target="_blank" rel="noopener" style={{
        background: '#25d366', color: 'white', textDecoration: 'none',
        padding: '14px 24px', fontWeight: 700, fontSize: 15,
        border: '2px solid rgba(255,255,255,0.3)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        minHeight: 56, whiteSpace: 'nowrap',
        flex: width < 560 ? '1 1 100%' : '0 0 auto',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.501-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347zM12.05 21.785h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884z"/></svg>
        WhatsApp
      </EditableLink>
      <div style={{ marginLeft: isNarrow ? 0 : 'auto', width: isNarrow ? '100%' : 'auto', display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {['✓ Instalação grátis', '✓ Wi-Fi 6', '✓ Suporte 24/7'].map((b, i) => (
          <span key={i} className="mono" style={{
            padding: '6px 12px', background: 'rgba(255,255,255,0.08)',
            border: '1px solid rgba(255,255,255,0.15)', fontSize: 11,
            color: 'rgba(255,255,255,0.85)', letterSpacing: '0.04em',
          }}>{b}</span>
        ))}
      </div>
    </div>
  );
};
const HeroBannerUpload = ({ data }) => {
  const ctx = window.BrodnetEdit?.useEdit?.();
  const fileRef = useRef(null);
  if (!ctx || !ctx.isEditMode) return null;
  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => ctx.updatePath('images.hero', e.target.result);
    reader.readAsDataURL(file);
  };
  return (
    <div style={{ marginTop: 20, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
      <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => handleFile(e.target.files[0])} />
      <button onClick={() => fileRef.current.click()} style={{
        background: 'var(--yellow)', color: 'var(--ink)', border: '2px solid var(--ink)',
        padding: '10px 18px', fontWeight: 800, fontSize: 13, cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 8
      }}>
        📸 TROCAR IMAGEM DO BANNER
      </button>
      {data.images?.hero &&
      <button onClick={() => ctx.updatePath('images.hero', '')} style={{
        background: 'rgba(255,255,255,0.15)', color: 'white', border: '2px solid rgba(255,255,255,0.4)',
        padding: '10px 18px', fontWeight: 700, fontSize: 13, cursor: 'pointer'
      }}>
          ✕ Remover imagem
        </button>
      }
    </div>);

};

// Banner promocional editável
const PromoBanner = ({ data }) => {
  const width = useWindowWidth();
  const isMobile = width < 720;
  const banners = (data.banners || []).filter((b) => b.enabled !== false);
  if (!banners.length) return null;
  return (
    <section style={{ padding: '32px clamp(16px,4vw,24px)', background: 'var(--bg)', borderTop: '3px solid var(--ink)' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {banners.map((b) =>
        <a key={b.id} href={`https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`} target="_blank" rel="noopener"
        style={{
          background: b.bgColor || 'var(--red)', color: b.fgColor || '#fff',
          border: '3px solid var(--ink)', boxShadow: isMobile ? '5px 5px 0 var(--ink)' : '8px 8px 0 var(--ink)',
          padding: isMobile ? '22px 20px' : '28px 32px', textDecoration: 'none',
          display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'auto 1fr auto', gap: isMobile ? 16 : 24, alignItems: 'center',
          transition: 'transform 200ms ease, box-shadow 200ms ease',
          position: 'relative', overflow: 'hidden'
        }}
        onMouseEnter={(e) => {e.currentTarget.style.transform = 'translate(-3px,-3px)';e.currentTarget.style.boxShadow = '11px 11px 0 var(--ink)';}}
        onMouseLeave={(e) => {e.currentTarget.style.transform = 'none';e.currentTarget.style.boxShadow = '8px 8px 0 var(--ink)';}}>

            {!isMobile && (
            <div style={{
            width: 64, height: 64, borderRadius: '50%', flexShrink: 0,
            background: b.accentColor || 'var(--yellow)', color: 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '3px solid var(--ink)', fontSize: 28
          }}>★</div>
            )}
            <div style={{ minWidth: 0 }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.85, marginBottom: 4 }}>
                ✦ OFERTA ESPECIAL ✦
              </div>
              <div className="display" style={{ fontSize: 'clamp(28px, 4vw, 48px)', lineHeight: 0.95 }}>
                {b.title}
              </div>
              <div style={{ marginTop: 8, fontSize: 16, fontWeight: 600, opacity: 0.95 }}>
                {b.subtitle}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: isMobile ? 'flex-start' : 'flex-end', gap: 12, minWidth: 0 }}>
              {b.price != null &&
            <div style={{ textAlign: isMobile ? 'left' : 'right' }}>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', opacity: 0.85 }}>{b.priceLabel || 'a partir de'}</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 2, color: b.accentColor || 'var(--yellow)' }}>
                    <span style={{ fontSize: 16, fontWeight: 800 }}>R$</span>
                    <span className="display" style={{ fontSize: 'clamp(36px, 5vw, 56px)' }}>{Math.floor(b.price)}</span>
                    <span className="display" style={{ fontSize: 22 }}>,{b.price.toFixed(2).split('.')[1]}</span>
                    <span style={{ fontSize: 13, opacity: 0.8, marginLeft: 4 }}>/mês</span>
                  </div>
                </div>
            }
              <span style={{
              background: b.accentColor || 'var(--yellow)', color: 'var(--ink)',
              padding: '12px 18px', fontWeight: 800, fontSize: 13,
              border: '3px solid var(--ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, whiteSpace: 'nowrap',
              width: isMobile ? '100%' : 'auto', boxSizing: 'border-box',
            }}>
                {b.cta || 'EU QUERO'} <span style={{ fontSize: 18 }}>↗</span>
              </span>
            </div>
          </a>
        )}
      </div>
    </section>);

};

// SEÇÃO APP
const AppSection = ({ data }) =>
<section id="app" style={{ padding: 'clamp(60px,9vw,100px) clamp(16px,4vw,24px)', background: 'var(--blue)', color: 'var(--bg)', borderTop: '3px solid var(--ink)', position: 'relative', overflow: 'hidden' }}>
    <div style={{ position: 'absolute', top: 60, right: '8%', fontSize: 60, color: 'var(--yellow)', animation: 'spin-slow 18s linear infinite', opacity: 0.5 }}>✦</div>
    <div style={{ maxWidth: 1400, margin: '0 auto', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 60, alignItems: 'center', position: 'relative' }}>
      <div>
        <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--yellow)', marginBottom: 16 }}>// 00 — APP OFICIAL</div>
        <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 84px)', margin: 0 }}>
          BRODNET<br />
          <span style={{ color: 'var(--yellow)', fontStyle: 'italic' }}>NA PALMA</span><br />
          DA SUA MÃO.
        </h2>
        <p style={{ marginTop: 24, fontSize: 16, lineHeight: 1.5, maxWidth: 480, opacity: 0.9 }}>
          {data.app?.description || ''}
        </p>
        <div style={{ marginTop: 32, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <a href={data.app?.iosUrl || '#'} target="_blank" rel="noopener" className="store-btn">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" /></svg>
            <span><span style={{ fontSize: 11, opacity: 0.8 }}>Baixe na</span><br /><span style={{ fontSize: 18, fontWeight: 800 }}>App Store</span></span>
          </a>
          <a href={data.app?.androidUrl || '#'} target="_blank" rel="noopener" className="store-btn">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M3 20.5V3.5c0-.32.06-.62.18-.89l9.94 9.94-9.94 9.94c-.12-.27-.18-.58-.18-.89zm10.66-7.71L4.07 22.45l11.36-6.55-1.77-3.11zm5.36-2.65L16.81 8.6l-2.04 2.05 2.83 2.83 2.42-1.39c.7-.36 1.04-1.18.66-1.95-.28-.41-.66-.66-1.04-.65zM4.07 1.55l9.59 9.66 1.77-3.11L4.07 1.55z" /></svg>
            <span><span style={{ fontSize: 11, opacity: 0.8 }}>Disponível no</span><br /><span style={{ fontSize: 18, fontWeight: 800 }}>Google Play</span></span>
          </a>
        </div>
        <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14 }}>
          <div>📄 <strong>Segunda via</strong> de boleto</div>
          <div>🔧 <strong>Abertura</strong> de chamados técnicos</div>
          <div>📊 <strong>Acompanhe</strong> sua conexão em tempo real</div>
        </div>
      </div>

      {/* Mockup celular */}
      <div style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}>
        <div style={{ position: 'relative', width: 280, height: 560, background: 'var(--ink)', borderRadius: 40, padding: 12, border: '4px solid var(--ink)', boxShadow: '12px 12px 0 var(--yellow)' }}>
          <div style={{ position: 'absolute', top: 18, left: '50%', transform: 'translateX(-50%)', width: 100, height: 22, background: 'var(--ink)', borderRadius: 16, zIndex: 2 }} />
          <div style={{ width: '100%', height: '100%', background: 'linear-gradient(160deg, var(--bg) 0%, var(--yellow) 100%)', borderRadius: 28, padding: '50px 20px 20px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            <div className="display" style={{ fontSize: 32, color: 'var(--ink)', lineHeight: 0.9, marginTop: 16 }}>OLÁ,<br />CLIENTE</div>
            <div style={{ marginTop: 20, padding: 16, background: 'var(--ink)', color: 'var(--bg)', borderRadius: 12 }}>
              <div className="mono" style={{ fontSize: 10, opacity: 0.7 }}>SEU PLANO</div>
              <div className="display" style={{ fontSize: 28, color: 'var(--yellow)' }}>BROD 200</div>
              <div style={{ fontSize: 12, marginTop: 4 }}>200 Mbps · próximo vencimento em 5 dias</div>
            </div>
            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <div style={{ background: 'white', padding: 12, borderRadius: 10, border: '2px solid var(--ink)' }}>
                <div style={{ fontSize: 22 }}>📄</div>
                <div className="mono" style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink)', marginTop: 4 }}>2ª VIA</div>
              </div>
              <div style={{ background: 'var(--red)', color: 'white', padding: 12, borderRadius: 10, border: '2px solid var(--ink)' }}>
                <div style={{ fontSize: 22 }}>🔧</div>
                <div className="mono" style={{ fontSize: 10, fontWeight: 700, marginTop: 4 }}>SUPORTE</div>
              </div>
              <div style={{ background: 'white', padding: 12, borderRadius: 10, border: '2px solid var(--ink)' }}>
                <div style={{ fontSize: 22 }}>📡</div>
                <div className="mono" style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink)', marginTop: 4 }}>STATUS</div>
              </div>
              <div style={{ background: 'white', padding: 12, borderRadius: 10, border: '2px solid var(--ink)' }}>
                <div style={{ fontSize: 22 }}>💬</div>
                <div className="mono" style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink)', marginTop: 4 }}>CHAT</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>;


// PLANOS internet
const PlansCategory = ({ id, number, sectionTitle, sectionAccent, plans, label, getValue, getUnit, bgColor, fgColor, accentColor, data }) => {
  const width = useWindowWidth();
  if (!plans || !plans.length) return null;
  // Colunas responsivas: 1 no celular, 2 no tablet, todas no desktop
  const cols = width < 720 ? 1 : width < 1080 ? Math.min(2, plans.length) : plans.length;
  const stacked = cols === 1;
  return (
    <section id={id} style={{ padding: 'clamp(60px,9vw,100px) clamp(16px,4vw,24px)', background: bgColor, color: fgColor, borderTop: '3px solid var(--ink)' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: accentColor, marginBottom: 16 }}>// {number} — {label}</div>
        <h2 className="display" style={{ fontSize: 'clamp(48px, 9vw, 120px)', margin: 0, color: fgColor }}>
          {sectionTitle}<br />
          <span style={{ color: accentColor, fontStyle: 'italic' }}>{sectionAccent}</span>
        </h2>
        <div style={{ marginTop: 48, display: 'grid', gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap: 0, border: '3px solid var(--ink)', overflow: 'visible' }}>
          {plans.map((plan, i) =>
          <Reveal key={plan.id} delay={i * 100}>
              <PlanCard plan={plan} data={data} index={i} isLast={i === plans.length - 1}
                lastInRow={(i + 1) % cols === 0 || i === plans.length - 1}
                stacked={stacked} getValue={getValue} getUnit={getUnit} />
            </Reveal>
          )}
        </div>
      </div>
    </section>);

};

// Ícones de plano por índice
const planIcons = [
// Básico — roteador
<svg key="0" width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="14" width="20" height="7" rx="2" /><path d="M6 14v-3a6 6 0 0 1 12 0v3" /><circle cx="12" cy="18" r="1" fill="currentColor" /><path d="M8 10.5a6 6 0 0 1 8 0" /></svg>,
// Família — casa+wifi
<svg key="1" width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /><path d="M9 21V12h6v9" /><path d="M8.5 7a5 5 0 0 1 7 0" /><path d="M10.5 9a2 2 0 0 1 3 0" /></svg>,
// Ultra — raio
<svg key="2" width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>];


// Paletas fixas por índice (sem depender de hover/estado)
const cardSchemes = [
{ bg: '#00007c', fg: '#ffffff', accent: '#ffbf00', btn: '#ffbf00', btnFg: '#00007c' }, // azul escuro
{ bg: '#ffbf00', fg: '#0a0a14', accent: '#990000', btn: '#0a0a14', btnFg: '#ffbf00' }, // amarelo (destaque)
{ bg: '#990000', fg: '#ffffff', accent: '#ffbf00', btn: '#ffbf00', btnFg: '#990000' }, // vermelho escuro
{ bg: '#0a0a14', fg: '#ffffff', accent: '#ffbf00', btn: '#ffbf00', btnFg: '#0a0a14' }, // preto (4º plano)
{ bg: '#00007c', fg: '#ffffff', accent: '#ffbf00', btn: '#ffbf00', btnFg: '#00007c' },
{ bg: '#990000', fg: '#ffffff', accent: '#ffbf00', btn: '#ffbf00', btnFg: '#990000' }];


const PlanCard = ({ plan, data, index, isLast, lastInRow, stacked, getValue, getUnit }) => {
  const scheme = plan.highlight ?
  cardSchemes[1] // sempre amarelo quando destacado
  : cardSchemes[index % cardSchemes.length === 1 ? index + 2 : index % cardSchemes.length];
  const icon = planIcons[index % planIcons.length];

  return (
    <div style={{
      padding: stacked ? '32px 22px' : '36px 28px', position: 'relative', minHeight: stacked ? 0 : 560,
      borderRight: !stacked && !lastInRow ? '3px solid var(--ink)' : 'none',
      borderBottom: stacked && !isLast ? '3px solid var(--ink)' : 'none',
      background: scheme.bg, color: scheme.fg,
      display: 'flex', flexDirection: 'column',
      marginTop: !stacked && plan.highlight ? -20 : 0,
      boxShadow: !stacked && plan.highlight ? '0 -8px 0 var(--ink), 0 8px 0 var(--ink)' : 'none',
      zIndex: plan.highlight ? 2 : 1
    }}>
      {plan.highlight &&
      <div style={{
        position: 'absolute', top: -18, left: '50%', transform: 'translateX(-50%)',
        background: '#990000', color: 'white', padding: '7px 18px',
        fontWeight: 800, fontSize: 11, letterSpacing: '0.12em',
        border: '3px solid var(--ink)', whiteSpace: 'nowrap',
        fontFamily: 'JetBrains Mono, monospace', zIndex: 3
      }}>
          ★ MAIS POPULAR
        </div>
      }

      {/* Ícone */}
      <div style={{
        width: 72, height: 72, borderRadius: 16,
        background: `${scheme.accent}22`,
        border: `2px solid ${scheme.accent}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: scheme.accent, marginBottom: 20
      }}>
        {React.cloneElement(icon, { width: 36, height: 36 })}
      </div>

      <div className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', opacity: 0.75 }}>
        PLANO 0{index + 1}
      </div>
      <div className="display" style={{ fontSize: 'clamp(22px, 2.5vw, 32px)', marginTop: 6, lineHeight: 1 }}>
        {plan.name.toUpperCase()}
      </div>

      {/* Velocidade / valor principal — fonte menor para valores longos (ex.: "Ilimitado") */}
      <div style={{ marginTop: 20, display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' }}>
        <span className="display" style={{
          fontSize: String(getValue(plan)).length > 4
            ? 'clamp(34px, 9vw, 56px)'
            : (stacked ? 'clamp(56px, 16vw, 100px)' : 'clamp(72px, 8vw, 100px)'),
          color: scheme.accent, lineHeight: 1, overflowWrap: 'anywhere',
        }}>
          {getValue(plan)}
        </span>
        <span className="display" style={{ fontSize: 22, opacity: 0.8, lineHeight: 1 }}>
          {getUnit(plan)}
        </span>
      </div>

      {/* Benefícios */}
      <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0 0', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        {(plan.benefits || []).slice(0, 4).map((b, bi) =>
        <li key={bi} style={{ display: 'flex', gap: 10, fontSize: 14, alignItems: 'flex-start' }}>
            <span style={{ color: scheme.accent, fontWeight: 900, flexShrink: 0, marginTop: 1 }}>✓</span>
            <span style={{ opacity: 0.9 }}>{b}</span>
          </li>
        )}
      </ul>

      {/* Preço + CTA */}
      <div style={{ marginTop: 24, paddingTop: 20, borderTop: `2px solid ${scheme.accent}44` }}>
        <div className="mono" style={{ fontSize: 11, opacity: 0.7, marginBottom: 4 }}>POR APENAS</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
          <span style={{ fontSize: 16, fontWeight: 700 }}>R$</span>
          <span className="display" style={{ fontSize: 'clamp(44px, 5vw, 60px)', lineHeight: 1 }}>
            {Math.floor(plan.price)}
          </span>
          <span className="display" style={{ fontSize: 24, lineHeight: 1 }}>
            ,{plan.price.toFixed(2).split('.')[1]}
          </span>
          <span style={{ fontSize: 13, opacity: 0.7, marginLeft: 4 }}>/mês</span>
        </div>
        <EditableLink
        path={`plans[${index}].ctaUrl`} label={`Link — ${plan.name}`}
        href={plan.ctaUrl || `https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`}
        target="_blank" rel="noopener" style={{
          marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: scheme.btn, color: scheme.btnFg,
          padding: '16px 20px', textDecoration: 'none', fontWeight: 800, fontSize: 15,
          border: '2px solid var(--ink)'
        }}>
          ASSINE AGORA <span style={{ fontSize: 22 }}>↗</span>
        </EditableLink>
      </div>
    </div>);

};

// Logos locais — pasta logos_canais/ na raiz do projeto
const LOCAL = '/logos_canais/';
const CHANNEL_LOGOS = {
  'Cultura': LOCAL+'tvcultura.jpg', 'SBT': LOCAL+'sbt.jpg', 'TV Globo': LOCAL+'globominashd.jpg',
  'Record': LOCAL+'recordtv.jpg', 'TV Brasil': LOCAL+'tvbrasil.jpg', 'RedeTV': LOCAL+'redetv.jpg',
  'TV Gazeta': LOCAL+'tvgazeta.jpg', 'Band': LOCAL+'band.jpg', 'Zapping Mix': LOCAL+'zpmix1br.jpg',
  'X Sports': LOCAL+'xsportsbr.jpg', 'GE TV': LOCAL+'getvbr.jpg', 'Futura': LOCAL+'futura.jpg',
  'RBTV': LOCAL+'rbtv.jpg', 'Central TV': LOCAL+'centraltv.jpg', 'RF TV': LOCAL+'redefamilia.jpg',
  'PIX TV': LOCAL+'pixtvbr.jpg', 'SescTV': LOCAL+'sesctv.jpg', 'Play TV': LOCAL+'playtv.jpg',
  'Canal GOV': LOCAL+'canalgov.jpg', 'TV Justiça': LOCAL+'tvjusticia.jpg', 'TV Senado': LOCAL+'tvsenadobr.jpg',
  'TV Câmara': LOCAL+'tvcamarabr.jpg', 'Canal Educação': LOCAL+'canaleducacao.jpg',
  'Canal do Boi': LOCAL+'canaldoboi.jpg', 'Solo Fértil': LOCAL+'canalsolofertil.jpg',
  'Agroplus': LOCAL+'agroplusbr.jpg', 'Agro Canal': LOCAL+'agrocanal.jpg',
  'TV Aparecida': LOCAL+'tvaparecida.jpg', 'TV Evangelizar': LOCAL+'tvevangelizar.jpg',
  'Canção Nova': LOCAL+'cancaonova.jpg', 'TV Pai Eterno': LOCAL+'tvpaieterno.jpg',
  'Rede Gospel': LOCAL+'redegospel.jpg', 'Mais Família': LOCAL+'redemaisfamilia.jpg',
  'Rede CNT': LOCAL+'cnt.jpg', 'Novo Tempo': LOCAL+'redenovotempo.jpg',
  'Boa Vontade': LOCAL+'boavontadetv.jpg', 'RIT TV': LOCAL+'rittv.jpg',
  'Rede Vida': LOCAL+'redevidabr.jpg', 'Século 21': LOCAL+'redeseculo21.jpg',
  'Daystar': LOCAL+'daystarengbr.jpg',
  'Music Urban': LOCAL+'music-urbanbrasil.jpg', 'Music MPB': LOCAL+'music-mpb.jpg',
  'Music Hits': LOCAL+'music-hits.jpg', 'Music Rock': LOCAL+'music-rock.jpg',
  'Music Sertanejo': LOCAL+'music-sertanejo.jpg', 'Music Samba': LOCAL+'music-samba.jpg',
  // Full extras
  'Zapping Mix Esportes': LOCAL+'zpmixesportes1br.jpg', 'BandSports': LOCAL+'bandsports.jpg',
  'SportyNet': LOCAL+'nossofutebolbr.jpg', 'NSports': LOCAL+'nsportsbr.jpg',
  'ESPN': LOCAL+'espn.jpg', 'ESPN 2': LOCAL+'espn2br.jpg', 'ESPN 3': LOCAL+'espn3br.jpg',
  'ESPN 6': LOCAL+'espn-6.jpg', 'SPORTV 3': LOCAL+'spor3.jpg', 'SPORTV 2': LOCAL+'spor2.jpg',
  'SPORTV': LOCAL+'sporhd.jpg', 'Mix News': LOCAL+'zpmixnews1br.jpg',
  'Globo News': LOCAL+'globonews.jpg', 'CNN Brasil': LOCAL+'cnnbrasil.jpg',
  'Record News': LOCAL+'recordnews.jpg', 'Band News': LOCAL+'bandnews.jpg',
  'Jovem Pan News': LOCAL+'jpnews.jpg', 'BM&C News': LOCAL+'bmcnews.jpg',
  'FOX News': LOCAL+'foxnews.jpg', 'BBC News': LOCAL+'bbcnews.jpg',
  'Times Brasil': LOCAL+'cnbcbr.jpg', 'CNN Money': LOCAL+'cnnmoneybr.jpg',
  'Investigação Discovery': LOCAL+'idbr.jpg', 'Discovery Turbo': LOCAL+'turbobr.jpg',
  'Discovery Science': LOCAL+'discoverysciencebr.jpg', 'Discovery Channel': LOCAL+'discoverybr.jpg',
  'Animal Planet': LOCAL+'animalplanetbr.jpg', 'Discovery Theater': LOCAL+'discoverytheaterbr.jpg',
  'Discovery World': LOCAL+'discoveryworldbr.jpg', 'Modo Viagem': LOCAL+'modoviagem.jpg',
  'Canal OFF': LOCAL+'off.jpg', 'Arte 1': LOCAL+'arte1.jpg', 'UOL': LOCAL+'canaluolbr.jpg',
  'Multishow': LOCAL+'multishow.jpg', 'BIS': LOCAL+'bis.jpg', 'GNT': LOCAL+'gnt.jpg',
  'Globoplay Novelas': LOCAL+'viva.jpg', 'TLC': LOCAL+'tlcbr.jpg',
  'Home & Health': LOCAL+'homeandhealthbr.jpg', 'Food Network': LOCAL+'foodnetworkbr.jpg',
  'HGTV': LOCAL+'hgtvbr.jpg', 'Sabor & Arte': LOCAL+'saboreartebr.jpg',
  'Gloob': LOCAL+'gloob.jpg', 'Gloobinho': LOCAL+'gloobinho.jpg',
  'Discovery Kids': LOCAL+'discoverykidsbr.jpg', 'Megapix': LOCAL+'megapix.jpg',
  'Universal TV': LOCAL+'ucbr.jpg', 'USA Network': LOCAL+'syfybr.jpg',
  'Studio Universal': LOCAL+'sucbr.jpg', 'Canal Brasil': LOCAL+'canalbrasil.jpg',
  'AMC': LOCAL+'amcbr.jpg', 'Film&Arts': LOCAL+'filmandartsbr.jpg',
  'DW Español': LOCAL+'dwe.jpg', 'RAI Italia': LOCAL+'raiitalia.jpg',
  'TV5Monde': LOCAL+'tv5monde.jpg', 'NHK World': LOCAL+'nhk.jpg',
  'France 24': LOCAL+'france24frbr.jpg', 'Terra Viva': LOCAL+'terraviva.jpg',
  'C3TV': LOCAL+'tvclimatempo.jpg', 'Agro Mais': LOCAL+'agromais.jpg',
};
// ============================================================
const TV_FEATURES_CONFIG = [
  {
    id: 'turbo',
    title: 'MODO TURBO',
    description: 'Com o <strong>Modo Turbo</strong> você recebe o sinal primeiro, grite gol antes do seu vizinho!',
    videoSrc: '/features-carousel-slides/BarraLight.webm?v=20260614-tv-fixes1',
    bg: 'var(--yellow)', fg: 'var(--ink)',
  },
  {
    id: 'replay',
    title: 'REPLAY',
    description: 'Assista novamente os melhores lances com <strong>Replay</strong>.',
    videoSrc: '/features-carousel-slides/ReplayLight.webm?v=20260614-tv-fixes1',
    bg: 'var(--red)', fg: 'var(--bg)',
  },
  {
    id: 'esportes',
    title: 'MODO ESPORTES',
    description: 'O <strong>Modo Esportes</strong> deixa sua experiência mais imersiva e vibrante.',
    videoSrc: '/features-carousel-slides/MomentosLight.webm?v=20260614-tv-fixes1',
    bg: 'var(--blue)', fg: 'var(--bg)',
  },
  {
    id: 'momentos',
    title: 'MOMENTOS',
    description: 'Reviva os melhores <strong>Momentos</strong> sempre que quiser.',
    videoSrc: '/features-carousel-slides/ReplayLight%20(1).webm?v=20260614-tv-fixes1',
    bg: 'var(--bg)', fg: 'var(--ink)',
  },
];

const TvFeaturesPlayer = ({ data }) => {
  const width = useWindowWidth();
  const isNarrow = width < 980;
  const features = (data.tvFeatures && data.tvFeatures.length)
    ? data.tvFeatures.map((f, i) => ({ ...TV_FEATURES_CONFIG[i % TV_FEATURES_CONFIG.length], ...f }))
    : TV_FEATURES_CONFIG;

  const [active, setActive] = useState(features[0]);
  const videoRef = useRef(null);
  const containerRef = useRef(null);

  const selectFeature = (f) => {
    setActive(f);
  };

  useEffect(() => {
    if (!videoRef.current || !active) return;
    const vid = videoRef.current;
    vid.src = active.videoSrc;
    vid.load();
    vid.play().catch(() => {});

    const onEnded = () => {
      const idx = features.findIndex(f => f.id === active.id);
      const next = features[(idx + 1) % features.length];
      selectFeature(next);
    };
    vid.addEventListener('ended', onEnded);
    return () => vid.removeEventListener('ended', onEnded);
  }, [active]);

  return (
    <div style={{ marginTop: 40 }}>
      {/* Cards clicáveis */}
      <div style={{ display: 'grid', gridTemplateColumns: isNarrow ? 'repeat(2, minmax(0, 1fr))' : 'repeat(4, 1fr)', gap: 0, border: '3px solid var(--ink)' }}>
        {features.map((f, i) => {
          const isActive = active?.id === f.id;
          const hasRightBorder = isNarrow ? i % 2 === 0 : i < features.length - 1;
          const hasBottomBorder = isNarrow ? i < features.length - 2 : false;
          return (
            <button key={f.id} onClick={() => selectFeature(f)} style={{
              padding: '22px 20px', border: 'none',
              borderRight: hasRightBorder ? '3px solid var(--ink)' : 'none',
              borderBottom: hasBottomBorder ? '3px solid var(--ink)' : 'none',
              background: isActive ? 'var(--ink)' : f.bg,
              color: isActive ? 'var(--yellow)' : f.fg,
              textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
              transition: 'all 200ms ease',
              position: 'relative',
              minHeight: 156,
              display: 'flex',
              flexDirection: 'column',
            }}>
              {isActive && !isNarrow && (
                <div style={{
                  position: 'absolute', bottom: -3, left: '50%', transform: 'translateX(-50%)',
                  width: 0, height: 0,
                  borderLeft: '12px solid transparent',
                  borderRight: '12px solid transparent',
                  borderTop: '12px solid var(--ink)',
                  zIndex: 2,
                }}/>
              )}
              <div className="mono" style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.1em', marginBottom: 8 }}>
                0{i + 1}
              </div>
              <div className="display" style={{ fontSize: 'clamp(18px, 2vw, 26px)', lineHeight: 1 }}>
                {f.title}
              </div>
              <p style={{ margin: '10px 0 0', fontSize: 13, lineHeight: 1.4, opacity: 0.9 }}>
                {f.description.replace(/<[^>]+>/g, '')}
              </p>
            </button>
          );
        })}
      </div>

      {/* Player de vídeo */}
      {active && (
        <div ref={containerRef} style={{
          background: '#000', border: '3px solid var(--ink)', borderTop: 'none',
          position: 'relative',
        }}>
          {/* Sem tab bar redundante — navegação só pelos cards acima */}

          {/* Vídeo */}
          <div style={{ position: 'relative', background: '#000' }}>
            <video
              ref={videoRef}
              autoPlay muted playsInline
              style={{ width: '100%', display: 'block', maxHeight: '62vh', objectFit: 'contain', background: '#000' }}
            />
          </div>

          {/* Descrição */}
          <div style={{
            padding: '20px 24px', background: '#000', color: 'white',
            textAlign: 'center', fontSize: isNarrow ? 16 : 20, lineHeight: 1.4,
          }}
            dangerouslySetInnerHTML={{ __html: active.description }}
          />
        </div>
      )}
    </div>
  );
};

// TV — com canais e modal
const TvSection = ({ data }) => {
  const [openPlan, setOpenPlan] = useState(null);
  return (
    <section id="tv" style={{ padding: 'clamp(60px,9vw,100px) clamp(16px,4vw,24px)', background: 'var(--ink)', color: 'var(--bg)', borderTop: '3px solid var(--ink)' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--yellow)', marginBottom: 16 }}>// 02 — TV POR ASSINATURA</div>
        <h2 className="display" style={{ fontSize: 'clamp(40px, 8vw, 110px)', margin: 0, color: 'var(--bg)' }}>
          A TV DO <span style={{ color: 'var(--red)', fontStyle: 'italic' }}>FUTURO</span><br />
          É PELA INTERNET.
        </h2>
        <p style={{ marginTop: 16, fontSize: 16, maxWidth: 600, opacity: 0.75, color: 'var(--bg)' }}>
          Sem antenas, sem decodificadores. Smart TV, celular ou tablet — onde e quando quiser.
        </p>

        {/* Features — cards clicáveis com player de vídeo */}
        <TvFeaturesPlayer data={data} />

        {/* Pacotes TV */}
        <div style={{ marginTop: 60, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 3, border: '3px solid var(--bg)', background: 'var(--ink)' }}>
          {data.tvPlans.map((tv, i) =>
          <TvPlanCard key={tv.id} tv={tv} data={data} index={i} isLast={i === data.tvPlans.length - 1} onOpen={() => setOpenPlan(tv)} />
          )}
        </div>
      </div>

      {openPlan && <ChannelsModal plan={openPlan} onClose={() => setOpenPlan(null)} data={data} />}
    </section>);

};

const TvPlanCard = ({ tv, data, index, isLast, onOpen }) => {
  const [hover, setHover] = useState(false);
  const channelsCount = tv.channels || parseInt(String(tv.channelsLabel || '').replace(/\D/g, ''), 10) || 0;
  const colors = ['var(--bg)', 'var(--yellow)', 'var(--red)', 'var(--blue)'];
  const fgs = ['var(--ink)', 'var(--ink)', 'var(--bg)', 'var(--bg)'];
  const bg = tv.highlight ? 'var(--yellow)' : hover ? colors[(index + 1) % 4] : colors[index % 4];
  const fg = tv.highlight ? 'var(--ink)' : hover ? fgs[(index + 1) % 4] : fgs[index % 4];
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{
      padding: 24, position: 'relative', minHeight: 420,
      background: bg, color: fg, display: 'flex', flexDirection: 'column',
      transition: 'all 250ms', cursor: 'pointer', marginTop: 0
    }}>
      {tv.highlight &&
      <div style={{ position: 'absolute', top: -18, right: 12, background: 'var(--red)', color: 'white', padding: '8px 14px', fontWeight: 800, fontSize: 11, letterSpacing: '0.1em', border: '3px solid var(--ink)', transform: 'rotate(4deg)', fontFamily: 'JetBrains Mono, monospace', zIndex: 2 }}>★ POPULAR</div>
      }
      <div className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em' }}>/ TV-0{index + 1}</div>
      <div className="display" style={{ fontSize: 30, marginTop: 8, lineHeight: 1 }}>{tv.name.toUpperCase()}</div>

      <div style={{ marginTop: 20, display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span className="display" style={{ fontSize: 64 }}>+{channelsCount}</span>
        <span className="mono" style={{ fontSize: 12, fontWeight: 700, opacity: 0.7 }}>CANAIS</span>
      </div>

      <button onClick={onOpen} className="mono" style={{ marginTop: 8, alignSelf: 'flex-start', background: 'transparent', border: '2px solid currentColor', color: 'inherit', padding: '8px 14px', minWidth: 128, fontSize: 11, fontWeight: 700, cursor: 'pointer', letterSpacing: '0.1em', textAlign: 'center' }}>
          👉 VER CANAIS
      </button>

      <div style={{ marginTop: 14, fontSize: 13, lineHeight: 1.4 }}>
        {tv.includesGlobo && <div style={{ display: 'inline-block', background: 'var(--ink)', color: 'var(--bg)', padding: '3px 8px', fontSize: 11, fontWeight: 700, marginBottom: 6 }}>📺 INCLUI TV GLOBO</div>}
        <div>📱 <strong>{tv.devices}</strong> {tv.devices === 1 ? 'dispositivo' : 'dispositivos'}</div>
        <p style={{ margin: '8px 0 0', opacity: 0.85 }}>{tv.description}</p>
      </div>

      <div style={{ marginTop: 'auto', paddingTop: 16, borderTop: '2px dashed currentColor' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{ fontSize: 16, fontWeight: 700 }}>R$</span>
          <span className="display" style={{ fontSize: 44 }}>{Math.floor(tv.price)}</span>
          <span className="display" style={{ fontSize: 22 }}>,{tv.price.toFixed(2).split('.')[1]}</span>
          <span style={{ fontSize: 12, opacity: 0.7, marginLeft: 4 }}>/mês</span>
        </div>
        {tv.priceAfter && <div className="mono" style={{ fontSize: 10, opacity: 0.7, marginTop: 2 }}>depois R$ {tv.priceAfter.toFixed(2).replace('.', ',')}</div>}
        <EditableLink
          path={`tvPlans[${index}].ctaUrl`} label={`Link — ${tv.name}`}
          href={tv.ctaUrl || `https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`}
          target="_blank" rel="noopener" style={{
          marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: tv.highlight ? 'var(--ink)' : 'var(--ink)', color: tv.highlight ? 'var(--yellow)' : 'var(--yellow)',
          padding: '12px 16px', textDecoration: 'none', fontWeight: 800, fontSize: 13, border: '2px solid var(--ink)'
        }}>
          ASSINAR AGORA <span style={{ fontSize: 18 }}>↗</span>
        </EditableLink>
      </div>
    </div>);

};

// Auto-slug a partir do nome + lookup no mapa + fallback local
const LOCAL_CDN = '/logos_canais/';
function autoSlug(name) {
  return name.toLowerCase()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') + '.jpg';
}
function getLogoUrl(c) {
  if (c.slug) return LOCAL_CDN + c.slug;
  if (CHANNEL_LOGOS[c.name]) return CHANNEL_LOGOS[c.name];
  return LOCAL_CDN + autoSlug(c.name);
}

const ChannelsModal = ({ plan, onClose, data }) => {
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  // Seleciona canais conforme o pacote
  const essencial = data.channelsEssencial || [];
  const fullExtras = data.channelsFullExtras || [];
  const isEssencial = plan.package === 'essencial' || (!plan.package && (plan.channels || 0) <= 45);
  const isFull = plan.package === 'full' || plan.includesGlobo;
  const channels = isFull
    ? [...essencial, ...fullExtras]
    : essencial;

  const totalChannels = isFull
    ? (plan.channelsLabel || '+110 canais')
    : (plan.channelsLabel || '+45 canais');

  // Agrupa por categoria
  const categories = isFull ? [
    { label: 'Abertos & Regionais', filter: (c) => parseInt(c.num) <= 15 || c.num.includes('*') },
    { label: 'Esportes', filter: (c) => { const n = parseInt(c.num); return n >= 20 && n <= 39; } },
    { label: 'Notícias', filter: (c) => { const n = parseInt(c.num); return n >= 40 && n <= 50; } },
    { label: 'Entretenimento & Doc', filter: (c) => { const n = parseInt(c.num); return n >= 51 && n <= 99; } },
    { label: 'Religiosos', filter: (c) => { const n = parseInt(c.num); return n >= 150 && n <= 186; } },
    { label: 'Música', filter: (c) => { const n = parseInt(c.num); return n >= 187; } },
    { label: 'Agro', filter: (c) => { const n = parseInt(c.num); return n >= 165 && n <= 171; } },
    { label: 'Internacional', filter: (c) => { const n = parseInt(c.num); return n >= 134 && n <= 138; } },
  ] : [
    { label: 'Abertos & Regionais', filter: (c) => parseInt(c.num) <= 15 || c.num.includes('*') },
    { label: 'Esportes', filter: (c) => { const n = parseInt(c.num); return (n >= 20 && n <= 39) || n === 60; } },
    { label: 'Religiosos', filter: (c) => { const n = parseInt(c.num); return n >= 150 && n <= 186; } },
    { label: 'Música', filter: (c) => { const n = parseInt(c.num); return n >= 187; } },
    { label: 'Agro', filter: (c) => { const n = parseInt(c.num); return n >= 165 && n <= 171; } },
  ];

  const [activeTab, setActiveTab] = useState('todos');
  const filtered = activeTab === 'todos' ? channels : channels.filter(
    categories.find(c => c.label === activeTab)?.filter || (() => true)
  );

  // Cor do header por plano
  const headerColors = {
    'Essencial': { bg: 'var(--bg)', fg: 'var(--ink)' },
    'Essencial Família': { bg: 'var(--yellow)', fg: 'var(--ink)' },
    'Full': { bg: 'var(--red)', fg: 'white' },
    'Full Família': { bg: 'var(--blue)', fg: 'white' },
  };
  const hc = headerColors[plan.name] || { bg: 'var(--yellow)', fg: 'var(--ink)' };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(10,10,20,0.82)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--bg)', width: '100%', maxWidth: 860, maxHeight: '90vh',
        border: '4px solid var(--ink)', boxShadow: '12px 12px 0 var(--yellow)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '20px 24px', borderBottom: '3px solid var(--ink)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: hc.bg, color: hc.fg, flexShrink: 0,
        }}>
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.7 }}>PACOTE</div>
            <div className="display" style={{ fontSize: 'clamp(20px, 5.5vw, 32px)', lineHeight: 1 }}>{plan.name.toUpperCase()}</div>
            <div className="mono" style={{ fontSize: 12, marginTop: 6, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span>{totalChannels}</span>
              {plan.includesGlobo && <span style={{ background: 'var(--ink)', color: 'var(--yellow)', padding: '2px 8px', fontSize: 10, fontWeight: 800 }}>📺 INCLUI TV GLOBO</span>}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'var(--ink)', color: 'var(--yellow)', border: 'none',
            width: 44, height: 44, fontSize: 24, cursor: 'pointer', fontWeight: 800, flexShrink: 0,
          }}>×</button>
        </div>

        {/* Tabs de categoria */}
        <div style={{
          display: 'flex', gap: 0, borderBottom: '2px solid var(--ink)', overflowX: 'auto',
          background: 'white', flexShrink: 0,
        }}>
          <button onClick={() => setActiveTab('todos')} className="mono" style={{
            padding: '10px 16px', border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 11, whiteSpace: 'nowrap',
            background: activeTab === 'todos' ? 'var(--ink)' : 'transparent',
            color: activeTab === 'todos' ? 'var(--yellow)' : 'var(--ink)',
            letterSpacing: '0.08em', borderRight: '1px solid rgba(0,0,0,0.08)',
          }}>TODOS ({channels.length})</button>
          {categories.map(cat => {
            const count = channels.filter(cat.filter).length;
            if (!count) return null;
            return (
              <button key={cat.label} onClick={() => setActiveTab(cat.label)} className="mono" style={{
                padding: '10px 14px', border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 11, whiteSpace: 'nowrap',
                background: activeTab === cat.label ? 'var(--ink)' : 'transparent',
                color: activeTab === cat.label ? 'var(--yellow)' : 'var(--ink)',
                letterSpacing: '0.06em', borderRight: '1px solid rgba(0,0,0,0.08)',
              }}>{cat.label.toUpperCase()} ({count})</button>
            );
          })}
        </div>

        {/* Grade de canais */}
        <div style={{ padding: 20, overflowY: 'auto', flex: 1 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 10 }}>
            {filtered.map((c, i) => {
              const logoUrl = getLogoUrl(c);
              const colors = [['var(--red)','white'],['var(--blue)','white'],['var(--yellow)','var(--ink)'],['var(--ink)','var(--yellow)']];
              const [bg, fg] = colors[i % 4];
              return (
                <div key={i} style={{
                  border: '2px solid var(--ink)', background: 'white',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                  padding: '10px 6px', textAlign: 'center',
                }}>
                  <div style={{
                    width: 52, height: 52, background: logoUrl ? '#f8f8f8' : bg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    overflow: 'hidden', flexShrink: 0,
                  }}>
                    {logoUrl ? (
                      <img
                        src={logoUrl} alt={c.name}
                        style={{ width: '100%', height: '100%', objectFit: 'contain' }}
                        onError={e => {
                          e.target.style.display = 'none';
                          e.target.parentNode.style.background = bg;
                          e.target.parentNode.innerHTML = `<span style="color:${fg};font-weight:900;font-size:11px;font-family:Archivo Black;text-align:center;line-height:1.1;padding:2px;">${c.name.split(' ').map(w=>w[0]).join('').slice(0,3).toUpperCase()}</span>`;
                        }}
                      />
                    ) : (
                      <span style={{ color: fg, fontWeight: 900, fontSize: 11, fontFamily: 'Archivo Black', textAlign: 'center', lineHeight: 1.1 }}>
                        {c.name.split(' ').map(w => w[0]).join('').slice(0,3).toUpperCase()}
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 10, fontWeight: 700, lineHeight: 1.2, color: 'var(--ink)' }}>{c.name}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--ink)', opacity: 0.65 }}>CH {c.num}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* CTA footer */}
        <div style={{ padding: 16, borderTop: '2px solid var(--ink)', background: 'white', flexShrink: 0 }}>
          <a href={`https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`}
             target="_blank" rel="noopener" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            background: 'var(--ink)', color: 'var(--yellow)', padding: '14px 20px',
            textDecoration: 'none', fontWeight: 800, fontSize: 15, border: '2px solid var(--ink)',
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.501-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347zM12.05 21.785h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884z"/></svg>
            ASSINAR {plan.name.toUpperCase()} NO WHATSAPP
          </a>
        </div>
      </div>
    </div>
  );
};

// ADICIONAIS
const Addons = ({ data }) =>
<section id="adicionais" style={{ padding: 'clamp(60px,9vw,100px) clamp(16px,4vw,24px)', background: 'var(--ink)', color: 'var(--bg)', borderTop: '3px solid var(--ink)' }}>
    <div style={{ maxWidth: 1400, margin: '0 auto' }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--yellow)', marginBottom: 16 }}>// 03 — ADICIONAIS</div>
      <h2 className="display" style={{ fontSize: 'clamp(40px, 8vw, 110px)', margin: 0 }}>
        TURBINE A SUA<br />
        <span style={{ color: 'var(--yellow)', fontStyle: 'italic' }}>EXPERIÊNCIA.</span>
      </h2>
      <p style={{ marginTop: 16, fontSize: 14, opacity: 0.8, maxWidth: 600 }}>
        🔥 Clientes BRODNET nos planos <strong>Lite+</strong> e <strong>Full</strong> ganham <strong>30% OFF</strong> nos pacotes adicionais (HBO Max não incluso).
      </p>

      <div style={{ marginTop: 40, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 16 }}>
        {(data.addons || []).map((a, i) =>
      <Reveal key={a.id} delay={i * 60}>
            <div style={{
          padding: 22, background: a.color, color: a.color === 'var(--yellow)' ? 'var(--ink)' : 'var(--bg)',
          border: '3px solid var(--bg)', minHeight: 200, display: 'flex', flexDirection: 'column',
          transition: 'transform 200ms'
        }} onMouseEnter={(e) => {e.currentTarget.style.transform = 'translate(-4px,-4px)';e.currentTarget.style.boxShadow = '8px 8px 0 var(--yellow)';}}
        onMouseLeave={(e) => {e.currentTarget.style.transform = 'none';e.currentTarget.style.boxShadow = 'none';}}>
              <div className="mono" style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.1em' }}>{a.highlight ? '★ DESTAQUE' : `ADD/0${i + 1}`}</div>
              <div className="display" style={{ fontSize: 28, marginTop: 8, lineHeight: 1 }}>{a.name.toUpperCase()}</div>
              <p style={{ margin: '12px 0', fontSize: 13, lineHeight: 1.4, opacity: 0.95 }}>{a.description}</p>
              <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'baseline', gap: 4 }}>
                <span style={{ fontSize: 14, fontWeight: 700 }}>R$</span>
                <span className="display" style={{ fontSize: 32 }}>{Math.floor(a.price)}</span>
                <span className="display" style={{ fontSize: 18 }}>,{a.price.toFixed(2).split('.')[1]}</span>
                <span style={{ fontSize: 11, opacity: 0.8, marginLeft: 4 }}>/mês</span>
              </div>
            </div>
          </Reveal>
      )}
      </div>
    </div>
  </section>;


// CEP
const CepCheck = ({ data }) => {
  const [cep, setCep] = useState('');
  const [status, setStatus] = useState(null);
  const [info, setInfo] = useState(null);
  const submit = async (e) => {
    e.preventDefault();
    const clean = cep.replace(/\D/g, '');
    if (clean.length !== 8) {setStatus('invalid');return;}
    setStatus('checking');
    try {
      const r = await fetch(`/api/cep.php?cep=${clean}`);
      const j = await r.json();
      if (j.ok && j.covered) { setInfo(j); setStatus('ok'); }
      else if (j.ok) { setInfo(null); setStatus('no'); }
      else { setStatus(j.error === 'cep_invalido' ? 'invalid' : 'error'); }
    } catch (_) { setStatus('error'); }
  };
  const fmt = (v) => {const c = v.replace(/\D/g, '').slice(0, 8);return c.length > 5 ? `${c.slice(0, 5)}-${c.slice(5)}` : c;};
  return (
    <section id="cobertura" style={{ background: 'var(--blue)', color: 'var(--bg)', padding: 'clamp(56px,8vw,80px) clamp(16px,4vw,24px)', position: 'relative', overflow: 'hidden', borderTop: '3px solid var(--ink)' }}>
      <div style={{ position: 'absolute', top: 30, left: '10%', fontSize: 40, color: 'var(--yellow)', animation: 'spin-slow 20s linear infinite' }}>✦</div>
      <div style={{ position: 'absolute', bottom: 40, right: '15%', fontSize: 28, color: 'var(--red)', animation: 'spin-slow 12s linear infinite reverse' }}>★</div>
      <div style={{ maxWidth: 900, margin: '0 auto', textAlign: 'center', position: 'relative' }}>
        <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--yellow)', marginBottom: 16 }}>// 06 — COBERTURA</div>
        <h2 className="display" style={{ fontSize: 'clamp(36px, 6vw, 84px)', margin: 0 }}>
          DIGITA O <span style={{ color: 'var(--yellow)' }}>CEP</span><br />E DESCOBRE.
        </h2>
        <form onSubmit={submit} style={{ marginTop: 36, display: 'flex', maxWidth: 560, margin: '36px auto 0', background: 'var(--bg)', border: '3px solid var(--ink)', boxShadow: '8px 8px 0 var(--yellow)' }}>
          <input value={cep} onChange={(e) => {setCep(fmt(e.target.value));setStatus(null);setInfo(null);}} placeholder="00000-000" inputMode="numeric" className="mono" style={{ flex: 1, border: 'none', padding: '18px 22px', fontSize: 20, fontWeight: 700, background: 'transparent', outline: 'none', color: 'var(--ink)', minWidth: 0 }} />
          <button type="submit" style={{ background: 'var(--ink)', color: 'var(--yellow)', border: 'none', padding: '0 24px', fontWeight: 800, fontSize: 15, cursor: 'pointer' }}>VERIFICAR →</button>
        </form>
        {status &&
        <div className="mono" style={{ marginTop: 20, fontSize: 15, fontWeight: 700, color: 'var(--yellow)' }}>
            {status === 'checking' && '⟳ verificando...'}
            {status === 'ok' && <>✓ CHEGAMOS{info && info.bairro && info.bairro !== 'Brodowski' ? ` no ${info.bairro}` : ''}! <a href={`https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#querocomprar')}`} target="_blank" rel="noopener" style={{ color: 'var(--yellow)', textDecoration: 'underline' }}>contrata aqui →</a></>}
            {status === 'no' && '✗ ainda não chegamos aí, mas tamo indo!'}
            {status === 'invalid' && '✗ cep inválido — 8 números'}
            {status === 'error' && '✗ erro ao verificar — tente de novo'}
          </div>
        }
      </div>
    </section>);

};

// Definições das redes sociais (ícone + cor) — usadas no popup do rodapé
const SOCIAL_DEFS = [
  { key: 'instagram', label: 'Instagram', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.2c3.2 0 3.6 0 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s0 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58 0-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.7 3.7 0 0 1-1.38-.9 3.7 3.7 0 0 1-.9-1.38c-.16-.42-.36-1.06-.41-2.23-.06-1.27-.07-1.65-.07-4.85s0-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.21 8.8 2.2 12 2.2zm0 1.8c-3.15 0-3.5 0-4.74.07-.9.04-1.38.19-1.7.32-.43.17-.74.37-1.06.69-.32.32-.52.63-.69 1.06-.13.32-.28.8-.32 1.7C3.2 8.5 3.2 8.85 3.2 12s0 3.5.07 4.74c.04.9.19 1.38.32 1.7.17.43.37.74.69 1.06.32.32.63.52 1.06.69.32.13.8.28 1.7.32 1.24.07 1.59.07 4.74.07s3.5 0 4.74-.07c.9-.04 1.38-.19 1.7-.32.43-.17.74-.37 1.06-.69.32-.32.52-.63.69-1.06.13-.32.28-.8.32-1.7.07-1.24.07-1.59.07-4.74s0-3.5-.07-4.74c-.04-.9-.19-1.38-.32-1.7a2.85 2.85 0 0 0-.69-1.06 2.85 2.85 0 0 0-1.06-.69c-.32-.13-.8-.28-1.7-.32C15.5 4 15.15 4 12 4zm0 3.06A4.94 4.94 0 1 1 12 16.94 4.94 4.94 0 0 1 12 7.06zm0 1.8a3.14 3.14 0 1 0 0 6.28 3.14 3.14 0 0 0 0-6.28zm5.14-.96a1.15 1.15 0 1 1-2.3 0 1.15 1.15 0 0 1 2.3 0z"/></svg> },
  { key: 'facebook', label: 'Facebook', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56V12h2.78l-.44 2.89h-2.34v6.99A10 10 0 0 0 22 12z"/></svg> },
  { key: 'youtube', label: 'YouTube', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M23 7.5a3 3 0 0 0-2.1-2.12C19.06 4.9 12 4.9 12 4.9s-7.06 0-8.9.48A3 3 0 0 0 1 7.5 31 31 0 0 0 .5 12 31 31 0 0 0 1 16.5a3 3 0 0 0 2.1 2.12C4.94 19.1 12 19.1 12 19.1s7.06 0 8.9-.48A3 3 0 0 0 23 16.5 31 31 0 0 0 23.5 12 31 31 0 0 0 23 7.5zM9.75 15.02V8.98L15.5 12l-5.75 3.02z"/></svg> },
  { key: 'linkedin', label: 'LinkedIn', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.35V9h3.42v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.07 2.07 0 1 1 0-4.14 2.07 2.07 0 0 1 0 4.14zm1.78 13.02H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.73v20.54C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.73V1.73C24 .77 23.2 0 22.22 0z"/></svg> },
];

// Card "CONECTE-SE" — abre popup com as redes sociais configuradas no admin
const SocialCard = ({ data }) => {
  const [open, setOpen] = useState(false);
  const networks = SOCIAL_DEFS.filter(s => data.social && data.social[s.key]);
  return (
    <React.Fragment>
      <button onClick={() => setOpen(true)} style={{
        background: 'var(--ink)', color: 'var(--bg)', padding: 24, border: '3px solid var(--bg)',
        display: 'flex', flexDirection: 'column', gap: 8, cursor: 'pointer', textAlign: 'left',
        fontFamily: 'inherit', width: '100%',
      }}>
        <div className="mono" style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.1em' }}>SOCIAL</div>
        <div className="display" style={{ fontSize: 22 }}>CONECTE-SE</div>
        <div style={{ fontSize: 13 }}>Escolha onde falar com a gente.</div>
      </button>
      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 100,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: 'var(--bg)', color: 'var(--ink)', border: '3px solid var(--ink)',
            boxShadow: '10px 10px 0 var(--ink)', maxWidth: 420, width: '100%', padding: '28px 24px',
            position: 'relative',
          }}>
            <button onClick={() => setOpen(false)} aria-label="Fechar" style={{
              position: 'absolute', top: 12, right: 12, width: 38, height: 38, cursor: 'pointer',
              background: 'var(--red)', color: 'white', border: '2px solid var(--ink)', boxShadow: '2px 2px 0 var(--ink)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
            <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--red)' }}>// REDES SOCIAIS</div>
            <div className="display" style={{ fontSize: 30, margin: '4px 0 20px', color: 'var(--ink)' }}>SIGA A BRODNET</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {networks.length === 0 && <div style={{ fontSize: 14, opacity: 0.7 }}>Nenhuma rede social configurada.</div>}
              {networks.map(n => (
                <a key={n.key} href={data.social[n.key]} target="_blank" rel="noopener" style={{
                  display: 'flex', alignItems: 'center', gap: 14, background: 'var(--ink)', color: 'var(--bg)',
                  textDecoration: 'none', padding: '15px 18px', border: '3px solid var(--ink)', boxShadow: '5px 5px 0 var(--yellow)',
                }}>
                  <span style={{ color: 'var(--yellow)', display: 'flex' }}>{n.icon}</span>
                  <span className="mono" style={{ fontSize: 15, fontWeight: 700, letterSpacing: '0.06em' }}>{n.label.toUpperCase()}</span>
                  <span style={{ marginLeft: 'auto', fontWeight: 800 }}>→</span>
                </a>
              ))}
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

const Footer = ({ data }) =>
<footer id="contato" style={{ background: 'var(--red)', color: 'var(--bg)', padding: 'clamp(56px,8vw,90px) clamp(16px,4vw,24px) 32px', borderTop: '3px solid var(--ink)' }}>
    <div style={{ maxWidth: 1400, margin: '0 auto' }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: '0.15em', color: 'var(--yellow)', marginBottom: 16 }}>// 07 — FALA COM A GENTE</div>
      <h2 className="display" style={{ fontSize: 'clamp(48px, 11vw, 160px)', margin: 0, lineHeight: 0.85 }}>
        CONEXÃO<br />
        <span style={{ color: 'var(--yellow)', fontStyle: 'italic' }}>SEGURA</span><br />
        E HUMANA.
      </h2>
      <div style={{ marginTop: 50, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 24 }}>
        <a href={`https://wa.me/${data.contact.whatsapp}?text=${encodeURIComponent('#queroconectar')}`} target="_blank" rel="noopener" style={{ background: '#25d366', color: 'var(--ink)', padding: 24, textDecoration: 'none', border: '3px solid var(--bg)', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div className="mono" style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.1em' }}>ATENDIMENTO</div>
          <div className="display" style={{ fontSize: 22 }}>CONVERSE</div>
          <div style={{ fontSize: 13 }}>Tire suas dúvidas pelo WhatsApp.</div>
        </a>
        <a href={data.contact.centralUrl} target="_blank" rel="noopener" style={{ background: 'var(--yellow)', color: 'var(--ink)', padding: 24, textDecoration: 'none', border: '3px solid var(--bg)', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div className="mono" style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.1em' }}>CENTRAL DO CLIENTE</div>
          <div className="display" style={{ fontSize: 22 }}>ACESSAR</div>
          <div style={{ fontSize: 13 }}>Faturas, pagamentos e serviços.</div>
        </a>
        <SocialCard data={data}/>
      </div>
      <div style={{ marginTop: 60, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.7, marginBottom: 8 }}>TELEFONE</div>
          <div className="display" style={{ fontSize: 28 }}>{data.contact.phone}</div>
        </div>
        <div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.7, marginBottom: 8 }}>E-MAIL</div>
          <div style={{ fontSize: 16, fontWeight: 700 }}>{data.contact.email}</div>
        </div>
        <div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.7, marginBottom: 8 }}>HORÁRIO</div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{data.contact.hours}</div>
        </div>
      </div>
      <div style={{ marginTop: 60, paddingTop: 20, borderTop: '2px solid rgba(244,240,232,0.3)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }} className="mono">
        <span style={{ fontSize: 11, opacity: 0.7 }}>© 2017 BRODNET — Internet Fibra Óptica</span>
      </div>
    </div>
  </footer>;


// Botão flutuante de telefone (click-to-call)
function normalizePhoneForCall(value) {
  const digits = String(value || '').replace(/\D+/g, '');
  if (!digits) return '';
  if (digits.startsWith('55') && digits.length >= 12) return digits;
  if (digits.length === 10 || digits.length === 11) return `55${digits}`;
  return digits;
}

const ClickToCallModal = ({ data, onClose }) => {
  const ctc = data.clickToCall || {};
  const [phone, setPhone] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    const numeroDestino = normalizePhoneForCall(phone);
    if (!numeroDestino || numeroDestino.length < 12) {
      setError('Informe seu telefone com DDD. Se preferir, pode digitar com +55.');
      trackEvent('click_to_call_invalid_phone', { event_category: 'lead', section_id: 'floating_phone' });
      return;
    }

    setBusy(true);
    try {
      const resp = await fetch(ctc.proxyUrl || '/click-to-call-proxy.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ numero_destino: numeroDestino }),
      });
      const json = await resp.json().catch(() => ({}));
      if (!resp.ok || !json?.success) {
        setError(json?.message || 'Nao foi possivel solicitar a ligacao agora.');
        return;
      }
      setSuccess(ctc.successMessage || 'Ligacao solicitada com sucesso. Aguarde nosso retorno.');
      trackEvent('click_to_call_requested', { event_category: 'lead', section_id: 'floating_phone' });
      setPhone('');
    } catch (_) {
      setError('Nao foi possivel solicitar a ligacao agora.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(10,10,20,0.82)', zIndex: 120,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 520, background: 'var(--bg)', border: '4px solid var(--ink)',
        boxShadow: '12px 12px 0 var(--yellow)', overflow: 'hidden',
      }}>
        <div style={{
          background: 'var(--blue)', color: 'white', padding: '18px 22px',
          borderBottom: '3px solid var(--ink)', display: 'flex',
          justifyContent: 'space-between', alignItems: 'center', gap: 16,
        }}>
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.75 }}>CLICK TO CALL</div>
            <div className="display" style={{ fontSize: 'clamp(24px, 5vw, 34px)', lineHeight: 1 }}>
              {(ctc.modalTitle || 'A BRODNET LIGA PRA VOCE').toUpperCase()}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'var(--ink)', color: 'var(--yellow)', border: 'none',
            width: 44, height: 44, fontSize: 24, cursor: 'pointer', fontWeight: 800, flexShrink: 0,
          }}>x</button>
        </div>

        <form onSubmit={submit} style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ fontSize: 14, lineHeight: 1.6 }}>
            {ctc.modalDescription || 'Informe seu telefone com DDD. Nossa central inicia a ligacao e conecta voce ao atendimento.'}
          </div>

          <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.12em' }}>
              {(ctc.inputLabel || 'Seu telefone').toUpperCase()}
            </span>
            <input
              value={phone}
              onChange={e => setPhone(e.target.value)}
              placeholder={ctc.inputPlaceholder || '(16) 99999-9999'}
              disabled={busy}
              style={{
                height: 54, border: '3px solid var(--ink)', background: 'white', color: 'var(--ink)',
                padding: '0 16px', fontSize: 18, fontWeight: 700, outline: 'none',
              }}
            />
          </label>

          <div style={{ fontSize: 12, opacity: 0.7 }}>
            Digite com DDD. Se informar apenas 10 ou 11 digitos, o site adiciona o +55 automaticamente.
          </div>

          {error && <div style={{ fontSize: 13, color: '#990000', background: '#99000010', padding: 12, borderRadius: 6 }}>{error}</div>}
          {success && <div style={{ fontSize: 13, color: '#14532d', background: '#14532d10', padding: 12, borderRadius: 6 }}>{success}</div>}

          <button type="submit" disabled={busy} className="mono" style={{
            background: 'var(--red)', color: 'white', border: '3px solid var(--ink)',
            boxShadow: '6px 6px 0 var(--ink)', padding: '14px 18px', cursor: busy ? 'wait' : 'pointer',
            fontSize: 12, fontWeight: 800, letterSpacing: '0.08em',
          }}>
            {busy ? 'SOLICITANDO...' : (ctc.submitLabel || 'SOLICITAR LIGACAO')}
          </button>
        </form>
      </div>
    </div>
  );
};

const PhoneButton = ({ data, onOpen }) => {
  const width = useWindowWidth();
  const isMobile = width < 768;
  const ctc = data.clickToCall || {};
  if (ctc.enabled === false) return null;

  if (ctc.html && ctc.html.trim()) {
    return (
      <div
        style={{
          position: 'fixed', bottom: isMobile ? 88 : 94, right: 24, zIndex: 40,
        }}
        dangerouslySetInnerHTML={{ __html: ctc.html }}
      />
    );
  }

  return (
    <button
      type="button"
      onClick={onOpen}
      title={ctc.tooltip || 'Ligar agora'}
      style={{
        position: 'fixed', bottom: isMobile ? 88 : 94, right: 24, zIndex: 40,
        width: isMobile ? 54 : 60, height: isMobile ? 54 : 60,
        background: 'var(--blue)', border: '3px solid var(--ink)',
        color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '6px 6px 0 var(--ink)', transition: 'transform 150ms',
        borderRadius: 0, cursor: 'pointer',
      }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'translate(-3px,-3px)'; e.currentTarget.style.boxShadow = '9px 9px 0 var(--ink)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '6px 6px 0 var(--ink)'; }}
    >
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.13 12a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 2.98 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 21 17z"/>
      </svg>
    </button>
  );
};

const { EditModeProvider, Editable, EditableLink } = window.BrodnetEdit;

const WaFloatingButton = ({ data }) => {
  const width = useWindowWidth();
  const isMobile = width < 768;

  return (
    <a href={`https://wa.me/${data.contact.whatsapp}?text=%23queroconectar`} target="_blank" rel="noopener" style={{
      position: 'fixed', bottom: 24, right: 24, zIndex: 40, width: isMobile ? 54 : 60, height: isMobile ? 54 : 60,
      background: '#25d366', border: '3px solid var(--ink)', color: 'white',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '6px 6px 0 var(--ink)', textDecoration: 'none', transition: 'transform 150ms'
    }} onMouseEnter={(e) => {e.currentTarget.style.transform = 'translate(-3px,-3px)';e.currentTarget.style.boxShadow = '9px 9px 0 var(--ink)';}}
    onMouseLeave={(e) => {e.currentTarget.style.transform = 'none';e.currentTarget.style.boxShadow = '6px 6px 0 var(--ink)';}}>
      <svg width={isMobile ? "24" : "28"} height={isMobile ? "24" : "28"} viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.501-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487 2.981 1.287 2.981.858 3.518.804.537-.054 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347zM12.05 21.785a9.86 9.86 0 0 1-5.031-1.378l-3.741.982 1-3.648a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 5.448 0 9.882 4.434 9.884 9.884 0 5.451-4.434 9.884-9.884 9.884z" /></svg>
    </a>
  );
};

const App = () => {
  const [data, setData] = useSiteData();
  const [clickToCallOpen, setClickToCallOpen] = useState(false);
  useEffect(() => {
    const route = getRouteConfig();
    if (!route?.section) return;
    const timer = setTimeout(() => {
      document.getElementById(route.section)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 450);
    return () => clearTimeout(timer);
  }, []);
  const openClickToCall = () => {
    trackEvent('click_to_call_open', { event_category: 'lead', section_id: 'floating_phone' });
    setClickToCallOpen(true);
  };
  return (
    <EditModeProvider data={data} setData={setData}>
      <SeoManager data={data} />
      <AnalyticsManager data={data} />
      <Nav data={data} />
      <Hero data={data} />
      <HeroCtaBar data={data} />
      <PromoBanner data={data} />
      <Marquee items={['#QUEROCONECTAR', 'FIBRA ÓPTICA', 'WI-FI 5G GRÁTIS', 'SEM PEGADINHAS']} />
      <AppSection data={data} />
      <div id="combos" />
      <PlansCategory id="internet" number="01" label="INTERNET FIBRA ÓPTICA"
      sectionTitle="PLANOS SEM" sectionAccent="SURPRESAS."
      plans={data.plans} data={data}
      getValue={(p) => p.speed} getUnit={() => 'MBPS'}
      bgColor="var(--bg)" fgColor="var(--ink)" accentColor="var(--red)" />
      <PlansCategory id="fone" number="02" label="TELEFONIA FIXA"
      sectionTitle="LIGA SEM" sectionAccent="LIMITE."
      plans={data.phonePlans} data={data}
      getValue={(p) => p.benefits[0].split(' ')[0]} getUnit={(p) => p.benefits[0].includes('Ilimitado') ? 'ILIMITADO' : 'MIN/MÊS'}
      bgColor="var(--bg)" fgColor="var(--ink)" accentColor="var(--blue)" />
      <PlansCategory id="movel" number="03" label="INTERNET 4G/5G"
      sectionTitle="4G PRA" sectionAccent="LEVAR."
      plans={data.mobilePlans} data={data}
      getValue={(p) => p.data} getUnit={() => 'GB'}
      bgColor="var(--yellow)" fgColor="var(--ink)" accentColor="var(--red)" />
      <Marquee items={['ASSINA NO WHATS', 'INSTALAÇÃO HOJE', 'SUPORTE HUMANO']} bg="var(--red)" color="var(--bg)" speed={25} />
      <TvSection data={data} />
      <Addons data={data} />
      <Marquee items={['BROD BOX A R$9,90', 'TRANSFORME SUA TV EM SMART TV']} bg="var(--yellow)" color="var(--ink)" speed={28} />
      <CepCheck data={data} />
      <Footer data={data} />
      <PhoneButton data={data} onOpen={openClickToCall} />
      {clickToCallOpen && <ClickToCallModal data={data} onClose={() => setClickToCallOpen(false)} />}
      <WaFloatingButton data={data} />
    </EditModeProvider>);

};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
