// ============================================================
// AgenticX — Central Legal
// Rotas canônicas: /legal, /privacidade, /termos e /exclusao-de-dados.
// O conteúdo público dos três documentos vem das versões aprovadas em
// docs/legal/*-v2.md, servidas pelo mesmo domínio da aplicação.
// ============================================================

const LEGAL_CONTACT = 'contato@agenticx.com.br';
const LEGAL_UPDATED = '25 de agosto de 2026';
const LEGAL_CANONICAL_BASE = 'https://landing.agenticx.com.br';

const LEGAL_DOCS = [
  {
    id: 'legal',
    hash: 'legal',
    path: '/legal',
    label: 'Central Legal',
    title: 'Central Legal',
    objective: 'Informações legais e documentos de uso da plataforma.',
    body: [
      'Aqui você encontra, em acesso público e direto, os documentos que explicam o tratamento de dados, as regras de uso da AgenticX e como solicitar exclusão ou interrupção de mensagens.',
      'Os três documentos abaixo são as versões aprovadas para implementação e publicação. As regras de terceiros, especialmente Meta e WhatsApp, podem mudar; os links oficiais ficam disponíveis dentro dos documentos.',
    ],
    isHub: true,
  },
  {
    id: 'privacidade',
    hash: 'privacidade',
    path: '/privacidade',
    sourcePath: '/docs/legal/politica-de-privacidade-v2.md',
    label: 'Política de Privacidade',
    title: 'Política de Privacidade',
    objective: 'Como tratamos dados pessoais, integrações e solicitações de titulares.',
    isPublic: true,
  },
  {
    id: 'termos',
    hash: 'termos',
    path: '/termos',
    sourcePath: '/docs/legal/termos-de-servico-v2.md',
    label: 'Termos de Serviço',
    title: 'Termos de Serviço',
    objective: 'Regras de uso, responsabilidades e condições da plataforma.',
    isPublic: true,
  },
  {
    id: 'exclusao-de-dados',
    hash: 'exclusao-de-dados',
    path: '/exclusao-de-dados',
    sourcePath: '/docs/legal/exclusao-de-dados-v2.md',
    label: 'Exclusão de Dados',
    title: 'Exclusão de Dados',
    objective: 'Instruções para exclusão, anonimização, bloqueio e interrupção de mensagens.',
    isPublic: true,
  },
  {
    id: 'lgpd',
    hash: 'lgpd',
    label: 'LGPD',
    title: 'LGPD — Proteção de Dados',
    objective: 'Direitos dos titulares e canal para solicitações sobre dados.',
    body: [
      'Atuamos em conformidade com a Lei Geral de Proteção de Dados Pessoais (LGPD), adotando práticas para proteger dados pessoais e respeitar os direitos dos titulares. O titular pode solicitar acesso, correção, confirmação de tratamento, portabilidade, anonimização, bloqueio ou eliminação de dados, conforme aplicável.',
      'Quando tratamos dados em nome de clientes, seguimos as instruções contratuais e aplicamos medidas de segurança, confidencialidade e governança. Solicitações relacionadas à LGPD serão avaliadas conforme a legislação, a natureza do dado e a relação com o serviço contratado.',
    ],
    finalCall: {
      label: 'Exercer seus direitos',
      email: LEGAL_CONTACT,
      prefix: 'Envie uma solicitação pelo canal de privacidade informado pela empresa.',
    },
  },
  {
    id: 'seguranca',
    hash: 'seguranca',
    label: 'Segurança',
    title: 'Segurança da Informação',
    objective: 'Medidas para proteger dados, acessos e integrações.',
    body: [
      'Adotamos medidas técnicas e organizacionais proporcionais ao risco para proteger dados, acessos e integrações, incluindo controle de acesso, proteção de credenciais, sessões server-side, registros de segurança, monitoramento e boas práticas de infraestrutura.',
      'Embora nenhum ambiente digital seja isento de riscos, trabalhamos para reduzir vulnerabilidades, limitar acessos desnecessários e responder a incidentes de forma responsável. Também recomendamos que os usuários protejam suas credenciais e restrinjam permissões conforme a necessidade.',
    ],
    finalCall: {
      label: 'Comunicar uma questão de segurança',
      email: LEGAL_CONTACT,
      prefix: 'Utilize o canal de contato indicado nos documentos publicados.',
    },
  },
];

