/* Tsintsiva Digital — Revamp */
const { useState, useEffect, useRef, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "terracotta",
  "showProcess": true
}/*EDITMODE-END*/;

const ACCENT_MAP = {
  terracotta: { val: "oklch(0.70 0.14 45)", soft: "oklch(0.70 0.14 45 / 0.12)" },
  ochre:      { val: "oklch(0.78 0.13 80)", soft: "oklch(0.78 0.13 80 / 0.14)" },
  ember:      { val: "oklch(0.65 0.18 25)", soft: "oklch(0.65 0.18 25 / 0.14)" },
  electric:   { val: "oklch(0.78 0.18 220)", soft: "oklch(0.78 0.18 220 / 0.14)" },
  matcha:     { val: "oklch(0.72 0.13 140)", soft: "oklch(0.72 0.13 140 / 0.14)" }
};

const NAV_ITEMS = [
  { id: "sobre", label: "Sobre", href: "Sobre.html", external: true },
  { id: "servicos", label: "Serviços" },
  { id: "portfolio", label: "Portfólio" },
  { id: "abordagem", label: "Abordagem" },
  { id: "contactos", label: "Contactos" }
];

const ArrowUR = ({ size = 14 }) => (
  <svg className="arrow-icon" width={size} height={size} viewBox="0 0 14 14" fill="none">
    <path d="M3 11L11 3M11 3H4.5M11 3V9.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const ArrowR = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M2 8h11M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

/* -------------- NAV -------------- */
function Nav({ active }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const close = () => setMenuOpen(false);

  return (
    <>
      <nav className={"nav" + (scrolled ? " scrolled" : "")}>
        <a href="#header" className="nav-logo" onClick={close}>
          <span className="logo-mark" aria-hidden="true"></span>
          <span>tsintsiva<span className="nav-logo-muted">.</span></span>
        </a>
        <div className="nav-links">
          {NAV_ITEMS.map(item => (
            <a key={item.id} href={item.external ? item.href : `#${item.id}`}
               className={"nav-link" + (active === item.id ? " active" : "")}>
              {item.label}
            </a>
          ))}
        </div>
        <div className="nav-actions">
          <a href="#contactos" className="nav-cta">Iniciar projecto <ArrowUR /></a>
          <button type="button"
                  className={"nav-burger" + (menuOpen ? " open" : "")}
                  onClick={() => setMenuOpen(o => !o)}
                  aria-label={menuOpen ? "Fechar menu" : "Abrir menu"}
                  aria-expanded={menuOpen ? "true" : "false"}>
            <span></span><span></span><span></span>
          </button>
        </div>
      </nav>

      <div className={"mobile-nav" + (menuOpen ? " open" : "")} aria-hidden={menuOpen ? "false" : "true"}>
        {NAV_ITEMS.map(item => (
          <a key={item.id}
             href={item.external ? item.href : `#${item.id}`}
             className="mobile-nav-link"
             onClick={close}>
            {item.label}
          </a>
        ))}
        <div className="mobile-nav-footer">
          <a href="#contactos" className="mobile-nav-cta" onClick={close}>
            Iniciar projecto <ArrowUR />
          </a>
        </div>
      </div>
    </>
  );
}

/* -------------- HERO -------------- */
function Hero() {
  const [time, setTime] = useState("");
  useEffect(() => {
    const tick = () => {
      const d = new Date();
      const opts = { timeZone: "Africa/Maputo", hour: "2-digit", minute: "2-digit", hour12: false };
      setTime(d.toLocaleTimeString("pt-PT", opts));
    };
    tick();
    const id = setInterval(tick, 30000);
    return () => clearInterval(id);
  }, []);
  return (
    <header id="header" className="hero" data-screen-label="01 Hero">
      <div className="hero-grid" aria-hidden="true"></div>
      <div className="hero-inner">
        <div className="hero-meta">
          <span><span className="dot">●</span> &nbsp;Maputo, Moçambique &nbsp;·&nbsp; {time || "—"} CAT</span>
          <span>EST. 2018 &nbsp;/&nbsp; v.2026</span>
        </div>

        <span className="hero-eyebrow">
          <span className="hero-eyebrow-tag">001</span>
          Software houses · Marketing digital · Consultoria
        </span>

        <h1 className="hero-title">
          It's about<br/>
          <span className="ital">digital</span> — built<br/>
          <span className="stroke">in Moçambique.</span>
        </h1>

        <div className="hero-bottom">
          <p className="hero-desc">
            A <strong>Tsintsiva Digital</strong> desenha e constrói software, aplicações móveis e marcas
            para o mercado moçambicano. Produtos seguros, escaláveis e fáceis de usar — feitos para
            crescer com o seu negócio.
          </p>
          <div className="hero-ctas">
            <a href="#contactos" className="btn-primary">Iniciar projecto <ArrowUR /></a>
            <a href="#portfolio" className="btn-ghost">Ver trabalho <ArrowR /></a>
          </div>
        </div>
      </div>
    </header>
  );
}

/* -------------- MARQUEE -------------- */
function Marquee() {
  const items = [
    "Web Apps", "·", "Android", "·", "Marketing Digital", "·", "Consultoria",
    "·", "SEO", "·", "Social Media", "·", "E-mail Marketing", "·", "Brand Systems",
    "·", "UI / UX", "·", "Maputo → World"
  ];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {[...items, ...items, ...items, ...items].map((t, i) => <span key={i}>{t}</span>)}
      </div>
    </div>
  );
}

