/* Titans site: shared pieces used by both the mobile and desktop versions */
(() => {
const C = window.TitansContent;
const ASSET_BASE = '../assets/';
const ASSET = { mono: ASSET_BASE + 'titans-monogram-gold.jpg', wm: ASSET_BASE + 'titans-wordmark-white.png', forest: ASSET_BASE + 'titans-wordmark-forest.png', founder: ASSET_BASE + 'titans-fundador.png' };
const waLink = (msg) => {
  const theme = (window.TitansTema && window.TitansTema.current) ? window.TitansTema.current : '';
  const finalMsg = theme ? `${msg} [ref:${theme}]` : msg;
  return `https://wa.me/${C.wa.number}?text=${encodeURIComponent(finalMsg)}`;
};

function Ico({ name, size = 18, stroke = 1.6 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = '';
    const el = document.createElement('i');
    el.setAttribute('data-lucide', name);
    ref.current.appendChild(el);
    window.lucide.createIcons({ attrs: { 'stroke-width': stroke, width: size, height: size } });
  }, [name, size, stroke]);
  return <span ref={ref} aria-hidden="true" style={{ display: 'inline-flex', width: size, height: size, flex: 'none' }}></span>;
}

function WAGlyph({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="currentColor" aria-hidden="true" style={{ display: 'block', flex: 'none' }}>
      <path d="M16.03 4C9.4 4 4 9.39 4 16.02c0 2.12.56 4.18 1.62 6L4 28l6.13-1.6a12 12 0 0 0 5.9 1.5h.01c6.62 0 12.02-5.39 12.02-12.02C28.06 9.39 22.66 4 16.03 4Zm0 21.7h-.01a9.9 9.9 0 0 1-5.05-1.38l-.36-.21-3.64.95.97-3.55-.24-.37a9.86 9.86 0 0 1-1.51-5.25c0-5.46 4.45-9.9 9.92-9.9 2.65 0 5.14 1.03 7.01 2.9a9.84 9.84 0 0 1 2.9 7.01c0 5.46-4.45 9.9-9.91 9.9Zm5.44-7.42c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.16-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.77-1.66-2.07-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.07-.15-.67-1.61-.92-2.21-.24-.58-.49-.5-.67-.51l-.57-.01c-.2 0-.52.07-.79.37-.27.3-1.04 1.01-1.04 2.47s1.06 2.87 1.21 3.07c.15.2 2.09 3.2 5.07 4.49.71.3 1.26.49 1.69.62.71.23 1.36.2 1.87.12.57-.08 1.76-.72 2-1.41.25-.69.25-1.29.17-1.41-.07-.12-.27-.2-.57-.35Z" />
    </svg>
  );
}

function WAButton({ children = C.cta, msg = C.msgs.menu, quiet = false, small = false, id, tabIndex }) {
  const [curTheme, setCurTheme] = React.useState(window.TitansTema ? window.TitansTema.current : '');
  React.useEffect(() => {
    const h = (e) => setCurTheme(e.detail);
    window.addEventListener('titans-tema', h);
    return () => window.removeEventListener('titans-tema', h);
  }, []);
  return (
    <a id={id} tabIndex={tabIndex} className={'btn' + (quiet ? ' btn-quiet' : '') + (small ? ' btn-sm' : '')} href={waLink(msg)} target="_blank" rel="noopener noreferrer">
      <WAGlyph size={small ? 18 : 20} /><span>{children}</span>
    </a>
  );
}

function Logo({ href = 'index.html' }) {
  return (
    <a className="logo" href={href} aria-label="Titans, página inicial">
      <img className="mono" src={ASSET.mono} alt="" />
      <img className="wm" src={ASSET.wm} alt="" />
    </a>
  );
}

function Skip() { return <a className="skip" href="#conteudo">Pular para o conteúdo</a>; }

/* Development only: in-menu theme switch. Mirrors the floating one from theme.js. */
function ThemeSwitch() {
  const T = window.TitansTema;
  const [cur, setCur] = React.useState(T ? T.current : 'a');
  React.useEffect(() => {
    const h = (e) => setCur(e.detail);
    window.addEventListener('titans-tema', h);
    return () => window.removeEventListener('titans-tema', h);
  }, []);
  if (!T) return null;
  return (
    <div className="tema-switch" role="group" aria-label="Tema do site (desenvolvimento)">
      <span>Tema</span>
      {Object.keys(T.list).map((k) => (
        <button key={k} type="button" title={T.list[k].name} aria-pressed={cur === k} onClick={() => T.set(k)}>{k.toUpperCase()}</button>
      ))}
    </div>
  );
}

/* The one choreographed moment: a night conversation that ends in a booking. Plays once when seen. */
function ChatDemo() {
  const { script, header, day, done: doneLabel, replay } = C.home.chat;
  const rootRef = React.useRef(null);
  const bodyRef = React.useRef(null);
  const [started, setStarted] = React.useState(false);
  const [run, setRun] = React.useState(0);
  const [shown, setShown] = React.useState(0);
  const [typing, setTyping] = React.useState(false);

  React.useEffect(() => {
    if (!('IntersectionObserver' in window)) { setStarted(true); return; }
    const o = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setStarted(true); o.disconnect(); } }, { threshold: 0.35 });
    if (rootRef.current) o.observe(rootRef.current);
    return () => o.disconnect();
  }, []);

  React.useEffect(() => {
    if (!started) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setShown(script.length); return; }
    const timers = [];
    setShown(0); setTyping(false);
    let d = 500;
    script.forEach((m, i) => {
      if (m.from === 'out') {
        timers.push(setTimeout(() => setTyping(true), d)); d += 1100;
        timers.push(setTimeout(() => { setTyping(false); setShown(i + 1); }, d)); d += 700;
      } else {
        timers.push(setTimeout(() => setShown(i + 1), d)); d += 1000;
      }
    });
    return () => timers.forEach(clearTimeout);
  }, [started, run]);

  React.useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [shown, typing]);
  const finished = shown >= script.length;

  return (
    <div className="chat" ref={rootRef}>
      <div className="chat-head">
        <img src={ASSET.mono} alt="" />
        <div>
          <div className="chat-name">{header}</div>
          <div className="chat-status" aria-live="polite">{typing ? 'digitando…' : 'online'}</div>
        </div>
      </div>
      <div className="chat-body" ref={bodyRef}>
        <div className="chat-day">{day}</div>
        {script.slice(0, shown).map((m, i) => (
          <div key={run + '-' + i} className={'bub' + (m.from === 'out' ? ' out' : '')}>
            {m.text}
            <div className="bub-meta">{m.t}{m.from === 'out' && <Ico name="check-check" size={13} />}</div>
          </div>
        ))}
        {typing && <div className="typing" aria-hidden="true"><span></span><span></span><span></span></div>}
        {finished && (
          <div className="chat-done">
            <span className="chip"><Ico name="calendar-check" size={13} /> {doneLabel}</span>
            <button className="replay" type="button" onClick={() => setRun((r) => r + 1)}>{replay}</button>
          </div>
        )}
      </div>
    </div>
  );
}

