/* global React */
// ============================================================
// Craque Cidadão — Home sections A: Hero, Impact, About, Projects, Instagram
// ============================================================
const { Icon, Reveal, CountUp, CourtLines, CC_LOGO, WA_LINK, IG_LINK } = window;

// Decorative CSS "ball" — subtle 3D futsal sphere.
function Ball({ size = 120, style = {} }) {
  return (
    <div aria-hidden style={{
      width: size, height: size, borderRadius: '50%', flex: 'none',
      background: 'radial-gradient(circle at 32% 28%, #fff 0 6%, var(--blue-300) 12%, var(--blue-600) 52%, var(--navy-900) 100%)',
      boxShadow: 'inset -8px -10px 22px rgba(8,24,48,0.45), 0 18px 36px rgba(8,24,48,0.32)',
      position: 'relative', overflow: 'hidden', ...style,
    }}>
      <svg viewBox="0 0 100 100" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}>
        <g fill="none" stroke="rgba(255,255,255,0.55)" strokeWidth="2">
          <path d="M50 14 L70 30 L62 56 L38 56 L30 30 Z" fill="rgba(12,28,56,0.5)" />
          <path d="M50 14 L50 2 M70 30 L86 24 M62 56 L74 74 M38 56 L26 74 M30 30 L14 24" />
        </g>
      </svg>
    </div>
  );
}

function FloatChip({ icon, label, value, style }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 11, background: '#fff',
      padding: '11px 16px', borderRadius: 'var(--radius-pill)', boxShadow: 'var(--shadow-lg)', ...style,
    }}>
      <span style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--brand-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
        <Icon name={icon} size={18} color="var(--brand)" />
      </span>
      <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
        <strong style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 18, color: 'var(--brand-ink)' }}>{value}</strong>
        <span style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 600 }}>{label}</span>
      </span>
    </div>
  );
}

const HERO_PHOTOS = [
  { src: 'uploads/Futsal01.jpeg', alt: 'Jovens na quadra' },
  { src: 'uploads/20240328_145216.jpg', alt: 'Oficina de culinária com a comunidade' },
  { src: 'uploads/IMG-20240406-WA0080.jpg', alt: 'Turma em formação na sala de aula' },
  { src: 'uploads/IMG-20240330-WA0163.jpg', alt: 'Entrega de certificado a participante' },
];

function HeroSlideshow() {
  const [i, setI] = React.useState(0);
  const motionOff = window.CC_MOTION === 'off';
  React.useEffect(() => {
    if (motionOff) return;
    const id = setInterval(() => setI((p) => (p + 1) % HERO_PHOTOS.length), 4200);
    return () => clearInterval(id);
  }, [motionOff]);
  return (
    <div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 5', borderRadius: 28, overflow: 'hidden', boxShadow: 'var(--shadow-lg)', border: '5px solid #fff' }}>
      {HERO_PHOTOS.map((p, idx) => (
        <img key={p.src} src={p.src} alt={p.alt}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
            opacity: idx === i ? 1 : 0, transition: 'opacity 900ms var(--ease-out)' }} />
      ))}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 14, display: 'flex', justifyContent: 'center', gap: 8, zIndex: 2 }}>
        {HERO_PHOTOS.map((p, idx) => (
          <button key={p.src} onClick={() => setI(idx)} aria-label={`Foto ${idx + 1}`}
            style={{ width: idx === i ? 22 : 8, height: 8, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 0,
              background: idx === i ? '#fff' : 'rgba(255,255,255,0.55)', boxShadow: '0 1px 4px rgba(18,36,64,0.35)', transition: 'width var(--dur) var(--ease-out), background var(--dur)' }} />
        ))}
      </div>
    </div>
  );
}

