// Componentes UI compartilhados

const FLAGS = {
  us: { stripes: ['#bf0a30', '#ffffff'], canton: '#002868' },
  br: { bg: '#009c3b', diamond: '#ffdf00', circle: '#002776' },
  pt: { left: '#046a38', right: '#da291c' }
};

function Flag({ country, className }) {
  const f = FLAGS[country];
  if (country === 'us') {
    return (
      <span className={'locale-flag ' + (className || '')} style={{ overflow: 'hidden' }}>
        <img src={(window.__rsrc && window.__rsrc('flag-us.png')) || 'flag-us.png'} alt="USA" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </span>);

  }
  if (country === 'br') {
    return (
      <span className={'locale-flag ' + (className || '')} style={{ overflow: 'hidden' }}>
        <img src={(window.__rsrc && window.__rsrc('flag-br.png')) || 'flag-br.png'} alt="Brasil" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </span>);

  }
  if (country === 'pt') {
    return (
      <span className={'locale-flag ' + (className || '')} style={{ overflow: 'hidden' }}>
        <img src={(window.__rsrc && window.__rsrc('flag-pt.png')) || 'flag-pt.png'} alt="Portugal" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </span>);

  }
  return null;
}

function MiniFlag({ country }) {
  return <Flag country={country} className="chip-flag" />;
}