/* Legal layout: same API the existing Privacidade.jsx / Termos.jsx expect, so their text is reused verbatim. */
function LegalLayout({ title, updated, note, toc, ctaMsg, children }) {
  return (
    <article className="legal">
      <header className="sec page-head" id="page-head">
        <div className="wrap">
          <h1 className="h1">{title}</h1>
          <p className="note" style={{ margin: 0 }}>Última atualização: {updated}</p>
        </div>
      </header>
      <div className="sec legal-body">
        <div className="wrap legal-grid">
          {toc && toc.length > 0 && (
            <nav className="toc" aria-label="Nesta página">
              <p className="toc-t">Nesta página</p>
              <ol>{toc.map((t) => <li key={t.id}><a href={'#' + t.id}>{t.label}</a></li>)}</ol>
            </nav>
          )}
          <div className="legal-text">
            {note && <p className="legal-note">{note}</p>}
            {children}
            <p className="legal-help">Ficou com dúvida? <a href={waLink(ctaMsg || C.msgs.menu)} target="_blank" rel="noopener noreferrer">Fale com a gente no WhatsApp</a>.</p>
          </div>
        </div>
      </div>
    </article>
  );
}
function LegalSection({ id, n, title, children }) {
  return <section id={id} className="legal-sec"><h2 className="legal-h"><span className="legal-n">{n}</span>{title}</h2>{children}</section>;
}
const LP = ({ children }) => <p className="legal-p">{children}</p>;
const LList = ({ children }) => <ul className="legal-list">{children}</ul>;
const LLI = ({ children }) => <li>{children}</li>;
const LStrong = ({ children }) => <strong>{children}</strong>;
const LBracket = ({ children }) => <span className="legal-bracket">{children}</span>;

Object.assign(window, { LegalLayout, LegalSection, LP, LList, LLI, LStrong, LBracket });
window.SiteKit = { C, ASSET, waLink, Ico, WAGlyph, WAButton, Logo, Skip, ThemeSwitch, ChatDemo };
})();
