// Shared building blocks: buttons, badges, dividers, countdown, reveal

// Reveal: IntersectionObserver-driven fade-up.
// Uses a CSS keyframe animation triggered by adding the .is-in class.
// IMPORTANT: when document.hidden is true (e.g. preview iframe not in foreground)
// CSS animations and transitions are paused — so we fall back to instant-show.
const Reveal = ({ children, delay = 0, y = 40, className = "", once = true }) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  const [docVisible, setDocVisible] = React.useState(() =>
    typeof document === 'undefined' ? true : !document.hidden
  );

  // Track visibility so we switch from instant-show to animated reveal when the
  // tab/iframe becomes visible.
  React.useEffect(() => {
    const onChange = () => setDocVisible(!document.hidden);
    document.addEventListener('visibilitychange', onChange);
    return () => document.removeEventListener('visibilitychange', onChange);
  }, []);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;

    let timer = null;
    let io = null;

    const reveal = () => {
      timer = setTimeout(() => setShown(true), Math.max(20, delay * 1000));
    };

    const vh = window.innerHeight || document.documentElement.clientHeight || 800;
    const rect = el.getBoundingClientRect();
    if (rect.top < vh * 1.0 && rect.bottom > 0) {
      reveal();
      if (once) return () => { if (timer) clearTimeout(timer); };
    }

    io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            reveal();
            if (once && io) io.unobserve(entry.target);
          } else if (!once) {
            setShown(false);
          }
        });
      },
      { threshold: 0, rootMargin: '0px 0px -5% 0px' }
    );
    io.observe(el);
    return () => {
      if (timer) clearTimeout(timer);
      if (io) io.disconnect();
    };
  }, [once, delay]);

  // When the document is hidden (preview iframes etc.) CSS animations don't run,
  // so the reveal would stay invisible. Render plain children with no animation.
  if (!docVisible) {
    return <div ref={ref} className={className}>{children}</div>;
  }

  return (
    <div
      ref={ref}
      className={`reveal-host ${shown ? 'is-in' : 'reveal-pending'} ${className}`}
      style={{ '--reveal-y': `${y}px` }}
    >
      {children}
    </div>
  );
};

// Big monumental CTA — solid crimson, hover gold
const PrimaryCTA = ({ href = "#", children, large = false, icon = null, ...rest }) => (
  <a
    href={href}
    className={`group relative inline-flex items-center justify-center gap-3
      font-headline uppercase tracking-[0.25em]
      ${large ? 'px-10 py-5 text-base sm:text-lg' : 'px-7 py-3.5 text-sm'}
      bg-crimson-700 text-parchment
      border border-crimson-500
      transition-all duration-300
      hover:bg-gold-700 hover:text-stone-950 hover:border-gold-500
      hover:shadow-[0_0_40px_rgba(218,165,32,0.35)]
      active:translate-y-[1px]`}
    style={{ clipPath: 'polygon(8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px), 0 8px)' }}
    {...rest}
  >
    {/* corner accents */}
    <span aria-hidden className="absolute top-0 left-0 w-2 h-2 border-l border-t border-gold-500/70 group-hover:border-stone-950" />
    <span aria-hidden className="absolute top-0 right-0 w-2 h-2 border-r border-t border-gold-500/70 group-hover:border-stone-950" />
    <span aria-hidden className="absolute bottom-0 left-0 w-2 h-2 border-l border-b border-gold-500/70 group-hover:border-stone-950" />
    <span aria-hidden className="absolute bottom-0 right-0 w-2 h-2 border-r border-b border-gold-500/70 group-hover:border-stone-950" />
    {icon}
    <span>{children}</span>
  </a>
);

// Outlined gold CTA
const GhostCTA = ({ href = "#", children, large = false, icon = null, ...rest }) => (
  <a
    href={href}
    className={`group relative inline-flex items-center justify-center gap-3
      font-headline uppercase tracking-[0.25em]
      ${large ? 'px-10 py-5 text-base sm:text-lg' : 'px-7 py-3.5 text-sm'}
      bg-transparent text-gold-400
      border border-gold-700
      transition-all duration-300
      hover:bg-gold-700/10 hover:text-gold-300 hover:border-gold-500
      hover:shadow-[0_0_30px_rgba(218,165,32,0.2)]
      active:translate-y-[1px]`}
    style={{ clipPath: 'polygon(8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px), 0 8px)' }}
    {...rest}
  >
    {icon}
    <span>{children}</span>
  </a>
);

// Ornamental divider with center label
const OrnamentDivider = ({ label = null, className = "" }) => (
  <div className={`flex items-center gap-4 sm:gap-8 w-full ${className}`}>
    <div className="flex-1 h-px bg-gradient-to-r from-transparent via-gold-700/60 to-transparent" />
    {label && (
      <>
        <div className="w-2 h-2 rotate-45 border border-gold-700/70" />
        <span className="font-impact tracking-[0.4em] text-xs text-gold-500/80">{label}</span>
        <div className="w-2 h-2 rotate-45 border border-gold-700/70" />
      </>
    )}
    {!label && <div className="w-2 h-2 rotate-45 border border-gold-700/70" />}
    <div className="flex-1 h-px bg-gradient-to-r from-transparent via-gold-700/60 to-transparent" />
  </div>
);