function Nav({ lang, setLang, onDonate }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [projOpen, setProjOpen] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [active, setActive] = React.useState('sobre');
  const projRef = React.useRef(null);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  React.useEffect(() => {
    const onClick = (e) => {if (projRef.current && !projRef.current.contains(e.target)) setProjOpen(false);};
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);
  // Scroll-spy: track active section
  React.useEffect(() => {
    const sectionIds = ['sobre', 'projetos', 'equipe'];
    const els = sectionIds.map((id) => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
      },
      { rootMargin: '-40% 0px -55% 0px', threshold: 0 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
  const clickNav = (id) => () => setActive(id);
  const t = lang === 'pt' ?
  { about: 'Início', projects: 'Projetos', team: 'Equipe', transp: 'Transparência', partner: 'Seja parceiro', all: 'Ver todos os projetos' } :
  { about: 'Home', projects: 'Programs', team: 'Team', transp: 'Transparency', partner: 'Partner with us', all: 'See all programs' };
  const { PROJECTS } = window.SC_DATA;
  return (
    <React.Fragment>
    <nav className="nav" style={{ borderBottomColor: scrolled ? 'var(--line-2)' : 'var(--line)' }}>
      <div className="container nav-inner">
        <a href={(window.SC_SITE && window.SC_SITE.home) || 'index.html'} className="brand brand-full">
          <img src={window.__r('logoFull', 'logo-full.png')} alt="Support Center · Café com Mulheres Corp." className="brand-full-img" />
        </a>
        <div className="nav-links">
          <a href="#sobre" className={active === 'sobre' ? 'active' : ''} onClick={clickNav('sobre')}>{t.about}</a>
          <div className="nav-projects" ref={projRef}>
            <button
              className={'nav-projects-btn ' + (projOpen || active === 'projetos' ? 'active' : '') + (projOpen ? ' open' : '')}
              onClick={() => { setProjOpen((o) => !o); setActive('projetos'); }}>
              
              {t.projects} <span className="nav-caret">▾</span>
            </button>
            {projOpen &&
            <div className="nav-projects-menu">
                <div className="nav-projects-label mono">{t.projects}</div>
                {PROJECTS.map((p) =>
              <a
                key={p.id}
                href={'Projeto.html?id=' + p.id + '#' + p.id}
                className="nav-project-item"
                onClick={() => setProjOpen(false)}>
                
                    <span className="nav-project-num mono" style={{ color: p.color }}>{p.num}</span>
                    <span className="nav-project-meta">
                      <span className="nav-project-name">{p.label}</span>
                      <span className="nav-project-tag">{typeof p.tag === 'object' ? (p.tag[lang] || p.tag.pt) : p.tag}</span>
                    </span>
                    <span className="arrow">→</span>
                  </a>
              )}
                <a href="#projetos" className="nav-projects-all" onClick={() => setProjOpen(false)}>
                  {t.all} →
                </a>
              </div>
            }
          </div>
          <a href="#equipe" className={active === 'equipe' ? 'active' : ''} onClick={clickNav('equipe')}>{t.team}</a>
          <a href="Transparencia.html">{t.transp}</a>
        </div>
        <div className="nav-cta">
          <button
            className="pill-link nav-lang"
            onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}
            title="Alternar idioma">
            
            {lang === 'pt' ? 'PT · BR' : 'EN · US'}
          </button>
          <button className="btn btn-primary nav-donate-btn" onClick={onDonate}>
            <span className="nav-donate-text nav-donate-text--full">{lang === 'pt' ? 'Doe agora' : 'Donate'}</span>
            <span className="nav-donate-text nav-donate-text--short">{lang === 'pt' ? 'Doe' : 'Donate'}</span>
            <span className="arrow nav-donate-arrow" style={{ marginLeft: 4 }}>→</span>
          </button>
          <button
            className={'nav-hamburger ' + (menuOpen ? 'is-open' : '')}
            onClick={() => setMenuOpen((o) => !o)}
            aria-label="Menu">
            <span /><span /><span />
          </button>
        </div>
      </div>
    </nav>
    {menuOpen &&
    <div className="nav-drawer-overlay" onClick={() => setMenuOpen(false)}>
      <div className="nav-drawer" onClick={(e) => e.stopPropagation()}>
        <button
          type="button"
          className="nav-drawer-lang nav-drawer-lang--top"
          onClick={() => { setLang(lang === 'pt' ? 'en' : 'pt'); }}>
          {lang === 'pt' ? 'PT · BR' : 'EN · US'} <span style={{ opacity: 0.6 }}>↻</span>
        </button>
        <a href="#sobre" className={active === 'sobre' ? 'active' : ''} onClick={() => { clickNav('sobre')(); setMenuOpen(false); }}>{t.about}</a>
        <div className="nav-drawer-section">
          <div className="nav-drawer-label">{t.projects}</div>
          {PROJECTS.map((p) =>
          <a key={p.id} href={'Projeto.html?id=' + p.id + '#' + p.id} className="nav-drawer-project" onClick={() => setMenuOpen(false)}>
            <span className="nav-project-num mono" style={{ color: p.color }}>{p.num}</span>
            <span className="nav-project-meta">
              <span className="nav-project-name">{p.label}</span>
              <span className="nav-project-tag">{typeof p.tag === 'object' ? (p.tag[lang] || p.tag.pt) : p.tag}</span>
            </span>
            <span className="arrow">→</span>
          </a>
          )}
        </div>
        <a href="#equipe" className={active === 'equipe' ? 'active' : ''} onClick={() => { clickNav('equipe')(); setMenuOpen(false); }}>{t.team}</a>
        <a href="Transparencia.html" onClick={() => setMenuOpen(false)}>{t.transp}</a>
      </div>
    </div>
    }
    </React.Fragment>);

}

const LOCATIONS = [
{ c: 'br', city: 'Minas Gerais', region: 'Brasil' },
{ c: 'br', city: 'Amapá', region: 'Brasil' },
{ c: 'br', city: 'São Paulo', region: 'Brasil' },
{ c: 'br', city: 'Paraíba', region: 'Brasil' },
{ c: 'pt', city: 'Albufeira', region: 'Algarve, Portugal' },
{ c: 'pt', city: 'Quarteira', region: 'Algarve, Portugal' },
{ c: 'us', city: 'Orlando', region: 'Flórida, USA' },
{ c: 'us', city: 'Deerfield Beach', region: 'Flórida, USA' }];


function LocationCarousel({ lang }) {
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % LOCATIONS.length), 2400);
    return () => clearInterval(id);
  }, [paused]);
  const cur = LOCATIONS[idx];
  return (
    <div
      className="hero-locales"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}>
      
      <div className="locale-head">
        <span className="mono">{lang === 'pt' ? 'Onde estamos' : 'Where we are'}</span>
      </div>
      <div className="locale-stage" key={idx}>
        <div className="locale-flag-lg"><Flag country={cur.c} /></div>
        <div className="locale-city serif">{cur.city}</div>
        <div className="locale-region">{cur.region}</div>
        <div className="locale-nucleus mono">
          {cur.c === 'br' ? (lang === 'pt' ? 'Núcleo brasileiro' : 'Brazilian hub')
            : cur.c === 'pt' ? (lang === 'pt' ? 'Núcleo europeu' : 'Portuguese hub')
            : (lang === 'pt' ? 'Núcleo americano' : 'American hub')}
        </div>
      </div>
      <div className="locale-track">
        {LOCATIONS.map((_, i) =>
        <button
          key={i}
          className={'locale-dot ' + (i === idx ? 'active' : '')}
          onClick={() => setIdx(i)}
          aria-label={'Local ' + (i + 1)} />

        )}
      </div>
    </div>);

}

