// Componentes globais compartilhados (nav, footer, grain, intro)
// Carregar via <script type="text/babel" src="js/shared.jsx"></script>

const { useState, useEffect, useRef } = React;

function Grain() {
  return <div id="noise" aria-hidden="true"></div>;
}

function Nav({ active }) {
  return (
    <div id="menu">
      <a id="logo" href="index.html" className="page-link">
        MARA<span className="dot"></span>
      </a>
      <nav id="nav">
        <a className={"page-link " + (active === "work" ? "selected" : "")} href="work.html">Trabalhos</a>
        <a className={"page-link " + (active === "about" ? "selected" : "")} href="about.html">Studio</a>
        <a className={"page-link " + (active === "contact" ? "selected" : "")} href="contact.html">Contato</a>
      </nav>
    </div>);

}

function SplitLine({ text, className = "", delayOffset = 0 }) {
  // wrap each char in a span with .split-line for animation
  const chars = [...text];
  return (
    <span className={"split-line " + className}>
      {chars.map((c, i) =>
      <span key={i} style={{ animationDelay: `${delayOffset + i * 0.045}s` }}>
          {c === " " ? " " : c}
        </span>
      )}
    </span>);

}

function PlayIcon({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="currentColor">
      <path d="M3 1 L16 9 L3 17 Z" />
    </svg>);

}

function ArrowIcon() {
  return (
    <svg width="16" height="12" viewBox="0 0 16 12" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M1 6 H15 M10 1 L15 6 L10 11" />
    </svg>);

}

// Generic cinematic placeholder for project videos
function VideoStill({ label, timecode = "00:00:14:21", duration = "00:18", tone = 0, aspect = "16/10" }) {
  // tone shifts hue slightly so cards feel different
  const hueShift = [0, -8, 6, -14, 12, 0][tone % 6];
  const baseStyle = {
    aspectRatio: aspect,
    filter: `hue-rotate(${hueShift}deg)`
  };
  return (
    <div className="video-still" style={baseStyle}>
      <span className="corner tl"></span>
      <span className="corner tr"></span>
      <span className="play"><PlayIcon size={18} /></span>
      {label &&
      <div style={{
        position: "absolute", left: 14, bottom: 14,
        fontFamily: "Courier New, monospace",
        fontSize: 10, letterSpacing: "0.18em",
        color: "rgba(242,234,219,0.85)",
        textTransform: "uppercase"
      }}>
          REC ● {label}
        </div>
      }
      <div className="timecode">{timecode}</div>
      <div className="frame-marks"></div>
    </div>);

}

function SpinBadge({ text = "QUE MARA! • QUE MARA! • ", size = 140, color = "var(--color-dark)" }) {
  // svg with text on circle
  const radius = size / 2 - 12;
  const id = "tp-" + Math.random().toString(36).slice(2, 8);
  return (
    <div className="spin-badge" style={{ width: size, height: size }}>
      <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
        <defs>
          <path id={id} d={`M ${size / 2}, ${size / 2} m -${radius}, 0 a ${radius},${radius} 0 1,1 ${radius * 2},0 a ${radius},${radius} 0 1,1 -${radius * 2},0`} />
        </defs>
        <text fontFamily="Bitter, serif" fontSize="11" fontWeight="500" letterSpacing="2" fill={color} style={{ textTransform: "uppercase" }}>
          <textPath href={`#${id}`}>{text.repeat(3)}</textPath>
        </text>
      </svg>
      <div className="core"></div>
    </div>);

}

