/* global React, tr, trDate, localHref */
const { useEffect: useEffectC, useRef: useRefC, useState: useStateC } = React;

/* ============================================================
   pacode: reusable components
   ============================================================ */

function PacodeLogo({ height = 36 }) {
  return (
    <img src="assets/pacode-logo.png" alt="pacode" style={{ height: `${height}px`, width: "auto" }} />
  );
}

function BalloonSvg({ color = "#E63946", width = 80, style = {} }) {
  return (
    <svg viewBox="0 0 80 120" width={width} style={style} aria-hidden="true">
      <ellipse cx="40" cy="48" rx="32" ry="40" fill={color} />
      <path d="M40 88 L36 96 L44 96 Z" fill={color} />
      <path d="M40 96 Q34 104 42 112 Q50 116 38 120" stroke={color} strokeWidth="2" fill="none" strokeLinecap="round" />
      <ellipse cx="30" cy="34" rx="6" ry="10" fill="rgba(255,255,255,0.32)" />
    </svg>
  );
}

function GridPattern() {
  return (
    <svg className="pc-grid-pattern" viewBox="0 0 200 240" preserveAspectRatio="none" aria-hidden="true">
      {[...Array(10)].map((_, i) =>
        [...Array(12)].map((_, j) => (
          <rect key={`${i}-${j}`} x={i * 20 + 1} y={j * 20 + 1} width="18" height="18" fill="none" stroke="#1E40AF" strokeWidth="0.6" opacity={(i + j) % 3 === 0 ? 0.9 : 0.35} />
        ))
      )}
    </svg>
  );
}

function ConfettiTiles() {
  const palette = ["#E63946", "#E8B739", "#1E40AF", "#0B0F1A", "transparent", "transparent"];
  const cells = [];
  for (let r = 0; r < 4; r++) {
    for (let c = 0; c < 11; c++) {
      const seed = (r * 13 + c * 7) % palette.length;
      cells.push(palette[seed]);
    }
  }
  return (
    <div className="pc-collage__tiles" aria-hidden="true">
      {cells.map((bg, i) => (
        <span key={i} style={{ background: bg, transform: i % 2 ? "skewX(-12deg)" : "skewX(12deg)" }} />
      ))}
    </div>
  );
}

function Eyebrow({ children }) {
  return <p className="pc-eyebrow">{children}</p>;
}

/* `action` is the main way out of a section: a button right below the text
   that opens the full page ({ label, href }). `links` are the small tags in
   the corner, for secondary navigation (back, anchors, external links). */
function SectionHeader({ eyebrow, title, lead, tag, links, action, level = 2 }) {
  const Heading = level === 1 ? "h1" : "h2";
  return (
    <header className="pc-section__header pc-reveal">
      <div>
        <Eyebrow>{eyebrow}</Eyebrow>
        <Heading className="pc-section__title">{title}</Heading>
        {lead ? <p className="pc-section__lead">{lead}</p> : null}
        {action ? (
          <a className="pc-section__cta" href={localHref(action.href)}>
            {action.label}
            <span className="pc-section__cta-icon" aria-hidden="true">→</span>
          </a>
        ) : null}
      </div>
      {links ? (
        <div className="pc-section__actions">
          {links.map((l) => (
            <a
              className="pc-tag is-link"
              href={localHref(l.href)}
              {...(/^https?:/.test(l.href) ? { target: "_blank", rel: "noopener noreferrer" } : {})}
              aria-label={l.ariaLabel}
              key={l.href}>
              {l.label}
              <span className="tag-icon" aria-hidden="true">{l.icon || "↗"}</span>
            </a>
          ))}
        </div>
      ) : tag ? (
        <span className="pc-tag">
          {tag}
          <span className="tag-icon" aria-hidden="true">→</span>
        </span>
      ) : null}
    </header>
  );
}

function PlaceholderMedia({ label, src, alt }) {
  return (
    <div className={`pc-card__media${src ? " has-image" : ""}`}>
      {src ? <img src={src} alt={alt || ""} className="pc-card__media-img" /> : null}
      <span className="placeholder-label">{label}</span>
    </div>
  );
}

function postHref(post) {
  return localHref(`blog.html?post=${encodeURIComponent(post.slug)}`);
}