const HERO_PORTRAITS = [
{ tone: '#8E3544', x: '8%', y: '12%', size: 220, delay: 0, label: 'Macapá' },
{ tone: '#a85567', x: '72%', y: '6%', size: 180, delay: 0.5, label: 'Albufeira' },
{ tone: '#6b2433', x: '85%', y: '52%', size: 240, delay: 1.0, label: 'Florida' },
{ tone: '#c27e8a', x: '2%', y: '58%', size: 170, delay: 1.5, label: 'São Paulo' },
{ tone: '#5a3a40', x: '40%', y: '78%', size: 150, delay: 2.0, label: 'Quarteira' }];


function HeroPortraits() {
  const [idx, setIdx] = React.useState(0);
  const slides = [
    window.__r('hero1', 'hero-1.jpg'),
    window.__r('hero2', 'hero-2.jpg'),
    window.__r('hero3', 'hero-3.jpg'),
    window.__r('hero4', 'hero-4.jpg'),
    window.__r('hero5', 'hero-5.jpg'),
  ];
  React.useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % slides.length), 5500);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="hero-portraits" aria-hidden="true">
      {slides.map((src, i) =>
      <div
        key={i}
        className={'hero-bg-image ' + (i === idx ? 'is-active' : '')}
        style={{ backgroundImage: 'url(' + src + ')' }} />

      )}
      <div className="hero-bg-overlay" />
      <div className="hero-bg-dots">
        {slides.map((_, i) =>
        <button
          key={i}
          className={'hero-bg-dot ' + (i === idx ? 'active' : '')}
          onClick={() => setIdx(i)}
          aria-label={'Slide ' + (i + 1)} />

        )}
      </div>
    </div>);

}

function Hero({ lang, onDonate }) {
  const t = lang === 'pt' ? {
    eyebrow: 'Resultados que transformam pessoas',
    titleA: 'Apoiamos projetos que',
    titleEm: 'transformam',
    titleB: 'vidas.',
    sub: 'A Support Center Café com Mulheres Corp é uma organização sem fins lucrativos que desenvolve e apoia projetos estruturados para fortalecer comunidades, impulsionar o empreendedorismo e promover transformação social, com atuação nacional e internacional.',
    cta1: 'Seja parceiro',
    cta2: 'Doar agora',
    live: 'Apoie projetos que transformam vidas. Seja um parceiro.'
  } : {
    eyebrow: 'Results that transform lives',
    titleA: 'Supporting initiatives that',
    titleEm: 'transform',
    titleB: 'lives.',
    sub: 'Support Center Café com Mulheres Corp is a nonprofit organization that develops and supports structured initiatives to strengthen communities, foster entrepreneurship, and promote social transformation at both national and international levels.',
    cta1: 'Partner with us',
    cta2: 'Donate now',
    live: 'Support programs that transform lives. Partner with us.'
  };
  return (
    <section className="hero" id="top">
      <HeroPortraits />
      <div className="container hero-inner">
        <div className="hero-grid">
          <div>
            <div className="eyebrow">{t.eyebrow}</div>
            <h1 className="hero-title serif">
              {t.titleA} <em>{t.titleEm}</em> {t.titleB}
            </h1>
            <p className="hero-sub">{t.sub}</p>
            <div className="hero-actions">
              <button className="btn btn-primary" onClick={onDonate}>{t.cta2} <span className="arrow">→</span></button>
              <a href="#projetos" className="btn btn-ghost">{t.cta1}</a>
            </div>
          </div>
          <LocationCarousel lang={lang} />
        </div>

        <div className="hero-strip">
          <div className="hero-strip-left">
            <span className="dot" />
            <span style={{ fontSize: "16px", color: "rgb(255, 255, 255)" }}>{t.live}</span>
          </div>
          <div className="mono">SC · 2026</div>
        </div>
      </div>
    </section>);

}