const LEGAL_HASHES = LEGAL_DOCS.map((doc) => doc.hash);
const LEGAL_PATHS = LEGAL_DOCS.reduce((paths, doc) => {
  if (doc.path) paths[doc.path] = doc.id;
  return paths;
}, {});

function legalHref(doc) {
  return doc.path || ('#' + doc.hash);
}

function isExternalLegalLink(href) {
  return /^https?:\/\//i.test(href);
}

function renderLegalInline(text, keyPrefix) {
  const pattern = new RegExp('(\\[[^\\]]+\\]\\([^)]+\\)|\\*\\*[^*]+\\*\\*|\\x60[^\\x60]+\\x60|\\*[^*]+\\*)', 'g');
  const nodes = [];
  let cursor = 0;
  let match;

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > cursor) nodes.push(text.slice(cursor, match.index));
    const token = match[0];
    const keyBase = keyPrefix + '-' + match.index;

    if (token.charAt(0) === '[') {
      const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
      if (link) {
        const href = link[2];
        nodes.push(
          <a
            key={keyBase + '-link'}
            href={href}
            target={isExternalLegalLink(href) ? '_blank' : undefined}
            rel={isExternalLegalLink(href) ? 'noopener noreferrer' : undefined}
            className="text-forest underline decoration-forest/40 underline-offset-2 hover:decoration-forest"
          >
            {link[1]}
          </a>,
        );
      } else {
        nodes.push(token);
      }
    } else if (token.indexOf('**') === 0) {
      nodes.push(<strong key={keyBase + '-strong'}>{token.slice(2, -2)}</strong>);
    } else if (token.charAt(0) === '*') {
      nodes.push(<em key={keyBase + '-em'}>{token.slice(1, -1)}</em>);
    } else if (token.charAt(0) === String.fromCharCode(96)) {
      nodes.push(
        <code key={keyBase + '-code'} className="rounded bg-sage/70 px-1.5 py-0.5 text-[0.9em] text-forest">
          {token.slice(1, -1)}
        </code>,
      );
    }
    cursor = match.index + token.length;
  }

  if (cursor < text.length) nodes.push(text.slice(cursor));
  return nodes;
}

function parseLegalTableRow(line) {
  return line
    .trim()
    .replace(/^\|/, '')
    .replace(/\|$/, '')
    .split('|')
    .map((cell) => cell.trim());
}

function isLegalTableSeparator(line) {
  return /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(line.trim());
}

function isLegalListLine(line) {
  return /^\s*(?:[-*]\s+|\d+\.\s+)/.test(line);
}

