// ui_kits/website/LegalPage.jsx
//
// One component renders all four legal documents (terms / privacy / sale /
// medical), chosen by the `doc` prop. Content is bilingual {es,en}.
// (renderPara still highlights any [[BRACKETED]] marker, so future draft copy
// can flag open decisions inline; the shipped copy has none.)

const legalStyles = {
  wrap: { maxWidth: 760, margin: '0 auto', padding: '56px 32px 96px' },
  h1: { fontFamily: 'var(--font-serif)', fontSize: 40, lineHeight: 1.12, color: 'var(--brand-leaf)', margin: '0 0 10px' },
  meta: { fontFamily: 'var(--font-sans)', fontSize: 13, letterSpacing: '0.02em', color: 'var(--color-fg-muted, #6b6b6b)', margin: '0 0 40px' },
  h2: { fontFamily: 'var(--font-serif)', fontSize: 22, lineHeight: 1.25, color: '#20302a', margin: '36px 0 12px' },
  p: { fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.72, color: '#33403b', margin: '0 0 14px' },
  contact: { fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.72, color: '#33403b', marginTop: 4 },
};

// Highlight [[PLACEHOLDER]] spans inside a paragraph so open decisions are
// visually obvious in the draft. Returns an array of strings + <mark> nodes.
function renderPara(text) {
  const parts = String(text).split(/(\[\[[^\]]+\]\])/g);
  return parts.map((seg, i) =>
    /^\[\[[^\]]+\]\]$/.test(seg)
      ? React.createElement('mark', {
          key: i,
          style: { background: '#FDE9A8', color: '#5A4708', padding: '0 4px', borderRadius: 3, fontWeight: 600 },
        }, seg.replace(/^\[\[|\]\]$/g, ''))
      : seg);
}

const LEGAL_UPDATED = { es: '11 julio, 2026', en: 'July 11, 2026' };