/* -------------- ABOUT -------------- */
function About() {
  return (
    <section id="sobre" className="section" data-screen-label="02 Sobre">
      <div className="section-head reveal">
        <div>
          <div className="section-label">Sobre / 02</div>
          <h2 className="section-title">
            Tecnologia <span className="ital">de raiz</span>,<br/>
            feita à medida.
          </h2>
        </div>
        <div>
          <p className="section-lede">
            Surgimos como resposta às necessidades do mercado moçambicano em tecnologias
            de informação. Hoje desenhamos sistemas, marcas e produtos digitais — desde
            a primeira linha até ao lançamento.
          </p>
          <a href="Sobre.html" className="about-readmore">
            Conhecer a história completa
            <ArrowUR />
          </a>
        </div>
      </div>

      <div className="about-grid reveal">
        <div className="about-cell">
          <span className="about-cell-num mono">/ 01 — História</span>
          <h3 className="about-cell-h">Nascidos em Maputo, pensados para escalar.</h3>
          <p className="about-cell-p">
            Especializados em websites, aplicações web e Android, marcas digitais e consultoria
            em software. Soluções construídas com as tecnologias mais recentes e estáveis disponíveis.
          </p>
        </div>
        <div className="about-cell">
          <span className="about-cell-num mono">/ 02 — Visão</span>
          <h3 className="about-cell-h">Ser referência em desenvolvimento de software em Moçambique.</h3>
          <p className="about-cell-p">
            Acreditamos que qualidade, simplicidade e fácil utilização não são opostos —
            são o mesmo princípio aplicado em camadas diferentes.
          </p>
        </div>
        <div className="about-cell">
          <span className="about-cell-num mono">/ 03 — Valores</span>
          <h3 className="about-cell-h">Cinco compromissos que guiam cada projecto.</h3>
          <div className="values-row">
            <span className="value-chip">Cliente</span>
            <span className="value-chip">Ética</span>
            <span className="value-chip">Respeito</span>
            <span className="value-chip">Qualidade</span>
            <span className="value-chip">Responsabilidade</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* -------------- SERVICES -------------- */
const SERVICES = [
  {
    n: "01",
    title: "Aplicações Web & Websites",
    desc: "Aplicações web e sites responsivos, desenhados para se adaptarem a qualquer dispositivo. Arquitectura limpa, performance e SEO técnico embutidos.",
    tags: ["React", "Next.js", "Node", "PostgreSQL", "Headless CMS"]
  },
  {
    n: "02",
    title: "Aplicações Android & Mobile",
    desc: "Desenvolvimento de aplicações Android nativas, templates reutilizáveis e integrações com APIs e pagamentos móveis locais.",
    tags: ["Kotlin", "Jetpack", "Firebase", "M-Pesa", "Offline-first"]
  },
  {
    n: "03",
    title: "Marketing Digital & SEO",
    desc: "Gestão de social media, e-mail marketing e SEO técnico. Estratégia de marca digital que liga produto a audiência.",
    tags: ["Meta Ads", "Google Ads", "SEO", "Analytics", "Newsletter"]
  },
  {
    n: "04",
    title: "Consultoria de Software",
    desc: "Auditorias técnicas, arquitectura de sistemas e acompanhamento de equipas internas. Decisões certas antes de escrever código.",
    tags: ["Auditoria", "Roadmap", "Architecture", "Mentoria"]
  }
];

function Services() {
  return (
    <section id="servicos" className="section" data-screen-label="03 Serviços">
      <div className="section-head reveal">
        <div>
          <div className="section-label">Serviços / 03</div>
          <h2 className="section-title">
            Quatro disciplinas,<br/>
            <span className="ital">um só</span> ponto de contacto.
          </h2>
        </div>
        <p className="section-lede">
          Cobrimos o ciclo completo — do primeiro protótipo à campanha de lançamento.
          Trabalhamos como equipa única, sem subcontratar o que define o seu produto.
        </p>
      </div>

      <div className="services reveal">
        {SERVICES.map(s => (
          <div className="service-row" key={s.n}>
            <span className="service-num">/ {s.n}</span>
            <div>
              <h3 className="service-title">{s.title}</h3>
              <div className="service-tags">
                {s.tags.map(t => <span key={t} className="service-tag">{t}</span>)}
              </div>
            </div>
            <p className="service-desc">{s.desc}</p>
            <div className="service-arrow" aria-hidden="true">
              <ArrowUR size={16} />
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* -------------- PORTFOLIO -------------- */
const PROJECTS = [
  {
    name: "maisUM",
    cat: "Mobile · Loyalty",
    desc: "Fidelização para pequenos negócios — pontos e recompensas, offline-first.",
    url: "https://maisum.tsintsivadigital.com/",
    year: "2025",
    size: "third",
    badge: "Lançamento",
    mark: "maisum"
  },
  {
    name: "a palavra",
    cat: "Android · Comunidade",
    desc: "Aplicação para grupos de orações e estudo bíblico.",
    year: "2024",
    size: "feat",
    badge: "Em produção",
    mark: "palavra"
  },
  {
    name: "karaoke",
    cat: "Web + Mobile · Eventos",
    desc: "Gestão de filas de karaoke em tempo real.",
    year: "2024",
    size: "half",
    badge: "Live",
    mark: "karaoke"
  },
  {
    name: "nikumile",
    cat: "Android · Civic-tech",
    desc: "Recuperação de pessoas e documentos perdidos.",
    year: "2023",
    size: "third",
    badge: "Beta",
    mark: "nikumile"
  },
  {
    name: "Kaluta app",
    cat: "Mobile · Fintech pessoal",
    desc: "Gestão financeira pessoal e controlo de despesas.",
    year: "2025",
    size: "third",
    badge: "Em produção",
    mark: "kaluta"
  }
];

const MARKS = {
  palavra: (
    <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M20 28 L60 22 L60 100 L20 96 Z" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round"/>
      <path d="M100 28 L60 22 L60 100 L100 96 Z" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round"/>
      <path d="M60 22 L60 100" stroke="currentColor" strokeWidth="2.5"/>
      <path d="M30 42 L50 39 M30 52 L50 49 M30 62 L50 59" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" opacity="0.55"/>
      <path d="M70 39 L90 42 M70 49 L90 52 M70 59 L90 62" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" opacity="0.55"/>
      <circle cx="60" cy="80" r="3.5" fill="currentColor"/>
    </svg>
  ),
  karaoke: (
    <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="46" y="20" width="28" height="52" rx="14" stroke="currentColor" strokeWidth="2.5"/>
      <path d="M34 60 C34 80 46 92 60 92 C74 92 86 80 86 60" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
      <path d="M60 92 L60 104 M48 104 L72 104" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
      <path d="M52 35 L68 35 M52 45 L68 45 M52 55 L68 55" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" opacity="0.55"/>
      <circle cx="22" cy="50" r="3" fill="currentColor"/>
      <circle cx="98" cy="50" r="3" fill="currentColor"/>
      <path d="M14 42 Q18 50 14 58 M106 42 Q102 50 106 58" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" opacity="0.55"/>
    </svg>
  ),
  nikumile: (
    <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M60 20 C42 20 28 33 28 50 C28 70 60 100 60 100 C60 100 92 70 92 50 C92 33 78 20 60 20 Z" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round"/>
      <circle cx="60" cy="50" r="13" stroke="currentColor" strokeWidth="2"/>
      <path d="M68 58 L78 68" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <circle cx="22" cy="88" r="2.5" fill="currentColor" opacity="0.5"/>
      <circle cx="100" cy="92" r="2.5" fill="currentColor" opacity="0.5"/>
      <circle cx="18" cy="36" r="2" fill="currentColor" opacity="0.35"/>
    </svg>
  ),
  kaluta: (
    <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="20" y="40" width="80" height="60" rx="8" stroke="currentColor" strokeWidth="2.5"/>
      <path d="M20 56 L100 56" stroke="currentColor" strokeWidth="2.5"/>
      <rect x="68" y="68" width="22" height="16" rx="4" stroke="currentColor" strokeWidth="2"/>
      <circle cx="79" cy="76" r="3" fill="currentColor"/>
      <path d="M32 30 L88 30 L88 40" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <path d="M30 84 L34 80 L42 86 L52 74 L60 80" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" opacity="0.6"/>
    </svg>
  ),
  maisum: (
    <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="60" cy="60" r="38" stroke="currentColor" strokeWidth="2.5"/>
      <path d="M60 38 L62.5 54 L78 56 L66 66 L70 82 L60 73 L50 82 L54 66 L42 56 L57.5 54 Z" fill="currentColor" opacity="0.85"/>
      <path d="M22 22 L26 26 M98 22 L94 26 M22 98 L26 94 M98 98 L94 94" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.5"/>
      <text x="60" y="112" textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill="currentColor" opacity="0.6" letterSpacing="0.08em">+1</text>
    </svg>
  )
};

function Portfolio() {
  return (
    <section id="portfolio" className="section" data-screen-label="04 Portfólio">
      <div className="section-head reveal">
        <div>
          <div className="section-label">Portfólio / 04</div>
          <h2 className="section-title">
            Trabalho recente,<br/>
            <span className="ital">resultados</span> reais.
          </h2>
        </div>
        <p className="section-lede">
          Uma selecção dos produtos que construímos — apps Android, plataformas web e ferramentas
          de gestão para clientes em Moçambique. Cada um começou com uma pergunta de negócio.
        </p>
      </div>

      <div className="portfolio-grid reveal">
        {PROJECTS.map((p, i) => (
          <article key={i} className={`portfolio-card ${p.size}`}>
            <div className="portfolio-thumb">
              <div className="portfolio-mark">{MARKS[p.mark]}</div>
            </div>
            <span className="portfolio-badge">{p.badge}</span>
            <div className="portfolio-meta">
              <div className="portfolio-meta-left">
                <span className="portfolio-cat">{p.cat}</span>
                <span className="portfolio-name">{p.name}</span>
                <span className="portfolio-desc">{p.desc}</span>
                {p.url && (
                  <a href={p.url} target="_blank" rel="noopener noreferrer" className="portfolio-link">
                    Abrir app <ArrowUR size={12} />
                  </a>
                )}
              </div>
              <span className="portfolio-year">{p.year}</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* -------------- APPROACH -------------- */
const STEPS = [
  { n: "01", h: "Descoberta", p: "Entendemos o negócio, o utilizador e o mercado. Definimos o problema antes da solução." },
  { n: "02", h: "Desenho", p: "Arquitectura, fluxos e identidade. Protótipos navegáveis antes de qualquer linha de código." },
  { n: "03", h: "Construção", p: "Sprints curtos, código revisto, deploys contínuos. Cada semana entrega algo testável." },
  { n: "04", h: "Lançamento", p: "Lançamento, marketing digital, monitoria e iteração. Acompanhamos depois do go-live." }
];

function Approach() {
  return (
    <section id="abordagem" className="section" data-screen-label="05 Abordagem" style={{ paddingTop: 80, paddingBottom: 80 }}>
      <div className="section-head reveal">
        <div>
          <div className="section-label">Abordagem / 05</div>
          <h2 className="section-title">
            Como <span className="ital">trabalhamos</span>.
          </h2>
        </div>
        <p className="section-lede">
          Um processo simples, com quatro etapas. Sem caixas pretas, sem surpresas no final.
        </p>
      </div>

      <div className="approach reveal">
        {STEPS.map(s => (
          <div className="approach-step" key={s.n}>
            <span className="approach-step-num">{s.n} / 04</span>
            <h3 className="approach-step-h">{s.h}</h3>
            <p className="approach-step-p">{s.p}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* -------------- CONTACT -------------- */
function Contact() {
  const [form, setForm] = useState({ name: "", email: "", company: "", service: "Aplicação Web", message: "" });
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);

  const onChange = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const valid = form.name.trim() && form.email.includes("@") && form.message.trim().length > 4;

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || sending) return;
    setSending(true);
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          access_key: "91accc3e-8b58-4b0d-880e-9f256e62d841",
          subject: "Novo contacto — " + form.service,
          from_name: form.name,
          email: form.email,
          empresa: form.company,
          servico: form.service,
          mensagem: form.message
        })
      });
      if (res.ok) {
        setSent(true);
        setForm({ name: "", email: "", company: "", service: "Aplicação Web", message: "" });
      } else {
        setSent("error");
      }
    } catch {
      setSent("error");
    } finally {
      setSending(false);
      setTimeout(() => setSent(false), 7000);
    }
  };

  return (
    <section id="contactos" className="contact" data-screen-label="06 Contactos">
      <div className="contact-left reveal">
        <div className="section-label">Contactos / 06</div>
        <h2 className="contact-headline">
          Tem uma ideia? <br/>
          <span className="ital">Conversemos.</span>
        </h2>

        <div className="contact-info">
          <div className="contact-info-item">
            <span className="contact-info-label">Endereço</span>
            <span className="contact-info-val">Av. Vladmir Lenine, nº 548 R/C<br/>Central B · Maputo · Moçambique</span>
          </div>
          <div className="contact-info-item">
            <span className="contact-info-label">Horário</span>
            <span className="contact-info-val">Seg — Sex · 08:30 — 19:00<br/>Sáb · 09:00 — 12:30</span>
          </div>
          <div className="contact-info-item">
            <span className="contact-info-label">Telefone</span>
            <span className="contact-info-val"><a href="tel:+258876460553">+258 87 646 0553</a></span>
          </div>
          <div className="contact-info-item">
            <span className="contact-info-label">E-mail</span>
            <span className="contact-info-val">
              <a href="mailto:comercial@tsintsivadigital.com">comercial@tsintsivadigital.com</a><br/>
              <a href="mailto:info@tsintsivadigital.com">info@tsintsivadigital.com</a>
            </span>
          </div>
          <div className="contact-info-item">
            <span className="contact-info-label">Social</span>
            <span className="contact-info-val">
              <a href="https://www.linkedin.com/company/tsintsivadigital/" target="_blank" rel="noopener noreferrer">LinkedIn</a> &nbsp;·&nbsp;
              <a href="https://m.facebook.com/Tsintsiva-Digital-383498635362137/" target="_blank" rel="noopener noreferrer">Facebook</a> &nbsp;·&nbsp;
              <a href="https://www.instagram.com/tsintsivadigitalmz/" target="_blank" rel="noopener noreferrer">Instagram</a>
            </span>
          </div>
        </div>
      </div>

      <form className="contact-form reveal" onSubmit={submit}>
        <div className="form-row">
          <div className="form-field">
            <label className="form-label" htmlFor="f-name">Nome</label>
            <input id="f-name" className="form-input" type="text" value={form.name} onChange={onChange("name")} placeholder="O seu nome" />
          </div>
          <div className="form-field">
            <label className="form-label" htmlFor="f-email">E-mail</label>
            <input id="f-email" className="form-input" type="email" value={form.email} onChange={onChange("email")} placeholder="voce@empresa.co.mz" />
          </div>
        </div>
        <div className="form-row">
          <div className="form-field">
            <label className="form-label" htmlFor="f-company">Empresa</label>
            <input id="f-company" className="form-input" type="text" value={form.company} onChange={onChange("company")} placeholder="Opcional" />
          </div>
          <div className="form-field">
            <label className="form-label" htmlFor="f-service">Serviço</label>
            <select id="f-service" className="form-select" value={form.service} onChange={onChange("service")}>
              <option>Aplicação Web</option>
              <option>Aplicação Android</option>
              <option>Marketing Digital</option>
              <option>Consultoria</option>
              <option>Outro</option>
            </select>
          </div>
        </div>
        <div className="form-field">
          <label className="form-label" htmlFor="f-message">Mensagem</label>
          <textarea id="f-message" className="form-textarea" value={form.message} onChange={onChange("message")} placeholder="Conte-nos sobre o seu projecto…" />
        </div>
        {sent === true ? (
          <div className="form-success mono">✓ Mensagem enviada — respondemos em 24h.</div>
        ) : sent === "error" ? (
          <div className="form-error">✗ Erro ao enviar. Contacte-nos directamente por e-mail.</div>
        ) : (
          <button className="form-submit" type="submit" disabled={!valid || sending}>
            {sending ? "A enviar…" : "Enviar mensagem"} <ArrowUR />
          </button>
        )}
      </form>
    </section>
  );
}

/* -------------- FOOTER -------------- */
function Footer() {
  return (
    <footer className="footer" data-screen-label="07 Footer">
      <div className="footer-inner">
        <div className="footer-big">
          <span className="logo-mark" aria-hidden="true"></span>
          <span>tsintsiva<span className="ital">.</span></span>
        </div>
        <div className="footer-bottom">
          <span>© 2018 — 2026 Tsintsiva Digital, LDA · Todos os direitos reservados.</span>
          <div className="footer-bottom-right">
            <a href="politica-de-privacidade.html">Política de privacidade</a>
            <a href="termos.html">Termos</a>
            <a href="#header">Voltar ao topo ↑</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* -------------- ACTIVE SECTION OBSERVER -------------- */
function useActiveSection() {
  const [active, setActive] = useState("");
  useEffect(() => {
    const ids = NAV_ITEMS.map(i => i.id);
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: "-30% 0px -60% 0px", threshold: 0 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
  return active;
}

/* -------------- REVEAL OBSERVER -------------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add("in"); });
    }, { rootMargin: "0px 0px -10% 0px", threshold: 0.05 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* -------------- APP -------------- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const active = useActiveSection();
  useReveal();

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    const a = ACCENT_MAP[t.accent] || ACCENT_MAP.terracotta;
    document.documentElement.style.setProperty("--accent", a.val);
    document.documentElement.style.setProperty("--accent-soft", a.soft);
    try {
      localStorage.setItem("tsintsiva-theme", JSON.stringify({
        theme: t.theme, accent: a.val, accentSoft: a.soft
      }));
    } catch (e) {}
  }, [t.theme, t.accent]);

  return (
    <>
      <Nav active={active} />
      <Hero />
      <Marquee />
      <About />
      <Services />
      <Portfolio />
      {t.showProcess && <Approach />}
      <Contact />
      <Footer />

      <TweaksPanel>
        <TweakSection label="Tema" />
        <TweakRadio label="Modo" value={t.theme}
                    options={["dark", "light", "cream"]}
                    onChange={(v) => setTweak("theme", v)} />
        <TweakSection label="Cor de Acento" />
        <TweakColor label="Acento" value={ACCENT_MAP[t.accent]?.val}
                    options={Object.values(ACCENT_MAP).map(a => a.val)}
                    onChange={(v) => {
                      const key = Object.keys(ACCENT_MAP).find(k => ACCENT_MAP[k].val === v);
                      if (key) setTweak("accent", key);
                    }} />
        <TweakSection label="Secções" />
        <TweakToggle label="Mostrar Abordagem" value={t.showProcess}
                     onChange={(v) => setTweak("showProcess", v)} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