function Hero({ onNav, heroStyle = 'photo' }) {
  const { Button } = window.CraqueCidadODesignSystem_6fdc08;
  return (
    <section style={{ position: 'relative', overflow: 'hidden', background: 'linear-gradient(135deg, var(--blue-700) 0%, var(--navy-900) 100%)', color: '#fff' }}>
      <CourtLines opacity={0.1} />
      <Ball size={210} style={{ position: 'absolute', right: '-60px', top: '-50px', opacity: 0.5, filter: 'blur(0.4px)' }} />
      <div className="cc-hero-grid" style={{
        position: 'relative', maxWidth: 'var(--container)', margin: '0 auto', padding: '92px 24px 100px',
        display: 'grid', gridTemplateColumns: '1.08fr 0.92fr', gap: 56, alignItems: 'center',
      }}>
        <div>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--gold-400)' }}>
            <span style={{ width: 26, height: 2, background: 'currentColor' }} /> Desde 2009 · Duque de Caxias/RJ
          </span>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 5.2vw, 4.1rem)', lineHeight: 1.02, letterSpacing: '-0.02em', color: '#fff', margin: '18px 0 0' }}>
            Formando craques<br />dentro e fora<br /><span style={{ color: 'var(--gold-400)' }}>da quadra.</span>
          </h1>
          <p style={{ fontSize: 'var(--fs-lead)', lineHeight: 1.55, color: 'rgba(255,255,255,0.88)', maxWidth: 540, margin: '22px 0 34px' }}>
            A ONG Craque Cidadão usa o esporte como ferramenta de inclusão, educação e cidadania para crianças e adolescentes em situação de vulnerabilidade social.
          </p>
          <div style={{ display: 'flex', gap: 13, flexWrap: 'wrap' }}>
            <window.WAButton size="lg">Fale pelo WhatsApp</window.WAButton>
            <Button variant="accent" size="lg" iconRight={<Icon name="arrow-right" size={18} />} onClick={() => onNav('projetos')}>Conheça nossos projetos</Button>
            <button onClick={() => onNav('parceiros')} className="cc-btn-frost"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '15px 26px', borderRadius: 'var(--radius-pill)', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16.5, color: '#fff', background: 'rgba(255,255,255,0.12)', border: '2px solid rgba(255,255,255,0.55)', backdropFilter: 'blur(4px)', transition: 'background var(--dur), border-color var(--dur), transform var(--dur)' }}>
              <Icon name="handshake" size={18} /> Seja parceiro
            </button>
          </div>
        </div>

        <div style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
          {heroStyle === 'card' ? (
            <div style={{ background: '#fff', borderRadius: 'var(--radius-xl)', padding: 32, boxShadow: 'var(--shadow-lg)', transform: 'rotate(-2deg)' }}>
              <img src={CC_LOGO} alt="Craque Cidadão" style={{ width: 230, height: 'auto', display: 'block' }} />
            </div>
          ) : (
            <div style={{ position: 'relative', width: '100%', maxWidth: 460 }}>
              <HeroSlideshow />
              <FloatChip icon="trophy" value="+08" label="Títulos" style={{ position: 'absolute', left: -26, top: 28 }} />
              <FloatChip icon="users" value="+780" label="Jovens" style={{ position: 'absolute', right: -22, bottom: 36 }} />
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function ImpactBand({ compact = false }) {
  const stats = window.CC_STATS;
  return (
    <section style={{ background: 'linear-gradient(135deg, var(--blue-600), var(--navy-900))', position: 'relative', overflow: 'hidden' }}>
      <CourtLines opacity={0.08} />
      <div style={{ position: 'relative', maxWidth: 'var(--container)', margin: '0 auto', padding: '60px 24px' }}>
        <Reveal>
          <p style={{ textAlign: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--gold-400)', margin: '0 0 36px' }}>
            Nossa ONG em fatos e números
          </p>
        </Reveal>
        <div className="cc-impact-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 20 }}>
          {stats.map((s, i) => (
            <Reveal key={s.label} delay={i * 80}>
              <div style={{ textAlign: 'center' }}>
                <Icon name={s.icon} size={26} color="rgba(255,255,255,0.55)" style={{ marginBottom: 8 }} />
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.4rem, 4.5vw, 3.6rem)', lineHeight: 0.95, letterSpacing: '-0.02em', color: '#fff' }}>
                  <CountUp end={s.value} prefix={s.prefix} />
                </div>
                <div style={{ marginTop: 8, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.78)' }}>{s.label}</div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function AboutBlock({ onNav }) {
  const { SectionHeading, Card, Button } = window.CraqueCidadODesignSystem_6fdc08;
  return (
    <section style={{ background: 'var(--surface-card)' }}>
      <div className="cc-about-grid" style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--cc-sy, 88px) 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center' }}>
        <Reveal>
          <SectionHeading eyebrow="O que é a Craque Cidadão" title="Mais do que formar atletas, formamos cidadãos."
            intro="A Craque Cidadão nasceu para ocupar positivamente o tempo de crianças e adolescentes, oferecendo esporte, convivência, disciplina, valores e oportunidades." />
          <p style={{ fontSize: 'var(--fs-body)', lineHeight: 1.65, color: 'var(--text-body)', margin: '18px 0 26px' }}>
            Atendemos de forma individualizada cada jovem e sua família — a base sobre a qual se constrói qualquer futuro. O esporte é o caminho; a cidadania, o destino.
          </p>
          <Button variant="primary" iconRight={<Icon name="arrow-right" size={17} />} onClick={() => onNav('quem-somos')}>Conheça nossa história</Button>
        </Reveal>
        <Reveal delay={120} style={{ position: 'relative' }}>
          <image-slot id="about-home" shape="rounded" radius="22" src="uploads/Amistoso Futsal sub11 e sub 14.jpeg" placeholder="Foto da equipe / atividade"
            style={{ display: 'block', width: '100%', height: 'auto', aspectRatio: '5 / 4', borderRadius: 22, boxShadow: 'var(--shadow-md)' }}></image-slot>
          <Card tone="navy" style={{ position: 'absolute', left: -18, bottom: -22, maxWidth: 250, boxShadow: 'var(--shadow-lg)' }}>
            <p style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, lineHeight: 1.35, color: '#fff', margin: 0 }}>
              “O esporte carrega a magia de construir famílias e multiplicar alegria.”
            </p>
          </Card>
        </Reveal>
      </div>
    </section>
  );
}

function ProjectsPreview({ onNav }) {
  const { SectionHeading, Button } = window.CraqueCidadODesignSystem_6fdc08;
  const items = window.CC_PROJECTS;
  const toneBg = { brand: 'var(--brand)', navy: 'var(--navy-900)', accent: 'var(--accent)' };
  return (
    <section style={{ background: 'var(--surface-page)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--cc-sy, 88px) 24px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap', marginBottom: 40 }}>
          <SectionHeading eyebrow="Nossos Projetos" title="Onde a transformação acontece" />
          <Button variant="outline" iconRight={<Icon name="arrow-right" size={16} />} onClick={() => onNav('projetos')}>Ver todos</Button>
        </div>
        <div className="cc-proj-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 22 }}>
          {items.map((p, i) => (
            <Reveal key={p.title} delay={i * 70} as="article" style={{ height: '100%' }}>
              <ProjectTile p={p} bg={toneBg[p.tone]} onNav={onNav} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProjectTile({ p, bg, onNav }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onClick={() => onNav && onNav('projetos')}
      style={{
        height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--surface-card)',
        borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', overflow: 'hidden', cursor: 'pointer',
        boxShadow: hover ? 'var(--shadow-lg)' : 'var(--shadow-sm)', transform: hover ? 'translateY(-4px)' : 'none',
        transition: 'transform var(--dur) var(--ease-out), box-shadow var(--dur) var(--ease-out)',
      }}>
      <div style={{ height: 92, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}>
        <Icon name={p.icon} size={40} color={p.tone === 'accent' ? 'var(--navy-950)' : '#fff'} />
      </div>
      <div style={{ padding: 'var(--space-5)', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--fs-h3)', color: 'var(--brand-ink)' }}>{p.title}</h3>
        <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-body)', flex: 1 }}>{p.text}</p>
        <span style={{ marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--brand)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14 }}>
          Saiba mais <span style={{ transform: hover ? 'translateX(4px)' : 'none', transition: 'transform var(--dur)' }}>→</span>
        </span>
      </div>
    </div>
  );
}

// InstagramFeed — preview com cards simulados.
// >> INTEGRAÇÃO FUTURA: substitua CC_IG_POSTS por dados da Instagram Graph API.
//    Endpoint: GET /{ig-user-id}/media?fields=caption,media_url,permalink,timestamp
//    Use autenticação oficial da Meta (NÃO usar scraping). Em caso de falha,
//    o componente mantém o fallback com os cards manuais abaixo.
function InstagramFeed() {
  const { SectionHeading, Button } = window.CraqueCidadODesignSystem_6fdc08;
  const posts = window.CC_IG_POSTS;
  return (
    <section style={{ background: 'var(--surface-card)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--cc-sy, 88px) 24px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap', marginBottom: 40 }}>
          <SectionHeading eyebrow="Últimas do Instagram" title="Acompanhe nossos últimos momentos" />
          <a href={IG_LINK} target="_blank" rel="noopener" style={{ textDecoration: 'none' }}>
            <Button variant="outline" iconLeft={<Icon name="instagram" size={17} />}>@ongcraquecidadao</Button>
          </a>
        </div>
        <div className="cc-ig-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
          {posts.map((post, i) => (
            <Reveal key={i} delay={i * 70}>
              <IgCard post={post} idx={i} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function IgCard({ post, idx }) {
  const { Badge } = window.CraqueCidadODesignSystem_6fdc08;
  const [hover, setHover] = React.useState(false);
  return (
    <a href={IG_LINK} target="_blank" rel="noopener" onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column', textDecoration: 'none', background: 'var(--surface-card)',
        borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', overflow: 'hidden',
        boxShadow: hover ? 'var(--shadow-lg)' : 'var(--shadow-sm)', transform: hover ? 'translateY(-4px)' : 'none',
        transition: 'transform var(--dur) var(--ease-out), box-shadow var(--dur) var(--ease-out)',
      }}>
      <div style={{ position: 'relative' }}>
        <image-slot id={`ig-${idx}`} shape="rect" src={post.src} placeholder="Post do Instagram"
          style={{ display: 'block', width: '100%', height: 'auto', aspectRatio: '1 / 1' }}></image-slot>
        <div style={{ position: 'absolute', top: 10, left: 10 }}><Badge tone="accent" solid>{post.tag}</Badge></div>
        <div style={{ position: 'absolute', top: 10, right: 10, width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,255,255,0.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="instagram" size={16} color="var(--brand-ink)" />
        </div>
      </div>
      <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5, color: 'var(--text-body)', display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{post.caption}</p>
        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 600 }}>{post.date}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--brand)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12.5 }}>Ver no Instagram <Icon name="external-link" size={13} /></span>
        </div>
      </div>
    </a>
  );
}

function TestimonialVideo() {
  const { SectionHeading } = window.CraqueCidadODesignSystem_6fdc08;
  const videoRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);

  // Persist playback position
  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const saved = parseFloat(localStorage.getItem('cc_testimonial_time') || '0');
    if (saved > 0) v.currentTime = saved;
    const save = () => localStorage.setItem('cc_testimonial_time', v.currentTime);
    v.addEventListener('timeupdate', save);
    return () => v.removeEventListener('timeupdate', save);
  }, []);

  const handleToggle = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) { v.play(); setPlaying(true); }
    else { v.pause(); setPlaying(false); }
  };

  return (
    <section style={{ background: 'linear-gradient(135deg, var(--blue-700) 0%, var(--navy-900) 100%)', position: 'relative', overflow: 'hidden' }}>
      <CourtLines opacity={0.07} />
      <div style={{ position: 'relative', maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--cc-sy, 88px) 24px' }}>
        <Reveal style={{ textAlign: 'center', marginBottom: 44 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--gold-400)', marginBottom: 14 }}>
            <span style={{ width: 26, height: 2, background: 'currentColor' }} /> Depoimento
          </span>
          <SectionHeading align="center" title="Quem vive a Craque Cidadão fala por ela." style={{ color: '#fff' }} />
        </Reveal>
        <Reveal delay={100}>
          <div style={{ maxWidth: 860, margin: '0 auto', position: 'relative', borderRadius: 22, overflow: 'hidden', boxShadow: '0 32px 80px rgba(8,24,48,0.55)' }}>
            <video ref={videoRef} src="uploads/Depoimento_CraqueCidadao.mp4"
              controls
              onPlay={() => setPlaying(true)}
              onPause={() => setPlaying(false)}
              style={{ display: 'block', width: '100%', height: 'auto', background: '#000' }}
            />
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, ImpactBand, AboutBlock, ProjectsPreview, ProjectTile, InstagramFeed, TestimonialVideo, Ball });