function Metrics({ lang }) {
  const { METRICS } = window.SC_DATA;
  return (
    <section className="metrics container" data-screen-label="Métricas">
      {METRICS.map((m, i) =>
      <div className="metric" key={i}>
          <div className="metric-num">
            {lang === 'en' && m.numEn ?
            m.numEn :
            <React.Fragment><span className="plus">+</span>{m.num}</React.Fragment>}
          </div>
          <div className="metric-label">{m.label[lang]}</div>
          <div className="metric-loc">{m.loc[lang]}</div>
        </div>
      )}
    </section>);

}

function NewsTicker({ lang }) {
  const items = lang === 'pt' ?
  ['Coragem', 'Independência', 'Acolhimento', 'Preparação', 'Conexão', 'Cursos', 'Workshops', 'Palestras', 'Mentoria', 'Networking', 'Transformação', 'Propósito'] :
  ['Courage', 'Independence', 'Welcoming', 'Preparation', 'Connection', 'Courses', 'Workshops', 'Talks', 'Mentorship', 'Networking', 'Transformation', 'Purpose'];
  return (
    <div className="news-ticker">
      <div className="news-track">
        {[...items, ...items].map((it, i) => <span key={i}>{it}</span>)}
      </div>
    </div>);

}

function projectImageSrc(filename) {
  if (!filename) return '';
  if (filename === 'elo-marias.png' && window.__r) return window.__r('eloMarias', filename);
  if (window.__rsrc) return window.__rsrc(filename);
  return filename;
}

function projectPageHref(id) {
  const site = window.SC_SITE || {};
  if (typeof site.projectHref === 'function') return site.projectHref(id);
  const item = (site.projects || []).find((p) => p.href && p.href.indexOf('id=' + id) !== -1);
  return item ? item.href : 'Projeto.html?id=' + encodeURIComponent(id) + '#' + encodeURIComponent(id);
}

function ProjectVisual({ proj, lang }) {
  const foot = (
    <div className="proj-visual-foot">
      <span>support center · café com mulheres</span>
      <span>{proj.label}</span>
    </div>
  );

  if (proj.visualMontage && proj.visualPhotos && proj.visualPhotos.length) {
    const tiles = proj.visualPhotos.map((item, i) => {
      const src = typeof item === 'string' ? item : item.src;
      const pos = typeof item === 'string' ? 'center' : (item.pos || 'center');
      return (
        <div
          key={i}
          className="proj-visual-tile"
          style={{
            backgroundImage: 'url(' + projectImageSrc(src) + ')',
            backgroundPosition: pos
          }} />
      );
    });

    return (
      <div
        className="proj-visual reveal in proj-visual--montage"
        style={{ '--montage-tint': proj.visualTint || '#2a1418' }}>
        
        <div className="proj-visual-collage" aria-hidden="true">{tiles}</div>
        <div className="proj-visual-montage-scrim" aria-hidden="true" />
        <div className="proj-visual-montage-glow" aria-hidden="true" />
        {proj.visualLogo &&
        <div className="proj-visual-logo-wrap">
            <img
            src={projectImageSrc(proj.visualLogo)}
            alt={proj.label}
            className="proj-visual-logo" />
          </div>
        }
        {foot}
      </div>);

  }

  if (proj.image) {
    const isCard = !!proj.cardImage;
    return (
      <div
        className={'proj-visual reveal in --has-image' + (proj.imageFit === 'contain' ? ' --fit-contain' : '') + (isCard ? ' --card-image' : '')}
        style={{
          backgroundImage: 'url(' + projectImageSrc(proj.image) + ')',
          backgroundSize: proj.imageFit || 'cover',
          backgroundPosition: proj.imagePosition || 'center',
          backgroundRepeat: 'no-repeat',
          ...(proj.imageBg ? { backgroundColor: proj.imageBg } : {})
        }}>
        
        {!isCard && <div className="proj-visual-scrim" />}
        {!isCard &&
        <div className="proj-visual-foot" style={{ color: 'rgba(255,255,255,0.9)', marginTop: 'auto' }}>
          <span>support center · café com mulheres</span>
          <span>{proj.label}</span>
        </div>
        }
      </div>);

  }

  return (
    <div className="proj-visual reveal in --placeholder">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative', zIndex: 2 }}>
        <span className="proj-visual-tag">FOTO · {proj.label.toUpperCase()}</span>
        <span className="mono" style={{ color: proj.color }}>{proj.num} / 04</span>
      </div>
      <div className="proj-visual-num" style={{ position: 'relative', zIndex: 2, color: 'var(--ink)' }}>
        {proj.visualNum}<span className="small" style={{ color: 'var(--ink-2)' }}>{proj.visualSmall[lang]}</span>
      </div>
      <div className="proj-visual-foot" style={{ color: 'var(--ink-2)' }}>
        <span>support center · café com mulheres</span>
        <span>{proj.label}</span>
      </div>
    </div>);

}