function parseLegalMarkdown(markdown) {
  const lines = markdown.replace(/\r\n/g, '\n').split('\n');
  const tokens = [];
  let index = 0;
  let skippedTitle = false;

  while (index < lines.length) {
    const raw = lines[index];
    const line = raw.trim();

    if (!line) {
      index += 1;
      continue;
    }

    if (line === '---') {
      index += 1;
      continue;
    }

    const heading = line.match(/^(#{1,6})\s+(.+)$/);
    if (heading) {
      const level = heading[1].length;
      if (level === 1 && !skippedTitle) {
        skippedTitle = true;
      } else {
        tokens.push({ type: 'heading', level: Math.min(level, 4), text: heading[2] });
      }
      index += 1;
      continue;
    }

    if (line.indexOf('|') >= 0 && index + 1 < lines.length && isLegalTableSeparator(lines[index + 1])) {
      const header = parseLegalTableRow(line);
      const rows = [];
      index += 2;
      while (index < lines.length && lines[index].trim().indexOf('|') >= 0 && lines[index].trim()) {
        rows.push(parseLegalTableRow(lines[index]));
        index += 1;
      }
      tokens.push({ type: 'table', header, rows });
      continue;
    }

    const listMatch = line.match(/^([-*]|\d+\.)\s+(.+)$/);
    if (listMatch) {
      const ordered = /^\d+\./.test(listMatch[1]);
      const items = [];
      while (index < lines.length) {
        const itemLine = lines[index].trim();
        const itemMatch = itemLine.match(/^([-*]|\d+\.)\s+(.+)$/);
        if (!itemMatch || /^\d+\./.test(itemMatch[1]) !== ordered) break;
        let itemText = itemMatch[2];
        index += 1;
        while (index < lines.length) {
          const continuation = lines[index];
          if (!continuation.trim()) break;
          if (isLegalListLine(continuation) || /^(#{1,6})\s+/.test(continuation.trim())) break;
          itemText += ' ' + continuation.trim();
          index += 1;
        }
        items.push(itemText);
        while (index < lines.length && !lines[index].trim()) index += 1;
      }
      tokens.push({ type: ordered ? 'ordered-list' : 'unordered-list', items });
      continue;
    }

    if (line.charAt(0) === '>') {
      const quote = [];
      while (index < lines.length && lines[index].trim().charAt(0) === '>') {
        quote.push(lines[index].trim().replace(/^>\s?/, ''));
        index += 1;
      }
      tokens.push({ type: 'quote', text: quote.join(' ') });
      continue;
    }

    const paragraph = [line];
    index += 1;
    while (index < lines.length) {
      const next = lines[index].trim();
      if (!next || next === '---' || /^(#{1,6})\s+/.test(next) || isLegalListLine(next)) break;
      if (next.indexOf('|') >= 0 && index + 1 < lines.length && isLegalTableSeparator(lines[index + 1])) break;
      paragraph.push(next);
      index += 1;
    }
    tokens.push({ type: 'paragraph', text: paragraph.join(' ') });
  }

  return tokens;
}

const LegalMarkdown = ({ markdown }) => {
  const tokens = React.useMemo(() => parseLegalMarkdown(markdown), [markdown]);

  return (
    <div className="mt-8 space-y-6">
      {tokens.map((token, index) => {
        const key = 'legal-token-' + index;
        if (token.type === 'heading') {
          const Tag = token.level <= 2 ? 'h2' : 'h3';
          const headingClass = token.level <= 2 ? 'pt-4 text-2xl sm:text-3xl' : 'pt-2 text-xl sm:text-2xl';
          return (
            <Tag key={key} className={headingClass + ' font-medium leading-tight text-black'}>
              {renderLegalInline(token.text, key)}
            </Tag>
          );
        }
        if (token.type === 'paragraph') {
          const isMeta = /^\*\*(?:Versão|Data|URL|Empresa|Responsável|Contato|Canal)/i.test(token.text);
          return (
            <p key={key} className={(isMeta ? 'text-sm text-slate' : 'text-[0.98rem] text-black/80') + ' leading-relaxed'}>
              {renderLegalInline(token.text, key)}
            </p>
          );
        }
        if (token.type === 'quote') {
          return (
            <blockquote key={key} className="border-l-2 border-teal pl-5 text-sm italic leading-relaxed text-slate">
              {renderLegalInline(token.text, key)}
            </blockquote>
          );
        }
        if (token.type === 'table') {
          return (
            <div key={key} className="overflow-x-auto rounded-2xl border border-line">
              <table className="min-w-full border-collapse text-left text-sm">
                <thead className="bg-sage/60 text-forest">
                  <tr>
                    {token.header.map((cell, cellIndex) => (
                      <th key={key + '-head-' + cellIndex} scope="col" className="border-b border-line px-4 py-3 font-semibold">
                        {renderLegalInline(cell, key + '-head-' + cellIndex)}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {token.rows.map((row, rowIndex) => (
                    <tr key={key + '-row-' + rowIndex} className="align-top even:bg-[#FAFAF8]">
                      {token.header.map((_, cellIndex) => (
                        <td key={key + '-cell-' + rowIndex + '-' + cellIndex} className="border-b border-line px-4 py-3 leading-relaxed text-black/80 last:border-b-0">
                          {renderLegalInline(row[cellIndex] || '', key + '-cell-' + rowIndex + '-' + cellIndex)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          );
        }
        const ListTag = token.type === 'ordered-list' ? 'ol' : 'ul';
        const listClass = token.type === 'ordered-list' ? 'list-decimal' : 'list-disc';
        return (
          <ListTag key={key} className={listClass + ' ml-5 space-y-2 text-[0.98rem] leading-relaxed text-black/80'}>
            {token.items.map((item, itemIndex) => (
              <li key={key + '-item-' + itemIndex} className="pl-1">
                {renderLegalInline(item, key + '-item-' + itemIndex)}
              </li>
            ))}
          </ListTag>
        );
      })}
    </div>
  );
};

function updateLegalMetadata(doc) {
  const path = doc.path || '/legal';
  const title = doc.title + ' — AgenticX';
  const description = doc.objective || 'Informações legais públicas da AgenticX.';
  document.title = title;

  const descriptionMeta = document.querySelector('meta[name="description"]');
  if (descriptionMeta) descriptionMeta.setAttribute('content', description);

  const canonical = document.querySelector('link[rel="canonical"]');
  if (canonical) canonical.setAttribute('href', LEGAL_CANONICAL_BASE + path);

  const ogTitle = document.querySelector('meta[property="og:title"]');
  if (ogTitle) ogTitle.setAttribute('content', title);
  const ogDescription = document.querySelector('meta[property="og:description"]');
  if (ogDescription) ogDescription.setAttribute('content', description);
  const ogUrl = document.querySelector('meta[property="og:url"]');
  if (ogUrl) ogUrl.setAttribute('content', LEGAL_CANONICAL_BASE + path);
}

const LegalPage = ({ activeHash }) => {
  const active = (activeHash || 'legal').replace(/^#/, '');
  const doc = LEGAL_DOCS.find((item) => item.hash === active) || LEGAL_DOCS[0];
  const [markdown, setMarkdown] = React.useState('');
  const [loading, setLoading] = React.useState(Boolean(doc.sourcePath));
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    updateLegalMetadata(doc);
    let cancelled = false;

    if (!doc.sourcePath) {
      setMarkdown('');
      setLoading(false);
      setError('');
      return () => { cancelled = true; };
    }

    setMarkdown('');
    setLoading(true);
    setError('');
    fetch(doc.sourcePath, { cache: 'no-store' })
      .then((response) => {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.text();
      })
      .then((text) => {
        if (!cancelled) {
          setMarkdown(text);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setLoading(false);
          setError('Não foi possível carregar este documento agora. Tente recarregar a página.');
        }
      });

    return () => { cancelled = true; };
  }, [doc.id, doc.path, doc.sourcePath]);

  return (
    <main id={doc.id} data-screen-label={doc.title} className="pt-16 sm:pt-20 pb-24">
      <Container>
        <div className="max-w-3xl">
          <Eyebrow>{doc.isHub ? 'Central Legal' : 'Documento público'}</Eyebrow>
          {doc.isHub ? (
            <>
              <h1 className="mt-5 text-4xl sm:text-5xl lg:text-[3.5rem] lg:leading-[1.05] font-medium text-black">
                Transparência e <span className="font-em text-forest">regras claras</span>
              </h1>
              <p className="mt-6 text-base sm:text-lg text-slate leading-relaxed">
                Tudo o que rege o uso da nossa plataforma de IA, em linguagem simples: políticas, termos e como protegemos seus dados.
              </p>
            </>
          ) : (
            <>
              <h1 className="mt-5 text-4xl sm:text-5xl lg:text-[3.5rem] lg:leading-[1.05] font-medium text-black">
                {doc.title}
              </h1>
              <p className="mt-6 text-base sm:text-lg text-slate leading-relaxed">{doc.objective}</p>
            </>
          )}
        </div>

        <div className="mt-14 grid lg:grid-cols-[16rem_1fr] gap-10 lg:gap-16">
          <aside className="lg:sticky lg:top-24 self-start">
            <nav aria-label="Navegação legal" className="flex flex-row flex-wrap lg:flex-col gap-2">
              {LEGAL_DOCS.map((item) => {
                const on = item.hash === active;
                return (
                  <a
                    key={item.id}
                    href={legalHref(item)}
                    aria-current={on ? 'page' : undefined}
                    className={'block rounded-xl px-4 py-3 text-sm font-medium transition-colors ' + (on ? 'bg-forest text-white' : 'text-slate hover:bg-sage hover:text-forest')}
                  >
                    {item.label}
                  </a>
                );
              })}
            </nav>
          </aside>

          <article className="max-w-4xl">
            {doc.isHub && (
              <>
                <p className="text-base text-black/80 leading-relaxed">
                  Encontre rapidamente o documento que precisa. As páginas são públicas, não exigem login e podem ser abertas diretamente por seus endereços permanentes.
                </p>
                <div className="mt-8 grid sm:grid-cols-2 gap-3">
                  {LEGAL_DOCS.filter((item) => item.isPublic).map((item) => (
                    <a
                      key={item.id}
                      href={legalHref(item)}
                      className="group flex items-start justify-between gap-4 rounded-2xl border border-line p-5 hover:border-forest hover:bg-sage/30 transition-colors"
                    >
                      <span>
                        <span className="block text-base font-medium text-black">{item.label}</span>
                        <span className="mt-1 block text-sm text-slate leading-snug">{item.objective}</span>
                        <span className="mt-4 inline-block text-sm font-medium text-forest underline underline-offset-2">Abrir documento</span>
                      </span>
                      <span className="mt-1 shrink-0 text-forest opacity-0 group-hover:opacity-100 transition-opacity"><IArrow size={14}/></span>
                    </a>
                  ))}
                </div>
                <div className="mt-8 rounded-2xl bg-sage/60 border border-line p-6">
                  <p className="text-sm font-semibold text-black">Canal de contato</p>
                  <p className="mt-1.5 text-sm text-slate leading-relaxed">
                    Dúvidas legais, solicitações de privacidade e pedidos de exclusão:
                    {' '}<a href={'mailto:' + LEGAL_CONTACT} className="text-forest underline underline-offset-2">{LEGAL_CONTACT}</a>
                  </p>
                </div>
              </>
            )}

            {!doc.isHub && doc.sourcePath && loading && (
              <div role="status" className="mt-8 rounded-2xl border border-line bg-[#FAFAF8] p-6 text-sm text-slate">
                Carregando o documento aprovado…
              </div>
            )}

            {!doc.isHub && doc.sourcePath && error && (
              <div role="alert" className="mt-8 rounded-2xl border border-red-200 bg-red-50 p-6 text-sm text-red-900">
                {error}
              </div>
            )}

            {!doc.isHub && doc.sourcePath && !loading && !error && <LegalMarkdown markdown={markdown}/>}

            {!doc.isHub && !doc.sourcePath && (
              <>
                <div className="mt-8 space-y-5">
                  {doc.body.map((paragraph, index) => (
                    <p key={index} className="text-base text-black/80 leading-relaxed">{paragraph}</p>
                  ))}
                </div>
                <div className="mt-8 rounded-2xl bg-sage/60 border border-line p-6">
                  <p className="text-sm font-semibold text-black">{doc.finalCall.label}</p>
                  <p className="mt-1.5 text-sm text-slate leading-relaxed">
                    {doc.finalCall.prefix}{' '}
                    <a href={'mailto:' + doc.finalCall.email} className="text-forest underline underline-offset-2">{doc.finalCall.email}</a>
                  </p>
                </div>
                <p className="mt-8 text-xs text-slate">Última atualização: {LEGAL_UPDATED}</p>
              </>
            )}
          </article>
        </div>
      </Container>
    </main>
  );
};

Object.assign(window, { LEGAL_DOCS, LEGAL_HASHES, LEGAL_PATHS, LegalPage });