/* One cell of the news grid. The title link is stretched over the whole
   cell, so the card is clickable but screen readers get a single link. */
function NewsItem({ post, feature = false, level = 3 }) {
  const Heading = `h${level}`;
  return (
    <article className={`pc-news__item${feature ? " is-feature" : ""}`}>
      <div className={`pc-news__media${post.image ? " has-image" : ""}`}>
        {post.image ? <img src={post.image} alt={post.imageAlt || ""} className="pc-news__media-img" /> : null}
        <span className="placeholder-label">{tr("imagem", "image")}: {post.cat.toLowerCase()}</span>
      </div>
      <div className="pc-news__meta">
        <span className="pc-news__cat">○ {post.cat}</span>
        <span>{trDate(post.date)}</span>
      </div>
      <Heading className="pc-news__title">
        <a className="pc-news__link" href={postHref(post)}>{post.title}</a>
      </Heading>
      <p className="pc-news__excerpt">{post.excerpt}</p>
      <span className="pc-news__more" aria-hidden="true">
        {tr("Ler notícia", "Read story")}
        <span className="pc-news__arrow">→</span>
      </span>
    </article>
  );
}

/* Turns **negrito** and [texto](url) into elements. Everything else is
   plain text, so content written in the data files never goes through
   innerHTML. Used by the blog and by the FAQ of participar.html. */
function renderInline(text) {
  const out = [];
  const re = /\*\*(.+?)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g;
  let last = 0;
  let m;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) out.push(text.slice(last, m.index));
    if (m[1] != null) {
      out.push(<strong key={m.index}>{m[1]}</strong>);
    } else {
      const external = /^https?:/.test(m[3]);
      out.push(
        <a key={m.index} href={localHref(m[3])} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>
          {m[2]}
        </a>
      );
    }
    last = re.lastIndex;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

/* Accent of each member, in the rotation order of the design system. */
const MEMBER_ACCENTS = ["#E63946", "#E8B739", "#1E40AF", "#0B0F1A"];

/* Square photo of a member, or the initial over the accent color when
   there is no photo yet. `showTag` adds the tag chip (co-founder) on the
   corner of the photo. */
function MemberAvatar({ member, index = 0, showTag = false }) {
  const accent = MEMBER_ACCENTS[index % MEMBER_ACCENTS.length];
  return (
    <div className={`pc-member__avatar${member.image ? " has-image" : ""}`} style={{
      background: member.image ? undefined : `radial-gradient(circle at 50% 35%, ${accent}33, ${accent}10 65%, ${accent}05)`
    }}>
      {member.image ?
      <img src={member.image} alt={member.imageAlt || member.name} className="pc-member__photo" loading="lazy" /> :
      <span className="initial" aria-hidden="true">{member.name[0]}</span>}
      {showTag && member.tag ? <span className="tag" style={{ borderColor: accent, color: accent }}>○ {member.tag}</span> : null}
    </div>);

}

/* The outside link of a member: LinkedIn, or a public CV page for someone
   who has no LinkedIn. Renders nothing when the member has neither. */
function MemberLink({ member }) {
  const href = member.linkedin || member.cv;
  if (!href) return null;
  const onLinkedin = Boolean(member.linkedin);
  return (
    <a
      className="pc-member__link"
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      aria-label={onLinkedin ?
      tr(`LinkedIn de ${member.name}`, `${member.name} on LinkedIn`) :
      tr(`Currículo de ${member.name}`, `CV of ${member.name}`)}>
      {onLinkedin ? "LinkedIn" : tr("Currículo", "CV")}
      <span className="pc-member__arrow" aria-hidden="true">↗</span>
    </a>);

}

/* simple scroll-reveal: adds .is-in to .pc-reveal elements when entering viewport */
function useScrollReveal() {
  useEffectC(() => {
    const els = document.querySelectorAll(".pc-reveal");
    if (!("IntersectionObserver" in window)) {
      els.forEach((el) => el.classList.add("is-in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

Object.assign(window, {
  PacodeLogo, BalloonSvg, GridPattern, ConfettiTiles, Eyebrow,
  SectionHeader, PlaceholderMedia, NewsItem, postHref, renderInline, MemberAvatar, MemberLink, useScrollReveal,
});