function Projects({ lang }) {
  const { PROJECTS } = window.SC_DATA;
  const [active, setActive] = React.useState(PROJECTS[0].id);
  const proj = PROJECTS.find((p) => p.id === active);
  const t = lang === 'pt' ?
  { eyebrow: 'Quatro frentes, um propósito', title: 'Nossos', titleEm: 'projetos', lead: 'Iniciativas estruturadas que se complementam, do acolhimento emocional à construção de patrimônio. Cada uma com formato próprio, presencial e online.', where: 'Atuação', learn: 'Conhecer o projeto' } :
  { eyebrow: 'Four fronts, one purpose', title: 'Our', titleEm: 'programs', lead: 'Structured initiatives that complement each other, ranging from emotional support to wealth building. All programs are available in both in-person and online formats.', where: 'Operating in', learn: 'Learn more' };
  return (
    <section className="container section" id="projetos" data-screen-label="Projetos">
      <div className="section-head">
        <div>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2 className="section-title serif">{t.title} <em>{t.titleEm}</em></h2>
        </div>
        <p className="section-lead">{t.lead}</p>
      </div>

      <div className="proj-tabs">
        {PROJECTS.map((p) =>
        <button
          type="button"
          key={p.id}
          className={'proj-tab ' + (active === p.id ? 'active' : '')}
          onClick={() => setActive(p.id)}>
          
            {p.logo &&
            <img
              className="proj-tab-logo"
              src={window.__rsrc ? window.__rsrc(p.logo) : p.logo}
              alt=""
              aria-hidden="true" />
            }
            <span>{p.label}</span>
          </button>
        )}
      </div>

      <div className="proj-content" key={active}>
        <div className="proj-info reveal in">
          <div className="mono" style={{ color: proj.color }}>{typeof proj.tag === 'object' ? (proj.tag[lang] || proj.tag.pt) : proj.tag}</div>
          <h3 className="serif">
            {proj.title[lang]} <em>{proj.titleEm[lang]}</em>
          </h3>
          <p className="proj-desc">{proj.desc[lang]}</p>
          <ul className="proj-list">
            {proj.items[lang].map((it, i) => <li key={i}><span>{it}</span></li>)}
          </ul>
          <div className="proj-where">
            <span className="mono" style={{ alignSelf: 'center', marginRight: 8 }}>{t.where}</span>
            {proj.where.map((c) =>
            <span className="chip" key={c}>
                <MiniFlag country={c} />
                <span>{c === 'us' ? (lang === 'pt' ? 'EUA' : 'USA') : c === 'br' ? (lang === 'pt' ? 'Brasil' : 'Brazil') : 'Portugal'}</span>
              </span>
            )}
          </div>
          <a href={projectPageHref(proj.id)} className="btn btn-ghost proj-learn-link">
            {t.learn} <span className="arrow">→</span>
          </a>
        </div>
        <ProjectVisual proj={proj} lang={lang} />
      </div>
    </section>);

}

window.SC_UI = { Nav, Hero, Metrics, NewsTicker, Projects, Flag, MiniFlag };