function Footer() {
  const [tc, setTc] = useState("00:00:00:00");
  useEffect(() => {
    // marca o início da sessão (persiste entre navegações até fechar a aba)
    let start = Number(sessionStorage.getItem("mara-session-start"));
    if (!start) {
      start = Date.now();
      sessionStorage.setItem("mara-session-start", String(start));
    }
    const tick = () => {
      const elapsed = Date.now() - start;
      const totalSec = Math.floor(elapsed / 1000);
      const hh = String(Math.floor(totalSec / 3600)).padStart(2, "0");
      const mm = String(Math.floor((totalSec % 3600) / 60)).padStart(2, "0");
      const ss = String(totalSec % 60).padStart(2, "0");
      const ff = String(Math.floor((elapsed % 1000) / 1000 * 24)).padStart(2, "0"); // 24fps
      setTc(`${hh}:${mm}:${ss}:${ff}`);
    };
    tick();
    const id = setInterval(tick, 1000 / 12); // 12hz suficiente pro frame piscar
    return () => clearInterval(id);
  }, []);

  return (
    <footer>
      <div className="footer-headline">
        VAMOS<br />FAZER<span style={{ color: "var(--color-red)" }}>.</span>
      </div>
      <div style={{ display: "flex", gap: "3vw", alignItems: "flex-end", marginTop: "2vw" }}>
        <a href="contact.html" className="button" style={{ borderColor: "var(--color-sand)" }}>
          MANDA UMA MENSAGEM <ArrowIcon />
        </a>
        <div style={{ marginLeft: "auto", textAlign: "right" }}>
          <div className="caption" style={{ marginBottom: 8, opacity: 0.7 }}>FALA COM A GENTE</div>
          <div style={{ fontSize: "var(--f-20)" }}>contato@produtoramara.com.br</div>
          <div style={{ fontSize: "var(--f-20)", opacity: 0.7 }}>@produtoramara</div>
        </div>
      </div>
      <div className="footer-meta">
        <div className="fm-social">
          <a href="https://instagram.com/produtoramara" target="_blank" rel="noreferrer" aria-label="Instagram">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.9" fill="currentColor" stroke="none"/></svg>
            <span>Instagram</span>
          </a>
          <a href="https://vimeo.com/produtoramara" target="_blank" rel="noreferrer" aria-label="Vimeo">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 8.5c1.5-1.2 3-2.2 4.3-2.2 1.5 0 2.2 1 2.5 2.4.5 2.2.9 4 1.6 4 .8 0 2.2-2.5 2.4-4 .2-1.5-.4-2.2-1.4-2-1 .2-1.5.7-1.5.7s.6-2.4 3.4-2.4c2.6 0 3 2 2.6 4-.4 2.4-3.4 7.5-5 8.6-1.7 1.2-3-.6-3.6-3-.5-2.3-1-5.5-1.6-5.5-.4 0-1.2.7-2 1.4z"/></svg>
            <span>Vimeo</span>
          </a>
          <a href="https://youtube.com/@produtoramara" target="_blank" rel="noreferrer" aria-label="YouTube">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="2.5" y="6" width="19" height="12" rx="3"/><path d="M10.5 9.5l4.5 2.5-4.5 2.5z" fill="currentColor" stroke="none"/></svg>
            <span>YouTube</span>
          </a>
          <a href="mailto:contato@produtoramara.com.br" aria-label="E-mail">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="2.5" y="5" width="19" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>
            <span>E-mail</span>
          </a>
        </div>

        <div className="fm-rec">
          <span className="fm-rec-dot"></span>
          <span>REC · ROLLING</span>
          <span className="fm-tc">{tc}</span>
        </div>

        <div className="fm-info">
          <span>© MARA · 2026</span>
          <span className="fm-sep">▸</span>
          <span>GOIÂNIA · BR</span>
          <span className="fm-sep">▸</span>
          <span>SITE EM CONSTRUÇÃO PERMANENTE</span>
        </div>
      </div>
    </footer>);

}

function IntroOverlay({ onDone }) {
  const [gone, setGone] = useState(false);
  useEffect(() => {
    // only on first visit per session
    if (sessionStorage.getItem("mara-intro-played")) {
      setGone(true);
      onDone && onDone();
      return;
    }
    const t = setTimeout(() => {
      setGone(true);
      sessionStorage.setItem("mara-intro-played", "1");
      onDone && onDone();
    }, 2400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className={"intro-overlay" + (gone ? " gone" : "")}>
      <div className="intro-logo">
        MARA<span className="dot"></span>
      </div>
    </div>);

}

// scroll-trigger fade-up for elements with .fade-up
function useFadeUp() {
  useEffect(() => {
    const els = document.querySelectorAll(".fade-up");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) e.target.classList.add("in");});
    }, { threshold: 0.15 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

Object.assign(window, {
  Grain, Nav, Footer, IntroOverlay,
  SplitLine, PlayIcon, ArrowIcon, VideoStill, SpinBadge,
  useFadeUp
});