const LEGAL_DOCS = {
  // ---------------------------------------------------------------- TERMS ---
  terms: {
    es: {
      title: 'Términos de uso',
      desc: 'Condiciones para el uso del sitio web de Top Natural Tips.',
      sections: [
        { h: 'Aceptación de los términos', p: [
          'Al acceder y utilizar topnaturaltips.com (el "Sitio"), aceptas estos Términos de uso. Si no estás de acuerdo con ellos, por favor no utilices el Sitio.',
          'El Sitio es operado por topnaturaltips, LLC ("nosotros"), con domicilio en Los Ángeles, California.',
        ]},
        { h: 'Naturaleza del contenido', p: [
          'Los artículos, el pódcast, los videos y demás contenidos del Sitio tienen fines educativos e informativos únicamente. No sustituyen la asesoría de un profesional de la salud. Consulta también nuestro Aviso médico.',
        ]},
        { h: 'Propiedad intelectual', p: [
          'Todo el contenido del Sitio —textos, imágenes, logotipos, marca y diseño— es propiedad de topnaturaltips, LLC o de sus licenciantes y está protegido por las leyes aplicables. Puedes ver y compartir el contenido para uso personal y no comercial; cualquier otro uso requiere nuestro permiso por escrito.',
        ]},
        { h: 'Uso aceptable', p: [
          'Te comprometes a no utilizar el Sitio de forma ilícita, a no interferir con su funcionamiento ni con su seguridad, y a no extraer datos de manera automatizada sin autorización.',
        ]},
        { h: 'Enlaces y contenido de terceros', p: [
          'El Sitio incorpora contenido de terceros (por ejemplo, videos de YouTube y episodios de pódcast alojados en Buzzsprout) y puede enlazar a otros sitios. No controlamos ese contenido y no somos responsables de él; su uso se rige por los términos de cada tercero.',
        ]},
        { h: 'Descargo de garantías', p: [
          'El Sitio se ofrece "tal cual" y "según disponibilidad". No garantizamos que el contenido sea exacto, completo o esté actualizado, ni que el Sitio funcione sin interrupciones o errores.',
        ]},
        { h: 'Limitación de responsabilidad', p: [
          'En la medida que permita la ley, topnaturaltips, LLC no será responsable por daños indirectos, incidentales o derivados del uso —o de la imposibilidad de uso— del Sitio o de su contenido.',
        ]},
        { h: 'Cambios en los términos', p: [
          'Podemos actualizar estos Términos en cualquier momento. La versión vigente es la publicada en esta página, con su fecha de actualización.',
        ]},
        { h: 'Ley aplicable', p: [
          'Estos Términos se rigen por las leyes del Estado de California, sin dar efecto a sus normas sobre conflicto de leyes.',
        ]},
        { h: 'Contacto', p: [
          'Para cualquier duda sobre estos Términos, escríbenos a support@topnaturaltips.com.',
        ]},
      ],
    },
    en: {
      title: 'Terms of Use',
      desc: 'Conditions for using the Top Natural Tips website.',
      sections: [
        { h: 'Acceptance of terms', p: [
          'By accessing and using topnaturaltips.com (the "Site"), you agree to these Terms of Use. If you do not agree, please do not use the Site.',
          'The Site is operated by topnaturaltips, LLC ("we," "us"), located in Los Angeles, California.',
        ]},
        { h: 'Nature of the content', p: [
          'The articles, podcast, videos, and other content on the Site are for educational and informational purposes only. They are not a substitute for professional medical advice. See also our Medical Disclaimer.',
        ]},
        { h: 'Intellectual property', p: [
          'All content on the Site — text, images, logos, branding, and design — is owned by topnaturaltips, LLC or its licensors and is protected by applicable law. You may view and share content for personal, non-commercial use; any other use requires our written permission.',
        ]},
        { h: 'Acceptable use', p: [
          'You agree not to use the Site unlawfully, not to interfere with its operation or security, and not to scrape or harvest data by automated means without authorization.',
        ]},
        { h: 'Third-party links and content', p: [
          'The Site embeds third-party content (for example, YouTube videos and podcast episodes hosted on Buzzsprout) and may link to other sites. We do not control and are not responsible for that content; your use of it is governed by each third party’s terms.',
        ]},
        { h: 'Disclaimer of warranties', p: [
          'The Site is provided "as is" and "as available." We do not warrant that the content is accurate, complete, or current, or that the Site will operate without interruption or error.',
        ]},
        { h: 'Limitation of liability', p: [
          'To the extent permitted by law, topnaturaltips, LLC will not be liable for indirect, incidental, or consequential damages arising from your use of — or inability to use — the Site or its content.',
        ]},
        { h: 'Changes to these terms', p: [
          'We may update these Terms at any time. The current version is the one posted on this page, with its update date.',
        ]},
        { h: 'Governing law', p: [
          'These Terms are governed by the laws of the State of California, without regard to its conflict-of-laws rules.',
        ]},
        { h: 'Contact', p: [
          'Questions about these Terms? Email support@topnaturaltips.com.',
        ]},
      ],
    },
  },

  // -------------------------------------------------------------- PRIVACY ---
  privacy: {
    es: {
      title: 'Política de privacidad',
      desc: 'Cómo Top Natural Tips recopila, usa y protege tus datos personales.',
      sections: [
        { h: 'Introducción', p: [
          'Esta Política explica qué datos personales recopilamos en topnaturaltips.com, cómo los usamos y con quién los compartimos. El responsable del tratamiento es topnaturaltips, LLC (Los Ángeles, California).',
        ]},
        { h: 'Datos que recopilamos', p: [
          'Boletín: tu dirección de correo electrónico cuando te suscribes.',
          'Compras: al pagar, nuestro procesador de pagos (Stripe) recopila tu nombre, correo, dirección de envío y datos de pago. No almacenamos los datos completos de tu tarjeta en nuestros servidores.',
          'Envíos: tu dirección se comparte con nuestro proveedor de logística (Shippo/USPS) para calcular tarifas y entregar tu pedido.',
          'Datos técnicos: nuestro alojamiento y CDN registran datos básicos de uso (dirección IP, tipo de navegador) para seguridad y funcionamiento del Sitio.',
        ]},
        { h: 'Cómo usamos tus datos', p: [
          'Para enviarte el boletín que solicitaste, procesar y entregar tus pedidos, atender tus consultas, mantener la seguridad del Sitio y cumplir obligaciones legales.',
        ]},
        { h: 'Con quién los compartimos', p: [
          'Compartimos datos únicamente con proveedores que nos prestan servicios: Stripe (pagos), Shippo y USPS (envíos), Google (gestión del boletín), y los servicios de alojamiento y CDN del Sitio. El contenido incrustado de YouTube y Buzzsprout puede recopilar datos según sus propias políticas. No vendemos tus datos personales.',
        ]},
        { h: 'Cookies y almacenamiento local', p: [
          'El Sitio usa almacenamiento local del navegador para recordar preferencias (como el idioma y el contenido en caché) y cookies necesarias para el pago. Puedes borrarlas desde la configuración de tu navegador.',
        ]},
        { h: 'Conservación de datos', p: [
          'Conservamos tus datos solo el tiempo necesario para las finalidades descritas o el que exija la ley.',
        ]},
        { h: 'Tus derechos', p: [
          'Puedes solicitar acceder, corregir o eliminar tus datos personales, o darte de baja del boletín en cualquier momento, escribiendo a Paola@topnaturaltips.com.',
        ]},
        { h: 'Menores de edad', p: [
          'El Sitio no está dirigido a menores de 13 años y no recopilamos conscientemente sus datos.',
        ]},
        { h: 'Cambios en esta política', p: [
          'Podemos actualizar esta Política; la versión vigente es la publicada aquí, con su fecha.',
        ]},
        { h: 'Contacto', p: [
          'Para asuntos de privacidad, escríbenos a Paola@topnaturaltips.com.',
        ]},
      ],
    },
    en: {
      title: 'Privacy Policy',
      desc: 'How Top Natural Tips collects, uses, and protects your personal data.',
      sections: [
        { h: 'Introduction', p: [
          'This Policy explains what personal data we collect on topnaturaltips.com, how we use it, and who we share it with. The data controller is topnaturaltips, LLC (Los Angeles, California).',
        ]},
        { h: 'Data we collect', p: [
          'Newsletter: your email address when you subscribe.',
          'Purchases: at checkout, our payment processor (Stripe) collects your name, email, shipping address, and payment details. We do not store full card numbers on our servers.',
          'Shipping: your address is shared with our fulfillment provider (Shippo/USPS) to calculate rates and deliver your order.',
          'Technical data: our hosting and CDN log basic usage data (IP address, browser type) for security and Site operation.',
        ]},
        { h: 'How we use your data', p: [
          'To send the newsletter you requested, process and deliver your orders, respond to your inquiries, keep the Site secure, and meet legal obligations.',
        ]},
        { h: 'Who we share it with', p: [
          'We share data only with providers that deliver services for us: Stripe (payments), Shippo and USPS (shipping), Google (newsletter management), and the Site’s hosting and CDN. Embedded YouTube and Buzzsprout content may collect data under their own policies. We do not sell your personal data.',
        ]},
        { h: 'Cookies and local storage', p: [
          'The Site uses browser local storage to remember preferences (such as language and cached content) and cookies necessary for checkout. You can clear these in your browser settings.',
        ]},
        { h: 'Data retention', p: [
          'We keep your data only as long as needed for the purposes described or as required by law.',
        ]},
        { h: 'Your rights', p: [
          'You may request to access, correct, or delete your personal data, or unsubscribe from the newsletter at any time, by writing to Paola@topnaturaltips.com.',
        ]},
        { h: 'Children', p: [
          'The Site is not directed to children under 13, and we do not knowingly collect their data.',
        ]},
        { h: 'Changes to this policy', p: [
          'We may update this Policy; the current version is the one posted here, with its date.',
        ]},
        { h: 'Contact', p: [
          'For privacy matters, email Paola@topnaturaltips.com.',
        ]},
      ],
    },
  },

  // ----------------------------------------------------------------- SALE ---
  sale: {
    es: {
      title: 'Términos de venta',
      desc: 'Condiciones de compra, envío y devoluciones en Top Natural Tips.',
      sections: [
        { h: 'Pedidos y aceptación', p: [
          'Al realizar un pedido en topnaturaltips.com haces una oferta de compra que aceptamos al confirmarla. Nos reservamos el derecho de rechazar o cancelar un pedido (por ejemplo, por error de precio o falta de existencias).',
        ]},
        { h: 'Precios y moneda', p: [
          'Los precios se muestran en dólares estadounidenses (USD) e incluyen los impuestos aplicables cuando corresponda. Podemos actualizar los precios en cualquier momento antes de tu compra.',
        ]},
        { h: 'Pago', p: [
          'El pago se procesa de forma segura a través de Stripe. Al pagar aceptas también los términos de Stripe como procesador.',
        ]},
        { h: 'Envíos', p: [
          'Enviamos a Estados Unidos, Canadá y México mediante USPS. Las tarifas se calculan en tiempo real al momento del pago según tu dirección. Los plazos de entrega son estimados y pueden variar por causas ajenas a nosotros.',
        ]},
        { h: 'Devoluciones', p: [
          'Aceptamos devoluciones dentro de los 30 días posteriores a la entrega. El cliente asume el costo del envío de devolución.',
          'Por motivos de salud y seguridad, los productos consumibles o de bienestar abiertos pueden no ser aptos para devolución. Los productos deben devolverse en condiciones adecuadas.',
        ]},
        { h: 'Reembolsos', p: [
          'Una vez recibida y revisada la devolución, emitiremos el reembolso al método de pago original. El importe del envío original no es reembolsable, salvo que el producto haya llegado defectuoso o equivocado.',
        ]},
        { h: 'Cancelaciones', p: [
          'Si necesitas cancelar un pedido, escríbenos lo antes posible a support@topnaturaltips.com; haremos lo posible si aún no ha sido enviado.',
        ]},
        { h: 'Ley aplicable', p: [
          'Estos Términos de venta se rigen por las leyes del Estado de California.',
        ]},
        { h: 'Contacto', p: [
          'Para asuntos de pedidos, envíos o devoluciones, escríbenos a support@topnaturaltips.com.',
        ]},
      ],
    },
    en: {
      title: 'Terms of Sale',
      desc: 'Purchase, shipping, and return conditions at Top Natural Tips.',
      sections: [
        { h: 'Orders and acceptance', p: [
          'When you place an order on topnaturaltips.com you make an offer to buy, which we accept when we confirm it. We reserve the right to refuse or cancel an order (for example, for a pricing error or lack of stock).',
        ]},
        { h: 'Prices and currency', p: [
          'Prices are shown in U.S. dollars (USD) and include applicable taxes where required. We may update prices at any time before your purchase.',
        ]},
        { h: 'Payment', p: [
          'Payment is processed securely through Stripe. By paying, you also agree to Stripe’s terms as the processor.',
        ]},
        { h: 'Shipping', p: [
          'We ship to the United States, Canada, and Mexico via USPS. Rates are calculated in real time at checkout based on your address. Delivery times are estimates and may vary for reasons beyond our control.',
        ]},
        { h: 'Returns', p: [
          'We accept returns within 30 days of delivery. The customer is responsible for return shipping costs.',
          'For health and safety reasons, opened consumable or wellness products may not be eligible for return. Products must be returned in suitable condition.',
        ]},
        { h: 'Refunds', p: [
          'Once we receive and review your return, we will issue a refund to the original payment method. Original shipping charges are non-refundable unless the product arrived defective or incorrect.',
        ]},
        { h: 'Cancellations', p: [
          'If you need to cancel an order, email us as soon as possible at support@topnaturaltips.com; we will do our best if it has not yet shipped.',
        ]},
        { h: 'Governing law', p: [
          'These Terms of Sale are governed by the laws of the State of California.',
        ]},
        { h: 'Contact', p: [
          'For orders, shipping, or returns, email support@topnaturaltips.com.',
        ]},
      ],
    },
  },

  // -------------------------------------------------------------- MEDICAL ---
  medical: {
    es: {
      title: 'Aviso médico',
      desc: 'El contenido y los productos de Top Natural Tips no sustituyen la atención médica profesional.',
      sections: [
        { h: 'Solo con fines educativos', p: [
          'El contenido de Top Natural Tips tiene fines exclusivamente educativos e informativos y no constituye asesoría médica, diagnóstico ni tratamiento. Consulta siempre a tu médico u otro profesional de la salud calificado ante cualquier duda sobre una condición de salud.',
        ]},
        { h: 'Consulta a un profesional', p: [
          'Nunca ignores el consejo médico profesional ni demores en buscarlo por algo que hayas leído o escuchado en este Sitio. Esto es especialmente importante si estás embarazada, amamantando, tomas medicamentos o tienes una condición médica.',
        ]},
        { h: 'Declaración de la FDA', p: [
          'Estas afirmaciones no han sido evaluadas por la Administración de Alimentos y Medicamentos de EE. UU. (FDA). Los productos ofrecidos no están destinados a diagnosticar, tratar, curar ni prevenir ninguna enfermedad.',
        ]},
        { h: 'Los resultados varían', p: [
          'Cualquier resultado mencionado en el contenido o por otros clientes es individual y puede no repetirse en todas las personas.',
        ]},
        { h: 'Uso de los productos', p: [
          'Lee siempre la etiqueta, los ingredientes y las indicaciones del fabricante antes de usar un producto. Suspende su uso y consulta a un profesional si presentas cualquier reacción adversa. Algunas personas pueden tener alergias u otras reacciones.',
        ]},
        { h: 'Información de terceros', p: [
          'No somos el fabricante de los productos que vendemos. La información de los productos proviene de sus fabricantes y de otras fuentes; no garantizamos que sea exacta, completa o esté actualizada.',
        ]},
        { h: 'Contacto', p: [
          'Si tienes preguntas sobre este aviso, escríbenos a support@topnaturaltips.com.',
        ]},
      ],
    },
    en: {
      title: 'Medical Disclaimer',
      desc: 'Top Natural Tips content and products are not a substitute for professional medical care.',
      sections: [
        { h: 'For educational purposes only', p: [
          'The content on Top Natural Tips is for educational and informational purposes only and does not constitute medical advice, diagnosis, or treatment. Always seek the advice of your physician or other qualified health provider with any questions you may have regarding a health condition.',
        ]},
        { h: 'Consult a professional', p: [
          'Never disregard professional medical advice or delay seeking it because of something you have read or heard on this Site. This is especially important if you are pregnant, nursing, taking medication, or have a medical condition.',
        ]},
        { h: 'FDA statement', p: [
          'These statements have not been evaluated by the U.S. Food and Drug Administration (FDA). The products offered are not intended to diagnose, treat, cure, or prevent any disease.',
        ]},
        { h: 'Results vary', p: [
          'Any results described in the content or reported by other customers are individual and may not occur for everyone.',
        ]},
        { h: 'Using the products', p: [
          'Always read the label, ingredients, and the manufacturer’s directions before using a product. Discontinue use and consult a professional if you experience any adverse reaction. Some people may have allergies or other reactions.',
        ]},
        { h: 'Third-party information', p: [
          'We are not the manufacturer of the products we sell. Product information comes from manufacturers and other sources; we do not warrant that it is accurate, complete, or current.',
        ]},
        { h: 'Contact', p: [
          'Questions about this disclaimer? Email support@topnaturaltips.com.',
        ]},
      ],
    },
  },
};