// Section heading: kicker + display title
const SectionHeading = ({ kicker, title, subtitle, align = "center" }) => (
  <div className={`flex flex-col gap-4 ${align === 'center' ? 'items-center text-center' : 'items-start text-left'}`}>
    {kicker && (
      <div className="flex items-center gap-3 text-gold-500/80">
        <div className="w-8 h-px bg-gold-700/70" />
        <span className="font-impact tracking-[0.5em] text-xs">{kicker}</span>
        <div className="w-8 h-px bg-gold-700/70" />
      </div>
    )}
    <h2 className="font-display font-black uppercase tracking-tight text-4xl sm:text-5xl md:text-6xl lg:text-7xl text-parchment text-shadow-monument leading-[0.95]">
      {title}
    </h2>
    {subtitle && (
      <p className="font-body text-base sm:text-lg text-parchment/60 max-w-2xl leading-relaxed">
        {subtitle}
      </p>
    )}
  </div>
);

// Pull-quote between sections — gold, large, monumental, i18n-aware
const PullQuote = ({ tKey, children }) => {
  const ctx = React.useContext(LangContext);
  const text = tKey ? ctx.t(tKey) : children;
  return (
    <Reveal>
      <div className="relative py-16 sm:py-24 px-6 flex flex-col items-center text-center gap-6">
        <div className="text-gold-500/60">
          <Ornament className="w-40 h-6" />
        </div>
        <blockquote className="font-display italic text-2xl sm:text-3xl md:text-4xl lg:text-5xl text-gold-400 text-glow-gold max-w-4xl leading-[1.2]">
          "{text}"
        </blockquote>
        <div className="text-gold-500/60 rotate-180">
          <Ornament className="w-40 h-6" />
        </div>
      </div>
    </Reveal>
  );
};

// ============================================================
// COUNTDOWN — Next Sunday 17:00 (America/Sao_Paulo)
// ============================================================

function nextSundayAt17BRT() {
  // BRT is UTC-3, no DST
  const now = new Date();
  // Get current time in São Paulo by offsetting from UTC
  const utcMs = now.getTime();
  const spOffsetMs = -3 * 60 * 60 * 1000; // BRT = UTC-3
  const sp = new Date(utcMs + spOffsetMs);
  // sp's UTC fields represent São Paulo wall-clock
  const dow = sp.getUTCDay(); // 0=Sun
  let daysUntilSun = (7 - dow) % 7;
  // Construct candidate Sunday 17:00 in SP wall-clock
  const candidateSp = new Date(Date.UTC(sp.getUTCFullYear(), sp.getUTCMonth(), sp.getUTCDate() + daysUntilSun, 17, 0, 0));
  // If today is Sunday but past 17:00, push +7
  if (candidateSp.getTime() - spOffsetMs <= utcMs) {
    candidateSp.setUTCDate(candidateSp.getUTCDate() + 7);
  }
  // Convert back to real UTC instant
  return candidateSp.getTime() - spOffsetMs;
}

const Countdown = () => {
  const [target] = React.useState(() => nextSundayAt17BRT());
  const [now, setNow] = React.useState(() => Date.now());
  const ctx = React.useContext(LangContext);
  const tt = ctx ? ctx.t : (k) => k;
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff % 86400000) / 3600000);
  const minutes = Math.floor((diff % 3600000) / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, '0');

  const units = [
    { label: tt('cd_days'),    value: pad(days) },
    { label: tt('cd_hours'),   value: pad(hours) },
    { label: tt('cd_minutes'), value: pad(minutes) },
    { label: tt('cd_seconds'), value: pad(seconds) },
  ];

  return (
    <div className="flex items-stretch justify-center gap-3 sm:gap-5 lg:gap-10">
      {units.map((u, i) => (
        <React.Fragment key={u.label}>
          <div className="flex flex-col items-center gap-3 min-w-[68px] sm:min-w-[100px] lg:min-w-[140px]">
            <div className="relative w-full">
              {/* Card */}
              <div className="relative bg-stone-900 border border-gold-700/40 px-2 py-4 sm:px-4 sm:py-7 md:py-9 overflow-hidden">
                {/* corner ticks */}
                <span aria-hidden className="absolute top-1 left-1 w-2 h-2 border-l border-t border-gold-500/70" />
                <span aria-hidden className="absolute top-1 right-1 w-2 h-2 border-r border-t border-gold-500/70" />
                <span aria-hidden className="absolute bottom-1 left-1 w-2 h-2 border-l border-b border-gold-500/70" />
                <span aria-hidden className="absolute bottom-1 right-1 w-2 h-2 border-r border-b border-gold-500/70" />
                {/* horizontal seam */}
                <div className="absolute left-0 right-0 top-1/2 h-px bg-stone-950/80" />
                <div
                  key={u.value}
                  className="font-display font-black tabular-nums text-4xl sm:text-5xl lg:text-7xl xl:text-8xl text-center text-gold-400 text-glow-gold leading-none"
                  style={{ textShadow: '0 2px 0 #000, 0 0 30px rgba(218,165,32,0.35)' }}
                >
                  {u.value}
                </div>
              </div>
            </div>
            <div className="font-impact tracking-[0.35em] text-[10px] sm:text-xs text-parchment/60">{u.label}</div>
          </div>
          {i < units.length - 1 && (
            <div className="hidden sm:flex items-center justify-center font-display text-4xl lg:text-6xl text-crimson-600 self-stretch pb-7">
              :
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

Object.assign(window, {
  Reveal, PrimaryCTA, GhostCTA, OrnamentDivider, SectionHeading, PullQuote, Countdown,
});