function LegalPage({ doc }) {
  const lang = React.useContext(LangContext);
  const isMobile = (typeof useIsMobile === 'function') ? useIsMobile() : false;
  const entry = LEGAL_DOCS[doc];
  const data = entry ? (entry[lang] || entry.es) : null;

  React.useEffect(() => {
    if (!data) return;
    updateSeo({
      title: data.title,
      description: data.desc,
      canonical: SEO.url(buildPath({ view: 'legal', doc })),
      ogType: 'website',
      lang,
    });
  }, [doc, lang, data]);

  if (!data) {
    return <NotFoundPage/>;
  }

  const updated = LEGAL_UPDATED[lang] || LEGAL_UPDATED.es;
  const updatedLabel = lang === 'en' ? 'Last updated' : 'Última actualización';

  return (
    <main style={{ ...legalStyles.wrap, ...(isMobile ? { padding: '40px 20px 72px' } : {}) }}>
      <h1 style={legalStyles.h1}>{data.title}</h1>
      <p style={legalStyles.meta}>{updatedLabel}: {updated}</p>
      {data.sections.map((s, i) => (
        <section key={i}>
          <h2 style={legalStyles.h2}>{s.h}</h2>
          {s.p.map((para, j) => (
            <p key={j} style={legalStyles.p}>{renderPara(para)}</p>
          ))}
        </section>
      ))}
    </main>
  );
}

window.LegalPage = LegalPage;
