<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title id="page-title">Domain</title>
  <meta name="description" content="This domain is registered.">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #fafaf9;
      --text: #1c1917;
      --text-muted: #57534e;
      --accent: #0f766e;
      --accent-hover: #0d9488;
      --border: #e7e5e4;
      --input-bg: #fff;
      --radius: 8px;
      --font: 'DM Sans', system-ui, sans-serif;
      --content-max: 100%;
      --content-padding: 1.5rem;
      --hero-title-size: 1.75rem;
      --section-space: 4rem;
      --section-padding-y: 2rem; /* 2rem at all breakpoints */
      --heading-letter-spacing: -0.025em;
      --shadow-sm: 0 1px 2px rgba(0,0,0,0.04);
      --shadow-md: 0 4px 12px rgba(0,0,0,0.06);
    }

    * {
      box-sizing: border-box;
    }

    html {
      font-size: clamp(16px, 2.5vw, 18px);
      -webkit-font-smoothing: antialiased;
      scroll-behavior: smooth;
    }

    body {
      margin: 0;
      min-height: 100vh;
      font-family: var(--font);
      color: var(--text);
      background: var(--bg);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-start;
      padding: 0 var(--content-padding) 0;
      line-height: 1.6;
      -webkit-font-smoothing: antialiased;
    }

    main {
      max-width: var(--content-max);
      width: 100%;
      text-align: center;
      padding-top: 0;
    }

    /* Mobile: single column, narrow content */
    @media (min-width: 480px) {
      :root {
        --content-max: min(420px, 100%);
      }
    }

    /* Tablet: wider content */
    @media (min-width: 640px) {
      :root {
        --content-max: min(600px, 92vw);
        --content-padding: 2rem;
        --hero-title-size: 2rem;
        --section-padding-y: 2rem;
      }
    }

    /* Desktop: full readable width */
    @media (min-width: 960px) {
      :root {
        --content-max: min(720px, 88vw);
        --content-padding: 2.5rem;
        --hero-title-size: 2.5rem;
        --section-space: 5rem;
        --section-padding-y: 2rem;
      }
    }

    /* Large: wider content */
    @media (min-width: 1280px) {
      :root {
        --content-max: 880px;
        --content-padding: 3rem;
        --hero-title-size: 3rem;
        --section-space: 6rem;
      --section-padding-y: 4rem;
      }
    }

    .domain {
      font-size: var(--hero-title-size);
      font-weight: 600;
      letter-spacing: var(--heading-letter-spacing);
      line-height: 1.2;
      margin: 0 0 0.75rem;
      word-break: break-word;
    }

    .tagline {
      color: var(--text-muted);
      font-size: 1.125rem;
      line-height: 1.65;
      max-width: 42em;
      margin: 0 auto 2rem;
    }

    .contact {
      border-top: 1px solid var(--border);
      padding-top: 2rem;
      margin-top: 2rem;
    }

    .contact h2 {
      font-size: 0.85rem;
      font-weight: 500;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--text-muted);
      margin: 0 0 1rem;
    }

    form {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      text-align: left;
      max-width: 42em;
      margin-left: auto;
      margin-right: auto;
      width: 100%;
    }

    label {
      font-size: 0.9rem;
      color: var(--text-muted);
    }

    input, textarea {
      width: 100%;
      padding: 0.75rem 1rem;
      font: inherit;
      font-size: 1rem;
      color: var(--text);
      background: var(--input-bg);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      transition: border-color 0.15s ease, box-shadow 0.15s ease;
    }

    input:focus, textarea:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
    }

    textarea {
      min-height: 100px;
      resize: vertical;
    }

    button[type="submit"] {
      font: inherit;
      font-size: 0.9375rem;
      font-weight: 500;
      color: #fff;
      background: var(--accent);
      border: none;
      border-radius: var(--radius);
      padding: 0.75rem 1.5rem;
      cursor: pointer;
      transition: background 0.15s ease, box-shadow 0.15s ease;
      margin-top: 0.25rem;
      box-shadow: var(--shadow-sm);
    }

    button[type="submit"]:hover {
      background: var(--accent-hover);
      box-shadow: var(--shadow-md);
    }

    button[type="submit"]:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .form-status {
      font-size: 0.9rem;
      margin-top: 0.5rem;
      min-height: 1.2em;
    }

    .form-status.success { color: var(--accent); }
    .form-status.error { color: #b91c1c; }

    /* Members auth – sign in / sign up */
    .members-auth {
      max-width: 420px;
      margin: 0 auto;
      padding: 2.5rem 1.5rem;
      text-align: left;
    }
    .members-auth-card {
      background: var(--input-bg);
      border: 1px solid var(--border);
      border-radius: 12px;
      box-shadow: var(--shadow-md);
      padding: 2rem;
    }
    .members-auth h1 { text-align: center; margin-bottom: 0.5rem; }
    .members-auth-subtitle {
      text-align: center;
      color: var(--text-muted);
      font-size: 1rem;
      margin: 0 0 1.75rem;
      line-height: 1.5;
    }
    .members-auth-tabs {
      display: flex;
      background: var(--bg);
      border-radius: 10px;
      padding: 4px;
      margin-bottom: 1.5rem;
      gap: 0;
    }
    .members-auth-tabs button {
      flex: 1;
      padding: 0.65rem 1rem;
      font-size: 0.9375rem;
      font-weight: 500;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      background: transparent;
      color: var(--text-muted);
      transition: background 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
    }
    .members-auth-tabs button:hover { color: var(--text); }
    .members-auth-tabs button.is-active {
      background: var(--input-bg);
      color: var(--text);
      box-shadow: var(--shadow-sm);
    }
    .members-auth-form .form-group {
      margin-bottom: 1.25rem;
    }
    .members-auth-form .form-group:last-of-type { margin-bottom: 1.5rem; }
    .members-auth-form label {
      display: block;
      font-size: 0.875rem;
      font-weight: 500;
      color: var(--text);
      margin-bottom: 0.4rem;
    }
    .members-auth-form input {
      width: 100%;
      padding: 0.75rem 1rem;
      font: inherit;
      font-size: 1rem;
    }
    .members-auth-form input::placeholder {
      color: var(--text-muted);
      opacity: 0.7;
    }
    .members-auth-form .password-wrap {
      position: relative;
      display: flex;
      align-items: center;
    }
    .members-auth-form .password-wrap input {
      padding-right: 2.75rem;
    }
    .members-auth-form .password-toggle {
      position: absolute;
      right: 0.5rem;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      padding: 0.35rem;
      cursor: pointer;
      color: var(--text-muted);
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
    }
    .members-auth-form .password-toggle:hover {
      color: var(--text);
      background: var(--border);
    }
    .members-auth-form .password-toggle svg {
      width: 20px;
      height: 20px;
    }
    .members-auth-error {
      display: none;
      padding: 0.75rem 1rem;
      font-size: 0.9rem;
      color: #b91c1c;
      background: #fef2f2;
      border: 1px solid #fecaca;
      border-radius: var(--radius);
      margin-bottom: 1.25rem;
    }
    .members-auth-error:not(:empty) { display: block; }
    .members-auth .auth-submit {
      width: 100%;
      padding: 0.875rem 1.25rem;
      font-size: 1rem;
      font-weight: 500;
    }
    .members-auth .auth-submit:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
    /* Assessment forms – consistent layout for all tests */
    .members-content input[type="radio"] {
      width: auto;
      min-width: 1.125rem;
      flex-shrink: 0;
      margin: 0.2em 0 0 0;
      padding: 0;
    }
    .members-content #members-test-form label {
      color: var(--text);
    }
    .members-content #members-test-form label span {
      flex: 1;
      min-width: 0;
      word-wrap: break-word;
    }
    .members-content #members-test-form div > label:last-child {
      margin-bottom: 0;
    }
    .members-content .assessment-item {
      margin-bottom: 2rem;
      padding: 1rem;
      background: var(--bg);
      border-radius: var(--radius);
    }

    .members-auth-back {
      display: block;
      margin-top: 1.5rem;
      font-size: 0.9rem;
      color: var(--text-muted);
      text-align: center;
      text-decoration: none;
      transition: color 0.15s ease;
    }
    .members-auth-back:hover { color: var(--accent); }

    /* 2-step signup flow (ClickPlay-style) */
    .members-signup-flow {
      display: grid;
      grid-template-columns: 1fr;
      gap: 2rem;
      max-width: 960px;
      margin: 0 auto;
      padding: 2rem 1.5rem;
      text-align: left;
    }
    @media (min-width: 768px) {
      .members-signup-flow { grid-template-columns: 1fr 1fr; gap: 3rem; }
    }
    .members-signup-flow .step-side {
      padding: 1rem 0;
    }
    .members-signup-flow .step-counter {
      font-size: 0.9rem;
      font-weight: 600;
      color: var(--text-muted);
      margin-bottom: 1.5rem;
      letter-spacing: 0.05em;
    }
    .members-signup-flow .step-product {
      font-size: 1.25rem;
      font-weight: 600;
      margin-bottom: 0.25rem;
    }
    .members-signup-flow .step-price {
      font-size: 1.5rem;
      font-weight: 600;
      color: var(--accent);
      margin-bottom: 1rem;
    }
    .members-signup-flow .step-side h2 {
      font-size: 1.5rem;
      margin: 0 0 0.75rem;
      font-weight: 600;
    }
    .members-signup-flow .step-side .step-desc {
      color: var(--text-muted);
      font-size: 0.95rem;
      line-height: 1.6;
      margin-bottom: 1.5rem;
    }
    .members-signup-flow .step-side .step-desc p { margin: 0 0 0.75rem; }
    .members-signup-flow .form-side {
      background: var(--input-bg);
      border: 1px solid var(--border);
      border-radius: 12px;
      box-shadow: var(--shadow-md);
      padding: 2rem;
    }
    .members-signup-flow .payment-placeholder {
      margin-top: 1.5rem;
      padding: 1.5rem;
      background: var(--bg);
      border: 1px dashed var(--border);
      border-radius: var(--radius);
      min-height: 200px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--text-muted);
      font-size: 0.9rem;
    }
    .members-signup-flow .payment-placeholder.disabled::after {
      content: '';
      position: absolute;
      inset: 0;
      background: rgba(255,255,255,0.5);
      border-radius: var(--radius);
      cursor: not-allowed;
    }
    .members-signup-flow .payment-placeholder.disabled {
      pointer-events: none;
    }

    .footer {
      margin: 0;
      padding-bottom: 1.5rem;
      font-size: 0.8rem;
      color: var(--text-muted);
    }

    .widget-legal { text-align: left; }
    .widget-legal .legal-content { white-space: pre-wrap; font-size: 0.9rem; line-height: 1.65; }
    .widget-legal-links .footer a { color: var(--text-muted); text-decoration: none; }
    .widget-legal-links .footer a:hover { color: var(--accent); }
    .footer a { color: var(--text-muted); text-decoration: none; }
    .footer a:hover { color: var(--accent); }
    #legal-dialog { display: none; position: fixed; inset: 0; z-index: 1000; align-items: center; justify-content: center; padding: 1rem; box-sizing: border-box; background: rgba(0,0,0,0.4); }
    #legal-dialog.is-open { display: flex; }
    #legal-dialog .legal-dialog-inner { max-width: 600px; max-height: 85vh; overflow: auto; background: var(--bg); border-radius: var(--radius); box-shadow: var(--shadow-md); padding: 1.5rem; }
    #legal-dialog .legal-dialog-title { font-size: 1.25rem; font-weight: 600; margin: 0 0 1rem; }
    #legal-dialog .legal-dialog-content { font-size: 0.9rem; line-height: 1.65; white-space: pre-wrap; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
    #legal-dialog .legal-dialog-close { margin-top: 1rem; }

    .widget { margin: 0; padding-top: var(--section-padding-y); padding-bottom: var(--section-padding-y); }

    /* Scroll-triggered and entrance animations */
    @keyframes fadeInUp {
      from { opacity: 0; transform: translateY(28px); }
      to { opacity: 1; transform: translateY(0); }
    }
    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }
    .widget.animate-reveal {
      opacity: 0;
    }
    @media (prefers-reduced-motion: reduce) {
      .widget.animate-reveal { opacity: 1; }
      .widget.animate-reveal.animate-in,
      .widget.animate-in .feature-item,
      .widget.animate-in .stat-item,
      .widget.animate-in .plan,
      .widget.animate-in .product-card,
      .widget.animate-in.widget-team > *,
      .widget-logos.animate-in a,
      .widget.animate-in .trust-item { animation: none; opacity: 1; }
    }
    .widget.animate-reveal.animate-in {
      opacity: 1;
      animation: fadeInUp 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
    }
    .widget-hero.animate-reveal.animate-in {
      animation: fadeInUp 0.7s cubic-bezier(0.22, 1, 0.36, 1) forwards;
    }
    /* Staggered children (section gets animate-in, children animate with delay) */
    .widget.animate-in .feature-item,
    .widget.animate-in .stat-item,
    .widget.animate-in .plan,
    .widget.animate-in .product-card,
    .widget.animate-in.widget-team > *,
    .widget-logos.animate-in a,
    .widget.animate-in .trust-item {
      opacity: 0;
      animation: fadeInUp 0.5s cubic-bezier(0.22, 1, 0.36, 1) forwards;
    }
    .widget.animate-in .feature-item:nth-child(1) { animation-delay: 0.05s; }
    .widget.animate-in .feature-item:nth-child(2) { animation-delay: 0.1s; }
    .widget.animate-in .feature-item:nth-child(3) { animation-delay: 0.15s; }
    .widget.animate-in .feature-item:nth-child(4) { animation-delay: 0.2s; }
    .widget.animate-in .feature-item:nth-child(5) { animation-delay: 0.25s; }
    .widget.animate-in .feature-item:nth-child(6) { animation-delay: 0.3s; }
    .widget-stats.animate-in .stat-item:nth-child(1) { animation-delay: 0.08s; }
    .widget-stats.animate-in .stat-item:nth-child(2) { animation-delay: 0.16s; }
    .widget-stats.animate-in .stat-item:nth-child(3) { animation-delay: 0.24s; }
    .widget-stats.animate-in .stat-item:nth-child(4) { animation-delay: 0.32s; }
    .widget-pricing.animate-in .plan:nth-child(2) { animation-delay: 0.06s; }
    .widget-pricing.animate-in .plan:nth-child(3) { animation-delay: 0.12s; }
    .widget-pricing.animate-in .plan:nth-child(4) { animation-delay: 0.18s; }
    .widget-product.animate-in .product-card:nth-child(2) { animation-delay: 0.06s; }
    .widget-product.animate-in .product-card:nth-child(3) { animation-delay: 0.12s; }
    .widget-product.animate-in .product-card:nth-child(4) { animation-delay: 0.18s; }
    .widget-team.animate-in > *:nth-child(1) { animation-delay: 0.06s; }
    .widget-team.animate-in > *:nth-child(2) { animation-delay: 0.12s; }
    .widget-team.animate-in > *:nth-child(3) { animation-delay: 0.18s; }
    .widget-full-bg {
      width: 100vw;
      margin-left: calc(50% - 50vw);
      margin-right: calc(50% - 50vw);
      padding: var(--section-padding-y) var(--content-padding);
      box-sizing: border-box;
    }
    /* When features have full-width bg, section must not be grid (inner is the grid) */
    .widget-full-bg.widget-features { display: block; }
    .widget-full-bg-inner {
      width: 100%;
      max-width: var(--content-max);
      margin-left: auto;
      margin-right: auto;
      min-width: 0;
    }
    .widget-full-bg-inner.widget-features { display: grid; }
    /* Text on colored/gradient background: light or dark */
    .widget-full-bg.section-text-light,
    .widget-full-bg.section-text-light .widget-full-bg-inner {
      color: #fff;
    }
    .widget-full-bg.section-text-light .domain,
    .widget-full-bg.section-text-light .section-heading,
    .widget-full-bg.section-text-light .body,
    .widget-full-bg.section-text-light .tagline,
    .widget-full-bg.section-text-light .countdown-value,
    .widget-full-bg.section-text-light .countdown-label,
    .widget-full-bg.section-text-light .plan-name,
    .widget-full-bg.section-text-light .plan-price,
    .widget-full-bg.section-text-light .plan-features,
    .widget-full-bg.section-text-light .feature-title,
    .widget-full-bg.section-text-light .feature-desc,
    .widget-full-bg.section-text-light .stat-value,
    .widget-full-bg.section-text-light .stat-label,
    .widget-full-bg.section-text-light .testimonial-quote,
    .widget-full-bg.section-text-light .testimonial-meta,
    .widget-full-bg.section-text-light .faq-answer,
    .widget-full-bg.section-text-light .widget-faq summary,
    .widget-full-bg.section-text-light .widget-pricing .plan-features,
    .widget-full-bg.section-text-light label { color: #fff; }
    .widget-full-bg.section-text-light .tagline,
    .widget-full-bg.section-text-light .feature-desc,
    .widget-full-bg.section-text-light .stat-label,
    .widget-full-bg.section-text-light .testimonial-meta,
    .widget-full-bg.section-text-light .countdown-label,
    .widget-full-bg.section-text-light .faq-answer,
    .widget-full-bg.section-text-light .widget-pricing .plan-features { color: rgba(255, 255, 255, 0.88); }
    .widget-full-bg.section-text-light .cta-outline { color: #fff; border-color: rgba(255,255,255,0.8); background: transparent; }
    .widget-full-bg.section-text-light .cta-outline:hover { color: #1c1917; background: #fff; border-color: #fff; }
    .widget-full-bg.section-text-light .nav-links a,
    .widget-full-bg.section-text-light .widget-social .social-links a { color: rgba(255,255,255,0.9); }
    .widget-full-bg.section-text-light .nav-links a:hover,
    .widget-full-bg.section-text-light .widget-social .social-links a:hover { color: #fff; }
    .widget-full-bg.section-text-light input,
    .widget-full-bg.section-text-light textarea { border-color: rgba(255,255,255,0.5); background: rgba(255,255,255,0.12); color: #fff; }
    .widget-full-bg.section-text-light input::placeholder,
    .widget-full-bg.section-text-light textarea::placeholder { color: rgba(255,255,255,0.6); }
    .widget-full-bg.section-text-dark,
    .widget-full-bg.section-text-dark .widget-full-bg-inner { color: #1c1917; }
    .widget-full-bg.section-text-dark .domain,
    .widget-full-bg.section-text-dark .section-heading,
    .widget-full-bg.section-text-dark .body,
    .widget-full-bg.section-text-dark .tagline,
    .widget-full-bg.section-text-dark .countdown-label,
    .widget-full-bg.section-text-dark .plan-name,
    .widget-full-bg.section-text-dark .plan-price,
    .widget-full-bg.section-text-dark .feature-title,
    .widget-full-bg.section-text-dark .feature-desc,
    .widget-full-bg.section-text-dark .stat-label,
    .widget-full-bg.section-text-dark .testimonial-quote,
    .widget-full-bg.section-text-dark .testimonial-meta,
    .widget-full-bg.section-text-dark .faq-answer,
    .widget-full-bg.section-text-dark .widget-faq summary,
    .widget-full-bg.section-text-dark .widget-pricing .plan-features,
    .widget-full-bg.section-text-dark label { color: #1c1917; }
    .widget-full-bg.section-text-dark .tagline,
    .widget-full-bg.section-text-dark .feature-desc,
    .widget-full-bg.section-text-dark .stat-label,
    .widget-full-bg.section-text-dark .testimonial-meta,
    .widget-full-bg.section-text-dark .countdown-label,
    .widget-full-bg.section-text-dark .faq-answer,
    .widget-full-bg.section-text-dark .widget-pricing .plan-features { color: #57534e; }
    .widget-full-bg.section-text-dark .cta-outline { color: #1c1917; border-color: #1c1917; background: transparent; }
    .widget-full-bg.section-text-dark .cta-outline:hover { color: #fff; background: #1c1917; }
    .widget-full-bg.section-text-dark .nav-links a,
    .widget-full-bg.section-text-dark .widget-social .social-links a { color: #57534e; }
    .widget-full-bg.section-text-dark .nav-links a:hover,
    .widget-full-bg.section-text-dark .widget-social .social-links a:hover { color: #1c1917; }
    .widget-hero { padding-top: 2rem; padding-bottom: 2rem; }
    .widget-hero .domain { font-size: var(--hero-title-size); font-weight: 600; letter-spacing: var(--heading-letter-spacing); margin-bottom: 1rem; }
    .widget-hero .tagline { color: var(--text-muted); font-size: 1.0625rem; margin-bottom: 1.5rem; line-height: 1.65; }
    .widget-hero .cta, .widget-button .cta, .widget-notifyme .cta {
      display: inline-block; font: inherit; font-size: 0.9375rem; font-weight: 500; padding: 0.75rem 1.5rem;
      border-radius: var(--radius); text-decoration: none; transition: all 0.2s ease; border: 2px solid transparent;
      box-shadow: var(--shadow-sm);
    }
    .widget-hero .hero-ctas { margin: 0; display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: center; }
    .cta-primary { color: #fff; background: var(--accent); }
    .cta-primary:hover { background: var(--accent-hover); }
    .cta-dark { color: #fff; background: #1c1917; }
    .cta-dark:hover { background: #44403c; }
    .cta-outline { color: var(--accent); background: transparent; border-color: var(--accent); }
    .cta-outline:hover { color: #fff; background: var(--accent); }
    .cta-gradient { color: #fff; background: linear-gradient(135deg, #0f766e 0%, #0d9488 50%, #14b8a6 100%); box-shadow: 0 4px 14px rgba(15, 118, 110, 0.4); }
    .cta-gradient:hover { box-shadow: 0 6px 20px rgba(15, 118, 110, 0.5); filter: brightness(1.05); }
    .cta-pill { color: #fff; background: var(--accent); border-radius: 999px; box-shadow: 0 2px 12px rgba(15, 118, 110, 0.35); }
    .cta-pill:hover { background: var(--accent-hover); box-shadow: 0 4px 16px rgba(15, 118, 110, 0.45); }
    .cta-bold { color: #fff; background: #ea580c; }
    .cta-bold:hover { background: #c2410c; }
    .cta-neon { color: #0f172a; background: #22d3ee; box-shadow: 0 4px 14px rgba(34, 211, 238, 0.5); }
    .cta-neon:hover { filter: brightness(1.1); box-shadow: 0 6px 20px rgba(34, 211, 238, 0.6); }
    .cta-coral { color: #fff; background: #ff6b6b; box-shadow: 0 4px 14px rgba(255, 107, 107, 0.45); }
    .cta-coral:hover { filter: brightness(1.08); box-shadow: 0 6px 20px rgba(255, 107, 107, 0.55); }
    .cta-electric { color: #fff; background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); box-shadow: 0 4px 14px rgba(59, 130, 246, 0.45); }
    .cta-electric:hover { filter: brightness(1.08); box-shadow: 0 6px 20px rgba(59, 130, 246, 0.55); }
    .cta-gold { color: #1c1917; background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%); box-shadow: 0 4px 14px rgba(251, 191, 36, 0.45); }
    .cta-gold:hover { filter: brightness(1.05); box-shadow: 0 6px 20px rgba(251, 191, 36, 0.55); }
    .cta-midnight { color: #fff; background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); box-shadow: 0 4px 14px rgba(99, 102, 241, 0.45); }
    .cta-midnight:hover { filter: brightness(1.08); box-shadow: 0 6px 20px rgba(99, 102, 241, 0.55); }
    .cta-urgent { color: #fff; background: #dc2626; box-shadow: 0 4px 14px rgba(220, 38, 38, 0.45); }
    .cta-urgent:hover { background: #b91c1c; box-shadow: 0 6px 20px rgba(220, 38, 38, 0.55); }
    .cta-mint { color: #1c1917; background: #34d399; box-shadow: 0 4px 14px rgba(52, 211, 153, 0.4); }
    .cta-mint:hover { filter: brightness(1.05); box-shadow: 0 6px 20px rgba(52, 211, 153, 0.5); }
    .cta-white-outline { color: #fff; background: transparent; border-color: rgba(255,255,255,0.9); }
    .cta-white-outline:hover { background: #fff; color: #1c1917; border-color: #fff; }
    .widget-text { padding-top: 2rem; padding-bottom: 2rem; }
    .widget-text.align-left { text-align: left; }
    .widget-text.align-center { text-align: center; }
    .widget-text.align-right { text-align: right; }
    .widget-text.align-justify { text-align: justify; }
    .widget-text .section-heading {
      font-size: 1.75rem;
      font-weight: 700;
      letter-spacing: var(--heading-letter-spacing);
      color: var(--text);
      margin: 0 0 1.25rem;
      line-height: 1.3;
    }
    @media (min-width: 640px) {
      .widget-text .section-heading { font-size: 2.25rem; margin-bottom: 1.5rem; }
    }
    .widget-text .body { white-space: pre-wrap; font-size: 1.0625rem; line-height: 1.75; color: var(--text); margin: 0; }
    .widget-text .section-heading + .body { margin-top: 0.75rem; }
    .widget-contact { border-top: 1px solid var(--border); padding-top: 2rem; margin-top: 0; padding-bottom: 2rem; }
    .widget-contact .section-heading {
      font-size: 1.75rem;
      font-weight: 700;
      letter-spacing: var(--heading-letter-spacing);
      color: var(--text);
      margin: 0 0 1.25rem;
      line-height: 1.3;
    }
    @media (min-width: 640px) {
      .widget-contact .section-heading { font-size: 2.25rem; margin-bottom: 1.5rem; }
    }
    .widget-social .social-links { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 0.75rem 1.25rem; justify-content: center; }
    .widget-social .social-links a { color: var(--accent); text-decoration: none; font-size: 0.95rem; }
    .widget-social .social-links a:hover { text-decoration: underline; }
    .widget-notifyme .notifyme-inline { display: flex; flex-direction: row; flex-wrap: nowrap; gap: 0.5rem; margin-top: 0.5rem; justify-content: center; align-items: center; }
    .widget-notifyme .notifyme-inline input { flex: 1; min-width: 0; max-width: 320px; }
    @media (min-width: 640px) {
      .widget-notifyme .notifyme-inline { justify-content: center; }
      .widget-notifyme .notifyme-inline input { max-width: 280px; }
    }
    .widget-image {
      width: 100vw;
      max-width: 100vw;
      min-width: 100vw;
      margin-left: calc(50% - 50vw);
      margin-right: calc(50% - 50vw);
      padding: 0;
      box-sizing: border-box;
      position: relative;
      left: 0;
    }
    .widget-image .widget-image-inner {
      display: block;
      width: 100%;
      min-width: 100%;
      max-width: none;
      border-radius: 0;
      overflow: hidden;
    }
    .widget-image .widget-image-inner img { border-radius: 0; display: block; }
    .widget-image .widget-image-inner.sized img { width: 100%; height: 100%; object-position: center; }
    .widget-image a { display: block; width: 100%; }
    .widget-countdown .countdown-value { font-size: 1.75rem; font-weight: 500; color: var(--accent); }
    .widget-countdown .countdown-label { font-size: 0.9rem; color: var(--text-muted); }
    .widget-faq details { margin-bottom: 0.5rem; border: 1px solid var(--border); border-radius: var(--radius); background: rgba(255,255,255,0.5); box-shadow: var(--shadow-sm); }
    .widget-faq summary { padding: 0.875rem 1.125rem; cursor: pointer; font-weight: 500; list-style: none; font-size: 1rem; }
    .widget-faq summary::-webkit-details-marker { display: none; }
    .widget-faq .faq-answer { padding: 0 1.125rem 0.875rem; color: var(--text-muted); font-size: 0.9375rem; line-height: 1.6; border-top: 1px solid var(--border); }
    .widget-testimonial { text-align: left; padding: 2rem; background: rgba(255,255,255,0.7); border-radius: var(--radius); border: 1px solid var(--border); box-shadow: var(--shadow-sm); max-width: 36em; margin-left: auto; margin-right: auto; }
    @media (min-width: 640px) {
      .widget-testimonial { padding: 2.5rem; }
    }
    .widget-testimonial .testimonial-quote { font-size: 1.0625rem; font-style: italic; color: var(--text); margin-bottom: 0.75rem; line-height: 1.6; }
    .widget-testimonial .testimonial-meta { font-size: 0.9375rem; color: var(--text-muted); }
    .widget-testimonial .testimonial-avatar { width: 48px; height: 48px; border-radius: 50%; object-fit: cover; margin-right: 0.75rem; }
    .widget-testimonial .testimonial-nav { display: flex; gap: 0.5rem; justify-content: center; margin-top: 1.25rem; }
    .widget-testimonial .testimonial-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--border); border: none; padding: 0; cursor: pointer; transition: background 0.2s; }
    .widget-testimonial .testimonial-dot.active { background: var(--accent); }
    /* Features: grid is always on inner div, never on section (section > .widget-features > items) */
    .widget-features {
      display: grid; gap: 2rem; text-align: center; grid-template-columns: 1fr;
      width: 100%; max-width: var(--content-max); margin-left: auto; margin-right: auto;
      min-width: 0; box-sizing: border-box;
    }
    .widget-features.cols-2 { grid-template-columns: 1fr; }
    .widget-features.cols-3 { grid-template-columns: 1fr; }
    .widget-features .feature-item {
      padding: 1.25rem; background: rgba(255,255,255,0.6); border-radius: var(--radius);
      border: 1px solid rgba(0,0,0,0.06); box-shadow: var(--shadow-sm);
      transition: box-shadow 0.2s ease, transform 0.2s ease, border-color 0.2s ease;
    }
    .widget-features .feature-item:hover {
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      border-color: rgba(0,0,0,0.1);
      transform: translateY(-2px);
    }
    .widget-features .feature-item { text-align: center; }
    .widget-features .feature-icon { font-size: 1.75rem; margin-bottom: 0.5rem; line-height: 1; }
    .widget-features .feature-title { font-size: 1.0625rem; font-weight: 600; margin-bottom: 0.35rem; letter-spacing: var(--heading-letter-spacing); }
    .widget-features .feature-desc { font-size: 0.9375rem; color: var(--text-muted); line-height: 1.6; }
    /* Mobile: 1 feature per row. 2 cols from 640px, 3 cols from 768px */
    @media (min-width: 640px) {
      .widget-features.cols-2 { grid-template-columns: 1fr 1fr; }
    }
    @media (min-width: 768px) {
      .widget-features.cols-3 { grid-template-columns: 1fr 1fr 1fr; }
    }
    .widget-stats { display: flex; flex-wrap: wrap; gap: 2.5rem 3rem; justify-content: center; padding: 2rem 0; }
    .widget-stats .stat-item { min-width: 5rem; }
    .widget-stats .stat-value { font-size: clamp(1.5rem, 4vw, 1.875rem); font-weight: 600; color: var(--accent); letter-spacing: var(--heading-letter-spacing); }
    .widget-stats .stat-label { font-size: 0.9375rem; color: var(--text-muted); margin-top: 0.25rem; }
    /* Initiatives – progress bars (ClickPlay-style) */
    .widget-initiatives { display: grid; gap: 1.25rem; grid-template-columns: 1fr; }
    .initiative-card { border: 1px solid var(--border); border-radius: var(--radius); padding: 1.25rem; background: var(--input-bg); box-shadow: var(--shadow-sm); }
    .initiative-title { font-size: 1.0625rem; font-weight: 600; margin: 0 0 0.5rem; letter-spacing: var(--heading-letter-spacing); }
    .initiative-desc { font-size: 0.9rem; color: var(--text-muted); margin: 0 0 1rem; line-height: 1.5; }
    .initiative-progress-wrap { height: 8px; background: var(--border); border-radius: 4px; overflow: hidden; margin-bottom: 0.5rem; }
    .initiative-progress-bar { height: 100%; background: var(--accent); border-radius: 4px; transition: width 0.4s ease; }
    .initiative-stats { font-size: 0.875rem; color: var(--text-muted); margin: 0 0 0.5rem; }
    .initiative-link { font-size: 0.9rem; color: var(--accent); text-decoration: none; font-weight: 500; }
    .initiative-link:hover { text-decoration: underline; }
    .initiatives-view-all { margin-top: 1.5rem; text-align: center; }
    @media (min-width: 640px) {
      .widget-initiatives { grid-template-columns: 1fr 1fr; }
    }
    @media (min-width: 960px) {
      .widget-initiatives { grid-template-columns: 1fr 1fr 1fr; }
    }
    /* Steps – How it works (numbered) */
    .widget-steps { display: flex; flex-direction: column; gap: 1.5rem; }
    .step-item { display: flex; gap: 1.25rem; align-items: flex-start; text-align: left; }
    .step-number { flex-shrink: 0; width: 2.5rem; height: 2.5rem; border-radius: 50%; background: var(--accent); color: #fff; font-weight: 600; font-size: 1rem; display: flex; align-items: center; justify-content: center; }
    .step-content { flex: 1; min-width: 0; }
    .step-title { font-size: 1.0625rem; font-weight: 600; margin: 0 0 0.35rem; letter-spacing: var(--heading-letter-spacing); }
    .step-desc { font-size: 0.9375rem; color: var(--text-muted); margin: 0; line-height: 1.55; }
    .step-link { font-size: 0.9rem; color: var(--accent); text-decoration: none; font-weight: 500; display: inline-block; margin-top: 0.5rem; }
    .step-link:hover { text-decoration: underline; }
    @media (min-width: 640px) {
      .widget-steps { flex-direction: row; flex-wrap: wrap; justify-content: center; gap: 2rem; }
      .step-item { flex: 1; min-width: 180px; max-width: 280px; flex-direction: column; align-items: center; text-align: center; }
      .step-item .step-content { text-align: center; }
    }
    .widget-logos { display: flex; flex-wrap: wrap; gap: 1.5rem; justify-content: center; align-items: center; }
    .widget-logos a { display: flex; align-items: center; color: var(--text-muted); text-decoration: none; font-size: 0.9rem; }
    .widget-logos a:hover { color: var(--accent); }
    .widget-logos img { max-height: 32px; max-width: 120px; object-fit: contain; }
    @media (min-width: 640px) {
      .widget-logos img { max-height: 40px; max-width: 140px; }
    }
    .widget-pricing { display: grid; gap: 1rem; text-align: center; grid-template-columns: 1fr; }
    .widget-pricing .section-heading { grid-column: 1 / -1; text-align: center; margin-bottom: 0.5rem; font-size: 1.75rem; font-weight: 700; letter-spacing: var(--heading-letter-spacing); color: var(--text); line-height: 1.3; }
    @media (min-width: 640px) {
      .widget-pricing .section-heading { font-size: 2.25rem; margin-bottom: 1rem; }
    }
    .widget-pricing.cols-2 { grid-template-columns: 1fr; }
    .widget-pricing.cols-3 { grid-template-columns: 1fr; }
    .widget-pricing .plan { border: 1px solid var(--border); border-radius: var(--radius); padding: 1.5rem; background: rgba(255,255,255,0.6); box-shadow: var(--shadow-sm); }
    .widget-pricing .plan.featured { border-color: var(--accent); background: rgba(15, 118, 110, 0.08); box-shadow: var(--shadow-md); }
    .widget-pricing .plan-name { font-weight: 500; margin-bottom: 0.25rem; }
    .widget-pricing .plan-price { font-size: 1.5rem; font-weight: 500; color: var(--accent); }
    .widget-pricing .plan-features { list-style: none; margin: 0.75rem 0 0; padding: 0; text-align: left; font-size: 0.9rem; color: var(--text-muted); }
    .widget-pricing .plan-cta { margin-top: 1rem; }
    @media (min-width: 600px) {
      .widget-pricing.cols-2 { grid-template-columns: 1fr 1fr; }
      .widget-pricing.cols-3 { grid-template-columns: 1fr 1fr; }
    }
    @media (min-width: 900px) {
      .widget-pricing.cols-3 { grid-template-columns: 1fr 1fr 1fr; }
    }
    .widget-product { display: grid; gap: 1.5rem; grid-template-columns: 1fr; text-align: center; }
    .widget-product .section-heading { grid-column: 1 / -1; text-align: center; margin-bottom: 0.5rem; font-size: 1.75rem; font-weight: 700; letter-spacing: var(--heading-letter-spacing); color: var(--text); line-height: 1.3; }
    .widget-product .product-card { border: 1px solid var(--border); border-radius: var(--radius); padding: 1.5rem; background: rgba(255,255,255,0.6); box-shadow: var(--shadow-sm); text-align: left; }
    .widget-product .product-image { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: var(--radius); margin-bottom: 1rem; background: var(--border); }
    .widget-product .product-name { font-weight: 600; font-size: 1.1rem; margin-bottom: 0.25rem; }
    .widget-product .product-description { font-size: 0.9rem; color: var(--text-muted); margin-bottom: 0.75rem; line-height: 1.5; }
    .widget-product .product-price { font-size: 1.25rem; font-weight: 600; color: var(--accent); margin-bottom: 1rem; }
    .widget-product .product-cta { margin-top: 0.5rem; }
    @media (min-width: 600px) {
      .widget-product.cols-2 { grid-template-columns: 1fr 1fr; }
      .widget-product.cols-3 { grid-template-columns: 1fr 1fr 1fr; }
    }
    .widget-team { display: grid; gap: 1rem; text-align: center; grid-template-columns: 1fr; }
    .widget-team.cols-2 { grid-template-columns: 1fr; }
    .widget-team.cols-3 { grid-template-columns: 1fr; }
    .widget-team .member-photo { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; margin: 0 auto 0.5rem; display: block; }
    .widget-team .member-name { font-weight: 500; }
    .widget-team .member-role { font-size: 0.9rem; color: var(--text-muted); }
    @media (min-width: 600px) {
      .widget-team.cols-2 { grid-template-columns: 1fr 1fr; }
      .widget-team.cols-3 { grid-template-columns: 1fr 1fr 1fr; }
    }
    .widget-video { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: var(--radius); }
    .widget-video iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; }
    /* Gallery: modern carousel, almost full width, expandable lightbox */
    .widget-gallery {
      width: 100vw;
      margin-left: calc(50% - 50vw);
      margin-right: calc(50% - 50vw);
      padding: 2rem 0;
      overflow: hidden;
      box-sizing: border-box;
    }
    .widget-gallery .gallery-track {
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      scroll-snap-type: x mandatory;
      scroll-behavior: smooth;
      gap: 1rem;
      padding: 0 max(1rem, calc(50vw - min(880px, 88vw) / 2));
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
      -ms-overflow-style: none;
    }
    .widget-gallery .gallery-track::-webkit-scrollbar { display: none; }
    .widget-gallery .gallery-slide {
      flex: 0 0 min(85%, 420px);
      scroll-snap-align: center;
      scroll-snap-stop: always;
    }
    .widget-gallery .gallery-slide figure {
      margin: 0;
      height: 100%;
    }
    .widget-gallery .gallery-slide img {
      width: 100%;
      height: var(--gallery-img-height, 52vmin);
      min-height: 180px;
      object-fit: cover;
      border-radius: var(--radius);
      display: block;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
    }
    .widget-gallery .gallery-slide img:hover {
      transform: scale(1.02);
      box-shadow: 0 8px 24px rgba(0,0,0,0.12);
    }
    .widget-gallery .gallery-caption {
      font-size: 0.875rem;
      color: var(--text-muted);
      margin-top: 0.5rem;
      padding: 0 0.25rem;
    }
    /* Gallery style: grid */
    .widget-gallery.gallery-style-grid .gallery-track {
      display: grid;
      overflow: visible;
      scroll-snap-type: none;
      gap: 1rem;
      padding: 0 1rem;
      max-width: min(880px, 88vw);
      margin: 0 auto;
    }
    .widget-gallery.gallery-style-grid.gallery-cols-2 .gallery-track { grid-template-columns: repeat(2, 1fr); }
    .widget-gallery.gallery-style-grid.gallery-cols-3 .gallery-track { grid-template-columns: repeat(3, 1fr); }
    .widget-gallery.gallery-style-grid .gallery-slide {
      flex: none;
      scroll-snap-align: none;
    }
    .widget-gallery.gallery-style-grid .gallery-slide img {
      min-height: 160px;
    }
    /* Gallery style: strip (compact horizontal) */
    .widget-gallery.gallery-style-strip .gallery-track {
      padding: 0 max(1rem, calc(50vw - min(880px, 88vw) / 2));
    }
    .widget-gallery.gallery-style-strip .gallery-slide {
      flex: 0 0 min(28%, 180px);
    }
    .widget-gallery.gallery-style-strip .gallery-slide img {
      height: var(--gallery-img-height, 42vmin);
      min-height: 140px;
    }
    /* Gallery lightbox */
    .gallery-lightbox {
      display: none;
      position: fixed;
      inset: 0;
      z-index: 9999;
      background: rgba(0,0,0,0.92);
      align-items: center;
      justify-content: center;
      padding: 2rem;
      box-sizing: border-box;
    }
    .gallery-lightbox.is-open { display: flex; }
    .gallery-lightbox .lightbox-backdrop {
      position: absolute;
      inset: 0;
      z-index: 0;
    }
    .gallery-lightbox .lightbox-close,
    .gallery-lightbox .lightbox-prev,
    .gallery-lightbox .lightbox-next,
    .gallery-lightbox .lightbox-content { z-index: 1; }
    .gallery-lightbox .lightbox-content {
      position: relative;
      max-width: 95vw;
      max-height: 95vh;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .gallery-lightbox .lightbox-content img {
      max-width: 95vw;
      max-height: 85vh;
      width: auto;
      height: auto;
      object-fit: contain;
      border-radius: var(--radius);
    }
    .gallery-lightbox .lightbox-caption {
      color: #fff;
      font-size: 0.9375rem;
      margin-top: 0.75rem;
      text-align: center;
      max-width: 90vw;
    }
    .gallery-lightbox .lightbox-close,
    .gallery-lightbox .lightbox-prev,
    .gallery-lightbox .lightbox-next {
      position: absolute;
      background: rgba(255,255,255,0.15);
      border: none;
      color: #fff;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      cursor: pointer;
      font-size: 1.5rem;
      line-height: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.2s;
    }
    .gallery-lightbox .lightbox-close:hover,
    .gallery-lightbox .lightbox-prev:hover,
    .gallery-lightbox .lightbox-next:hover {
      background: rgba(255,255,255,0.25);
    }
    .gallery-lightbox .lightbox-close { top: -56px; right: 0; }
    .gallery-lightbox .lightbox-prev { left: -60px; top: 50%; transform: translateY(-50%); }
    .gallery-lightbox .lightbox-next { right: -60px; top: 50%; transform: translateY(-50%); }
    @media (max-width: 640px) {
      .gallery-lightbox .lightbox-prev { left: 0.5rem; }
      .gallery-lightbox .lightbox-next { right: 0.5rem; }
      .gallery-lightbox .lightbox-close { top: 0.5rem; right: 0.5rem; }
    }
    .widget-appstores { display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: center; }
    .widget-appstores a { display: inline-block; }
    .widget-appstores img { height: 40px; width: auto; display: block; }
    .widget-divider-line { border: 0; border-top: 1px solid var(--border); margin: 1.5rem 0; }
    .widget-divider-space { height: 2rem; }
    .widget-trust { display: flex; flex-wrap: wrap; gap: 1rem; justify-content: center; align-items: center; }
    .widget-trust .trust-item { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; color: var(--text-muted); }
    .widget-trust .trust-icon { font-size: 1.25rem; }
    /* Full-width nav bar */
    .widget-nav {
      position: sticky; top: 0; z-index: 100;
      width: 100vw; margin-left: calc(50% - 50vw); margin-right: calc(50% - 50vw);
      background: #fff; border-bottom: 1px solid var(--border);
      padding: 1.25rem var(--content-padding); margin-bottom: 0;
      text-align: left; box-sizing: border-box;
      box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }
    .widget-nav .nav-inner {
      max-width: var(--content-max); margin: 0 auto;
      display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.75rem;
    }
    .widget-nav .nav-logo { font-weight: 700; color: var(--text); text-decoration: none; font-size: 1.125rem; letter-spacing: var(--heading-letter-spacing); }
    .widget-nav .nav-links { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 0.5rem 1.25rem; }
    .widget-nav .nav-links a { color: var(--text-muted); text-decoration: none; font-size: 0.9375rem; font-weight: 500; transition: color 0.15s; }
    .widget-nav .nav-links a:hover { color: var(--accent); }
    @media (min-width: 640px) {
      .widget-nav { padding: 1.5rem var(--content-padding); }
      .widget-nav .nav-logo { font-size: 1.35rem; }
      .widget-nav .nav-links { gap: 0.75rem 1.75rem; }
    }
    /* Footer: 3 sections */
    .widget-footer {
      border-top: 1px solid var(--border); padding-top: 2rem; margin-top: 0; padding-bottom: 1.5rem;
      font-size: 0.875rem; color: var(--text-muted); line-height: 1.6;
    }
    .widget-footer .footer-content { display: flex; flex-direction: column; }
    .widget-footer .footer-sections {
      display: grid; gap: 2rem; text-align: center; grid-template-columns: 1fr;
    }
    .widget-footer .footer-section { min-width: 0; }
    .widget-footer .footer-section-title {
      font-size: 0.8125rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--text-muted); margin: 0 0 0.75rem;
    }
    .widget-footer .footer-section p { margin: 0; white-space: pre-wrap; }
    .widget-footer .footer-brand .footer-section-title { font-size: 1rem; font-weight: 600; text-transform: none; letter-spacing: var(--heading-letter-spacing); color: var(--text); }
    .widget-footer .footer-links { list-style: none; margin: 0; padding: 0; }
    .widget-footer .footer-links li { margin-bottom: 0.35rem; }
    .widget-footer .footer-links a { color: var(--text-muted); text-decoration: none; }
    .widget-footer .footer-links a:hover { color: var(--accent); }
    .widget-footer .footer-copyright {
      margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--border);
      text-align: center; font-size: 0.8125rem; color: var(--text-muted);
    }
    @media (min-width: 640px) {
      .widget-footer { padding-top: 2rem; padding-bottom: 1.5rem; }
      .widget-footer .footer-sections { grid-template-columns: 1fr 1fr 1fr; text-align: left; gap: 2.5rem; }
    }
    @media (min-width: 960px) {
      .widget-footer { padding-top: 2rem; padding-bottom: 1.5rem; }
    }
    .widget-button { padding: 2rem 0; }
    .widget-text .body { max-width: 65ch; }
    @media (min-width: 640px) {
      .widget-text .body { margin-left: auto; margin-right: auto; }
    }
    .widget-text.align-center .body { margin-left: auto; margin-right: auto; }
    .widget-text.align-right .body { margin-left: auto; margin-right: 0; }
    /* Map / Location */
    .widget-map .widget-map-address { margin: 0.5rem 0 1rem; font-size: 0.95rem; color: var(--text-muted); }
    /* Announcement bar */
    .widget-announcement { width: 100vw; margin-left: calc(50% - 50vw); margin-right: calc(50% - 50vw); padding: 0.5rem var(--content-padding); text-align: center; font-size: 0.875rem; box-sizing: border-box; }
    .widget-announcement.announcement-primary { background: var(--accent); color: #fff; }
    .widget-announcement.announcement-primary .announcement-link { color: #fff; text-decoration: underline; }
    .widget-announcement.announcement-dark { background: #1c1917; color: #fff; }
    .widget-announcement.announcement-dark .announcement-link { color: #fff; text-decoration: underline; }
    .widget-announcement .announcement-text { margin: 0; }
    /* Newsletter */
    .widget-newsletter .newsletter-form { display: flex; flex-direction: row; flex-wrap: wrap; gap: 0.5rem; justify-content: center; align-items: center; margin-top: 0.5rem; }
    .widget-newsletter .newsletter-form input { flex: 1; min-width: 0; max-width: 320px; }
    /* Opening hours */
    .widget-hours { width: 100%; max-width: 400px; margin: 0 auto; border-collapse: collapse; font-size: 0.9rem; }
    .widget-hours td { padding: 0.35rem 0.75rem; border-bottom: 1px solid var(--border); }
    .widget-hours td:first-child { font-weight: 500; }
    .widget-hours td:last-child { color: var(--text-muted); }
    /* Comparison table */
    .widget-comparison-wrap { overflow-x: auto; margin: 0 -1rem; }
    .widget-comparison { width: 100%; min-width: 400px; border-collapse: collapse; font-size: 0.9rem; }
    .widget-comparison th, .widget-comparison td { padding: 0.5rem 0.75rem; border: 1px solid var(--border); text-align: center; }
    .widget-comparison th:first-child, .widget-comparison td:first-child { text-align: left; font-weight: 500; }
    .widget-comparison th { background: var(--border); font-weight: 600; }
    /* Blog / News */
    .widget-blog { text-align: left; }
    .widget-blog .blog-item { margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid var(--border); }
    .widget-blog .blog-item:last-child { border-bottom: 0; margin-bottom: 0; padding-bottom: 0; }
    .widget-blog .blog-title { font-size: 1rem; margin: 0 0 0.25rem; }
    .widget-blog .blog-title a { color: var(--text); text-decoration: none; }
    .widget-blog .blog-title a:hover { color: var(--accent); }
    .widget-blog .blog-excerpt { margin: 0; font-size: 0.9rem; color: var(--text-muted); }
    .widget-blog .blog-date { font-size: 0.8rem; color: var(--text-muted); }
    /* Reviews */
    .widget-reviews { text-align: left; }
    .widget-reviews .review-item { margin-bottom: 1.5rem; padding: 1rem; background: var(--bg); border-radius: var(--radius); }
    .widget-reviews .review-stars { color: #f59e0b; font-size: 1rem; margin-bottom: 0.25rem; }
    .widget-reviews .review-quote { margin: 0 0 0.5rem; font-style: italic; }
    .widget-reviews cite { font-size: 0.85rem; color: var(--text-muted); font-style: normal; }
    /* Accordion */
    .widget-accordion { text-align: left; max-width: 600px; margin: 0 auto; }
    .widget-accordion .accordion-item { border: 1px solid var(--border); border-radius: var(--radius); margin-bottom: 0.5rem; overflow: hidden; }
    .widget-accordion .accordion-item summary { padding: 0.75rem 1rem; cursor: pointer; font-weight: 500; list-style: none; }
    .widget-accordion .accordion-item summary::-webkit-details-marker { display: none; }
    .widget-accordion .accordion-item summary::after { content: '+'; float: right; }
    .widget-accordion .accordion-item[open] summary::after { content: '−'; }
    .widget-accordion .accordion-content { padding: 0 1rem 1rem; color: var(--text-muted); font-size: 0.9rem; }
    /* CTA banner */
    .widget-ctabanner { background: var(--accent); color: #fff; }
    .widget-ctabanner .ctabanner-inner { max-width: var(--content-max); margin: 0 auto; padding: 1.5rem var(--content-padding); }
    .widget-ctabanner .ctabanner-inner p { margin: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 0.5rem; }
    .widget-ctabanner .cta { color: #fff; border-color: #fff; }
    .widget-ctabanner .cta:hover { background: rgba(255,255,255,0.2); }
    /* Contact info */
    .widget-contactinfo { text-align: left; }
    .widget-contactinfo p { margin: 0.5rem 0; }
    .widget-contactinfo a { color: var(--accent); text-decoration: none; }
    .widget-contactinfo a:hover { text-decoration: underline; }
    .widget-contactinfo .contactinfo-links { list-style: none; margin: 0.5rem 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; }
    /* Menu */
    .widget-menu { text-align: left; }
    .widget-menu .menu-category { margin-bottom: 2rem; }
    .widget-menu .menu-cat-name { font-size: 1.1rem; margin: 0 0 0.75rem; padding-bottom: 0.35rem; border-bottom: 2px solid var(--accent); }
    .widget-menu .menu-item { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 0.25rem; margin-bottom: 0.75rem; }
    .widget-menu .menu-item-name { font-weight: 500; }
    .widget-menu .menu-item-price { color: var(--text-muted); }
    .widget-menu .menu-item-desc { margin: 0.25rem 0 0; font-size: 0.9rem; color: var(--text-muted); width: 100%; }
    /* Events */
    .widget-events { text-align: left; }
    .widget-events .event-item { margin-bottom: 1rem; padding: 0.75rem; background: var(--bg); border-radius: var(--radius); }
    .widget-events .event-title { font-weight: 500; }
    .widget-events .event-title a { color: var(--text); text-decoration: none; }
    .widget-events .event-title a:hover { color: var(--accent); }
    .widget-events .event-date, .widget-events .event-location { font-size: 0.9rem; color: var(--text-muted); margin-top: 0.25rem; }
    /* Tabs */
    .widget-tabs { text-align: left; }
    .widget-tabs .tab-labels { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-bottom: 1rem; border-bottom: 1px solid var(--border); }
    .widget-tabs .tab-label { background: none; border: none; padding: 0.5rem 1rem; font: inherit; font-size: 0.9rem; color: var(--text-muted); cursor: pointer; }
    .widget-tabs .tab-label:hover { color: var(--text); }
    .widget-tabs .tab-label.active { color: var(--accent); font-weight: 600; border-bottom: 2px solid var(--accent); margin-bottom: -1px; }
    .widget-tabs .tab-panel { display: none; padding: 0.5rem 0; }
    .widget-tabs .tab-panel.active { display: block; }
  </style>
  <noscript><style>.widget.animate-reveal{opacity:1 !important;animation:none !important}.widget.animate-in .feature-item,.widget.animate-in .stat-item,.widget.animate-in .plan,.widget.animate-in .product-card,.widget.animate-in.widget-team > *,.widget-logos.animate-in a,.widget.animate-in .trust-item{opacity:1 !important;animation:none !important}</style></noscript>
</head>
<body>
  <main>
    <div id="content"></div>
    <p class="footer" id="footer"></p>
  </main>

  <div id="legal-dialog" class="legal-dialog" aria-hidden="true" role="dialog" aria-label="Legal document">
    <div class="legal-dialog-inner">
      <h2 class="legal-dialog-title" id="legal-dialog-title"></h2>
      <div class="legal-dialog-content" id="legal-dialog-content"></div>
      <button type="button" class="cta cta-primary legal-dialog-close" id="legal-dialog-close">Close</button>
    </div>
  </div>
  <div id="gallery-lightbox" class="gallery-lightbox" aria-hidden="true" role="dialog" aria-label="Image gallery">
    <div class="lightbox-backdrop"></div>
    <button type="button" class="lightbox-close" aria-label="Close">&times;</button>
    <button type="button" class="lightbox-prev" aria-label="Previous image">&lsaquo;</button>
    <button type="button" class="lightbox-next" aria-label="Next image">&rsaquo;</button>
    <div class="lightbox-content">
      <img src="" alt="" class="lightbox-img">
      <p class="lightbox-caption"></p>
    </div>
  </div>

  <script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-app-check-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-firestore-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-functions-compat.js"></script>
  <script src="https://js.stripe.com/v3/"></script>
  <script>
    window.FIREBASE_CONFIG = window.FIREBASE_CONFIG || {
      apiKey: 'AIzaSyDgJ0MFqAHkq6BQzJ5mnrJuDIohr4KHDBc',
      authDomain: 'domain-placeholder-fbae7.firebaseapp.com',
      projectId: 'domain-placeholder-fbae7',
      storageBucket: 'domain-placeholder-fbae7.firebasestorage.app',
      messagingSenderId: '744422230015',
      appId: '1:744422230015:web:0a55403a0f5a3dcc5ac9ca',
      appCheckRecaptchaSiteKey: '',
      appCheckRecaptchaEnterpriseSiteKey: '6LcMpIcsAAAAACXBNQZ-e9mCa0F1t4Pt1_IU7I4f'
    };
  </script>
  <script>
    (function() {
      var hostname = window.location.hostname.replace(/^www\./, '') || '—';
      var path = (window.location.pathname || '').replace(/^\/+|\/+$/g, '');
      var contentEl = document.getElementById('content');
      var footerEl = document.getElementById('footer');
      var pageTitle = document.getElementById('page-title');

      pageTitle.textContent = hostname !== '—' ? hostname + ' — Registered' : 'Domain';

      firebase.initializeApp(window.FIREBASE_CONFIG);
      var cfg = window.FIREBASE_CONFIG || {};
      var enterpriseKey = cfg.appCheckRecaptchaEnterpriseSiteKey || '';
      var v3Key = cfg.appCheckRecaptchaSiteKey || '';
      if (enterpriseKey) {
        firebase.appCheck().activate(new firebase.appCheck.ReCaptchaEnterpriseProvider(enterpriseKey), true);
      } else if (v3Key) {
        firebase.appCheck().activate(v3Key, true);
      }
      var db = firebase.firestore();

      function getCookie(name) {
        var m = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/([.*+?^${}()|[\]\\])/g, '\\$1') + '=([^;]*)'));
        return m ? decodeURIComponent(m[1]) : null;
      }
      function setCookie(name, value, days) {
        var expires = '';
        if (days) {
          var d = new Date();
          d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
          expires = '; expires=' + d.toUTCString();
        }
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; SameSite=Lax';
      }

      function escapeHtml(s) {
        if (s == null || s === undefined) return '';
        var div = document.createElement('div');
        div.textContent = s;
        return div.innerHTML;
      }

      var altHostname = hostname.startsWith('www.') ? hostname.replace(/^www\./, '') : 'www.' + hostname;

      var ASSESSMENT_PRODUCT_IDS = ['npi_test', 'big_five', 'dark_triad', 'phq9', 'gad7', 'pss10', 'who5', 'holland', 'mbti', 'fitness_membership'];

      var NPI_ITEMS = [
        { a: 'I really like to be the center of attention', b: 'It makes me uncomfortable to be the center of attention', scoreA: 1 },
        { a: 'I am no better or no worse than most people', b: 'I think I am a special person', scoreA: 0 },
        { a: 'Everybody likes to hear my stories', b: 'Sometimes I tell good stories', scoreA: 1 },
        { a: 'I usually get the respect that I deserve', b: 'I insist upon getting the respect that is due me', scoreA: 0 },
        { a: "I don't mind following orders", b: 'I like having authority over people', scoreA: 0 },
        { a: 'I am going to be a great person', b: 'I hope I am going to be successful', scoreA: 1 },
        { a: 'People sometimes believe what I tell them', b: 'I can make anybody believe anything I want them to', scoreA: 0 },
        { a: 'I expect a great deal from other people', b: 'I like to do things for other people', scoreA: 1 },
        { a: 'I like to be the center of attention', b: 'I prefer to blend in with the crowd', scoreA: 1 },
        { a: 'I am much like everybody else', b: 'I am an extraordinary person', scoreA: 0 },
        { a: 'I always know what I am doing', b: 'Sometimes I am not sure of what I am doing', scoreA: 1 },
        { a: "I don't like it when I find myself manipulating people", b: 'I find it easy to manipulate people', scoreA: 0 },
        { a: "Being an authority doesn't mean that much to me", b: 'People always seem to recognize my authority', scoreA: 0 },
        { a: 'I know that I am good because everybody keeps telling me so', b: 'When people compliment me I sometimes get embarrassed', scoreA: 1 },
        { a: 'I try not to be a show off', b: 'I am apt to show off if I get the chance', scoreA: 0 },
        { a: 'I am more capable than other people', b: 'There is a lot that I can learn from other people', scoreA: 1 }
      ];

      var MBTI_ITEMS = [
        { a: 'You enjoy being the center of attention at social gatherings', b: 'You prefer to observe and listen at social gatherings', factor: 'E', scoreA: 1 },
        { a: 'You feel energized after spending time with people', b: 'You feel energized after spending time alone', factor: 'E', scoreA: 1 },
        { a: 'You tend to speak your thoughts out loud', b: 'You tend to think through ideas before speaking', factor: 'E', scoreA: 1 },
        { a: 'You prefer a wide circle of acquaintances', b: 'You prefer a few close friends', factor: 'E', scoreA: 1 },
        { a: 'You are outgoing and sociable in new situations', b: 'You are reserved and take time to warm up in new situations', factor: 'E', scoreA: 1 },
        { a: 'You focus on facts and concrete details', b: 'You focus on patterns and possibilities', factor: 'S', scoreA: 1 },
        { a: 'You prefer step-by-step instructions', b: 'You prefer to see the big picture first', factor: 'S', scoreA: 1 },
        { a: 'You trust experience and what has worked before', b: 'You trust intuition and new ideas', factor: 'S', scoreA: 1 },
        { a: 'You are practical and down-to-earth', b: 'You are imaginative and abstract', factor: 'S', scoreA: 1 },
        { a: 'You notice specifics and remember details', b: 'You notice connections and meanings', factor: 'S', scoreA: 1 },
        { a: 'You make decisions based on logic and analysis', b: 'You make decisions based on values and how people will feel', factor: 'T', scoreA: 1 },
        { a: 'You value truth and fairness over harmony', b: 'You value harmony and compassion over being right', factor: 'T', scoreA: 1 },
        { a: 'You prefer to be objective and detached when evaluating', b: 'You prefer to consider how decisions affect people', factor: 'T', scoreA: 1 },
        { a: 'You are direct and straightforward in communication', b: "You are tactful and considerate of others' feelings", factor: 'T', scoreA: 1 },
        { a: 'You prioritize consistency and principles', b: 'You prioritize empathy and circumstances', factor: 'T', scoreA: 1 },
        { a: 'You prefer a planned and organized schedule', b: 'You prefer to stay flexible and spontaneous', factor: 'J', scoreA: 1 },
        { a: 'You like to finish things before starting new ones', b: 'You like to juggle multiple projects', factor: 'J', scoreA: 1 },
        { a: 'You make decisions quickly and stick to them', b: 'You prefer to keep options open', factor: 'J', scoreA: 1 },
        { a: 'You feel more comfortable when things are decided', b: 'You feel more comfortable when things are open-ended', factor: 'J', scoreA: 1 },
        { a: 'You prefer structure and closure', b: 'You prefer adaptability and discovery', factor: 'J', scoreA: 1 }
      ];
      var MBTI_ARCHETYPES = {
        INTJ: 'Architect', INTP: 'Logician', ENTJ: 'Commander', ENTP: 'Debater',
        INFJ: 'Advocate', INFP: 'Mediator', ENFJ: 'Protagonist', ENFP: 'Campaigner',
        ISTJ: 'Logistician', ISFJ: 'Defender', ESTJ: 'Executive', ESFJ: 'Consul',
        ISTP: 'Virtuoso', ISFP: 'Adventurer', ESTP: 'Entrepreneur', ESFP: 'Entertainer'
      };

      var PHQ9_ITEMS = [
        'Little interest or pleasure in doing things',
        'Feeling down, depressed, or hopeless',
        'Trouble falling or staying asleep, or sleeping too much',
        'Feeling tired or having little energy',
        'Poor appetite or overeating',
        'Feeling bad about yourself — or that you are a failure or have let yourself or your family down',
        'Trouble concentrating on things, such as reading the newspaper or watching television',
        'Moving or speaking so slowly that other people could have noticed? Or the opposite — being so fidgety or restless that you have been moving around a lot more than usual',
        'Thoughts that you would be better off dead or of hurting yourself in some way'
      ];
      var PHQ9_LABELS = ['Not at all', 'Several days', 'More than half the days', 'Nearly every day'];

      var GAD7_ITEMS = [
        'Feeling nervous, anxious, or on edge',
        'Not being able to stop or control worrying',
        'Worrying too much about different things',
        'Trouble relaxing',
        "Being so restless that it's hard to sit still",
        'Becoming easily annoyed or irritable',
        'Feeling afraid as if something awful might happen'
      ];

      var PSS10_ITEMS = [
        { text: 'In the last month, how often have you been upset because of something that happened unexpectedly?', reverse: false },
        { text: 'In the last month, how often have you felt unable to control the important things in your life?', reverse: false },
        { text: 'In the last month, how often have you felt nervous and "stressed"?', reverse: false },
        { text: 'In the last month, how often have you felt confident about your ability to handle your personal problems?', reverse: true },
        { text: 'In the last month, how often have you felt that things were going your way?', reverse: true },
        { text: 'In the last month, how often have you found that you could not cope with all the things that you had to do?', reverse: false },
        { text: 'In the last month, how often have you been able to control irritations in your life?', reverse: true },
        { text: 'In the last month, how often have you felt that you were on top of things?', reverse: true },
        { text: 'In the last month, how often have you been angered because of things that were outside of your control?', reverse: false },
        { text: 'In the last month, how often have you felt difficulties were piling up so high that you could not overcome them?', reverse: false }
      ];
      var PSS10_LABELS = ['Never', 'Almost never', 'Sometimes', 'Fairly often', 'Very often'];

      var WHO5_ITEMS = [
        'I have felt cheerful and in good spirits',
        'I have felt calm and relaxed',
        'I have felt active and vigorous',
        'I woke up feeling fresh and rested',
        'My daily life has been filled with things that interest me'
      ];
      var WHO5_LABELS = ['At no time', 'Some of the time', 'Less than half the time', 'More than half the time', 'Most of the time', 'All of the time'];

      var BFI10_ITEMS = [
        { text: 'I see myself as someone who is reserved', factor: 'E', reverse: true },
        { text: 'I see myself as someone who is generally trusting', factor: 'A', reverse: false },
        { text: 'I see myself as someone who tends to be lazy', factor: 'C', reverse: true },
        { text: 'I see myself as someone who is relaxed, handles stress well', factor: 'N', reverse: true },
        { text: 'I see myself as someone who has few artistic interests', factor: 'O', reverse: true },
        { text: 'I see myself as someone who is outgoing, sociable', factor: 'E', reverse: false },
        { text: 'I see myself as someone who tends to find fault with others', factor: 'A', reverse: true },
        { text: 'I see myself as someone who does a thorough job', factor: 'C', reverse: false },
        { text: 'I see myself as someone who gets nervous easily', factor: 'N', reverse: false },
        { text: 'I see myself as someone who has an active imagination', factor: 'O', reverse: false }
      ];
      var BFI10_FACTORS = { E: 'Extraversion', A: 'Agreeableness', C: 'Conscientiousness', N: 'Neuroticism', O: 'Openness' };

      var SD3_ITEMS = [
        { text: 'People see me as a natural leader', factor: 'N' },
        { text: 'I hate being the center of attention', factor: 'N', reverse: true },
        { text: 'Many group activities tend to be dull without me', factor: 'N' },
        { text: 'I know that I am special because everyone keeps telling me so', factor: 'N' },
        { text: 'I like to get acquainted with important people', factor: 'N' },
        { text: 'I feel embarrassed if someone compliments me', factor: 'N', reverse: true },
        { text: 'I have been compared to famous people', factor: 'N' },
        { text: 'I am an average person', factor: 'N', reverse: true },
        { text: 'I insist on getting the respect I deserve', factor: 'N' },
        { text: 'I like to use clever manipulation to get my way', factor: 'M' },
        { text: 'I avoid dangerous situations', factor: 'M', reverse: true },
        { text: 'Payback needs to be quick and nasty', factor: 'M' },
        { text: 'I have been called cold-blooded or vindictive', factor: 'M' },
        { text: 'I avoid direct conflict with others', factor: 'M', reverse: true },
        { text: 'It\'s not wise to tell your secrets', factor: 'M' },
        { text: 'I make sure my plans benefit me, not others', factor: 'M' },
        { text: 'Most people can be used', factor: 'M' },
        { text: 'I like to get revenge on authorities', factor: 'M' },
        { text: 'I like to get revenge on people', factor: 'P' },
        { text: 'I avoid trouble', factor: 'P', reverse: true },
        { text: 'I like to pick on losers', factor: 'P' },
        { text: 'I say whatever it takes to get what I want', factor: 'P' },
        { text: 'I like to see people hurt', factor: 'P' },
        { text: 'I have never gotten into trouble with the law', factor: 'P', reverse: true },
        { text: 'I enjoy having sex with people I hardly know', factor: 'P' },
        { text: 'I\'ll say anything to get what I want', factor: 'P' },
        { text: 'People who mess with me always regret it', factor: 'P' }
      ];
      var SD3_FACTORS = { N: 'Narcissism', M: 'Machiavellianism', P: 'Psychopathy' };

      var HOLLAND_ITEMS = [
        { text: 'Test the quality of parts before shipment', type: 'R' },
        { text: 'Study the structure of the human body', type: 'I' },
        { text: 'Conduct a musical choir', type: 'A' },
        { text: 'Give career guidance to people', type: 'S' },
        { text: 'Sell restaurant franchises to individuals', type: 'E' },
        { text: 'Generate monthly payroll checks', type: 'C' },
        { text: 'Design artwork for magazines', type: 'A' },
        { text: 'Help people with drug or alcohol problems', type: 'S' },
        { text: 'Manage a retail store', type: 'E' },
        { text: 'Develop a new medicine', type: 'I' },
        { text: 'Repair household appliances', type: 'R' },
        { text: 'Prepare financial reports', type: 'C' },
        { text: 'Write stories or articles', type: 'A' },
        { text: 'Teach children how to read', type: 'S' },
        { text: 'Run a machine in a factory', type: 'R' },
        { text: 'Conduct market research surveys', type: 'I' },
        { text: 'Sell real estate', type: 'E' },
        { text: 'Organize office files', type: 'C' }
      ];
      var HOLLAND_TYPES = { R: 'Realistic', I: 'Investigative', A: 'Artistic', S: 'Social', E: 'Enterprising', C: 'Conventional' };

      function getLibraryTopic(productId) {
        if (['phq9'].indexOf(productId) >= 0) return 'depression';
        if (['gad7'].indexOf(productId) >= 0) return 'anxiety';
        if (['pss10'].indexOf(productId) >= 0) return 'stress';
        if (['who5'].indexOf(productId) >= 0) return 'wellbeing';
        if (['npi_test', 'big_five', 'dark_triad', 'mbti'].indexOf(productId) >= 0) return 'personality';
        if (['holland'].indexOf(productId) >= 0) return 'career';
        return null;
      }

      function getRecommendations(productId, score, scores) {
        var recs = [];
        if (productId === 'phq9') {
          if (score >= 10) recs.push('Consider speaking with a healthcare provider or therapist.');
          if (score >= 15) recs.push('Behavioral activation can help — try the exercise below.');
          if (score >= 20) recs.push('Please reach out for support. You don\'t have to face this alone.');
        }
        if (productId === 'gad7') {
          if (score >= 10) recs.push('Consider speaking with a healthcare provider or therapist.');
          if (score >= 5) recs.push('Grounding and breathing exercises may help — try them below.');
        }
        if (productId === 'pss10') {
          if (score >= 20) recs.push('Stress management techniques and lifestyle changes may help.');
          recs.push('Identify one stressor you can address this week.');
        }
        if (productId === 'who5') {
          if (score < 13) recs.push('Consider speaking with a healthcare provider or counselor.');
          recs.push('Small daily habits — sleep, movement, connection — can improve wellbeing.');
        }
        return recs;
      }

      function renderResourcesSection(productId, result, library) {
        var topic = getLibraryTopic(productId);
        var score = result && result.score != null ? result.score : 0;
        var scores = result && result.scores ? result.scores : {};
        var recs = getRecommendations(productId, score, scores);
        var topics = (library && library.topics) || {};
        var exercises = (library && library.exercises) || [];
        var crisisResources = (library && library.crisisResources) || '';
        var h = '<div id="members-resources" style="margin-top:3rem;padding-top:2rem;border-top:1px solid var(--border)">';
        h += '<h3 style="margin-bottom:1rem;font-size:1.25rem">Resources</h3>';
        if (recs.length > 0) {
          h += '<p style="font-weight:500;margin-bottom:0.5rem;color:var(--text)">Based on your results:</p>';
          h += '<ul style="margin-bottom:1.5rem;padding-left:1.25rem;color:var(--text-muted)">';
          recs.forEach(function(r) { h += '<li style="margin-bottom:0.35rem">' + r + '</li>'; });
          h += '</ul>';
        }
        if (topic && topics[topic]) {
          var lib = topics[topic];
          h += '<div style="margin-bottom:1.5rem;padding:1rem;background:rgba(255,255,255,0.6);border-radius:var(--radius);border:1px solid var(--border)">';
          h += '<p style="font-weight:500;margin-bottom:0.5rem">' + (lib.title || '') + '</p>';
          h += '<p style="font-size:0.95rem;color:var(--text-muted);margin-bottom:0.75rem;line-height:1.6">' + (lib.shortInfo || '') + '</p>';
          h += '<p style="font-size:0.9rem;font-weight:500;margin-bottom:0.35rem">Coping strategies:</p>';
          h += '<ul style="margin:0;padding-left:1.25rem;font-size:0.9rem;color:var(--text-muted);line-height:1.5">';
          (lib.copingStrategies || []).forEach(function(s) { h += '<li>' + s + '</li>'; });
          h += '</ul>';
          h += '<p style="font-size:0.9rem;margin-top:0.75rem;color:var(--text-muted)">' + (lib.whenToSeekHelp || '') + '</p>';
          h += '</div>';
        }
        h += '<p style="font-weight:500;margin-bottom:0.5rem">Guided exercises</p>';
        exercises.forEach(function(ex) {
          h += '<details style="margin-bottom:0.5rem;border:1px solid var(--border);border-radius:var(--radius);background:rgba(255,255,255,0.5)">';
          h += '<summary style="padding:0.75rem 1rem;cursor:pointer;font-weight:500">' + (ex.title || '') + '</summary>';
          h += '<div style="padding:0 1rem 1rem;font-size:0.9rem;color:var(--text-muted)">';
          h += '<p style="margin-bottom:0.5rem">' + (ex.desc || '') + '</p>';
          h += '<ol style="margin:0;padding-left:1.25rem">';
          (ex.steps || []).forEach(function(s) { h += '<li style="margin-bottom:0.25rem">' + s + '</li>'; });
          h += '</ol></div></details>';
        });
        if (crisisResources) h += '<p style="font-size:0.85rem;margin-top:1rem;color:var(--text-muted)">' + crisisResources + '</p>';
        h += '</div>';
        return h;
      }

      function fetchAndRenderResources(domainKey, productId, result, placeholderId) {
        var getContent = firebase.app().functions('us-central1').httpsCallable('getMembersContent');
        getContent({ domain: domainKey }).then(function(res) {
          var library = res && res.data && res.data.library ? res.data.library : null;
          var html = renderResourcesSection(productId, result, library);
          var el = document.getElementById(placeholderId);
          if (el) el.outerHTML = html;
        }).catch(function() {
          var el = document.getElementById(placeholderId);
          if (el) el.outerHTML = '<div id="members-resources" style="margin-top:3rem;padding-top:2rem;border-top:1px solid var(--border)"><p style="color:var(--text-muted)">Resources are temporarily unavailable.</p></div>';
        });
      }

      function initMembersArea() {
        pageTitle.textContent = hostname !== '—' ? hostname + ' — Members' : 'Members';
        footerEl.textContent = '';
        var domainKey = hostname.replace(/^www\./, '').toLowerCase();
        db.collection('domains').doc(domainKey).get().catch(function() { return { exists: false }; }).then(function(snap) {
          var doc = snap && snap.exists ? snap : null;
          if (!doc || !doc.exists) {
            doc = null;
            return db.collection('domains').doc('www.' + domainKey).get().catch(function() { return { exists: false }; });
          }
          return Promise.resolve(doc);
        }).then(function(snap) {
          var domainDoc = snap && snap.exists ? snap : null;
          if (!domainDoc) {
            contentEl.innerHTML = '<section class="widget widget-hero" style="padding:3rem 1.5rem"><h1 class="domain">Members area</h1><p>This site does not have a members area.</p><a href="/" class="cta cta-primary" style="display:inline-block;margin-top:1rem">Back to home</a></section>';
            return;
          }
          var domainData = domainDoc.data();
          var productId = (domainData.productId || '').toString().trim();
          if (ASSESSMENT_PRODUCT_IDS.indexOf(productId) < 0) {
            contentEl.innerHTML = '<section class="widget widget-hero" style="padding:3rem 1.5rem"><h1 class="domain">Members area</h1><p>Members content is coming soon for this site.</p><a href="/" class="cta cta-primary" style="display:inline-block;margin-top:1rem">Back to home</a></section>';
            return;
          }
          var auth = firebase.auth();
          auth.onAuthStateChanged(function(user) {
            if (!user) {
              renderMembersLoginSignup(domainKey, productId, domainData);
              return;
            }
            var accessRef = db.collection('members_access').doc(domainKey + '_' + user.uid);
            accessRef.get().then(function(accessSnap) {
              var data = accessSnap.exists ? accessSnap.data() : {};
              var statusOk = data.status === 'active' || data.active === true;
              var expiresAt = data.expiresAt;
              var expiresAtSeconds = data.expiresAtSeconds;
              var now = Date.now() / 1000;
              var expired = false;
              if (expiresAt && expiresAt.toMillis) expired = expiresAt.toMillis() < Date.now();
              else if (typeof expiresAtSeconds === 'number') expired = expiresAtSeconds < now;
              var hasAccess = accessSnap.exists && statusOk && !expired;
              if (!hasAccess) {
                var pendingCheckout = sessionStorage.getItem('membersPendingCheckout');
                if (pendingCheckout) sessionStorage.removeItem('membersPendingCheckout');
                var stripeId = (domainData.stripeMembersPriceId || '').toString().trim();
                var hasStripe = stripeId.startsWith('price_') || stripeId.startsWith('prod_');
                var embedEl = document.getElementById('members-checkout-embed');
                if (embedEl && embedEl.parentNode) {
                  mountStripeEmbedInPlace(domainKey, user, productId, hasStripe);
                } else {
                  renderMembersPaymentInline(domainKey, user, productId, hasStripe);
                }
                return;
              }
              db.collection('test_results').where('domain', '==', domainKey).where('userId', '==', user.uid).orderBy('completedAt', 'desc').limit(1).get().then(function(resultsSnap) {
                var latestResult = resultsSnap.docs.length > 0 ? resultsSnap.docs[0].data() : null;
                renderMembersContent(domainKey, user, latestResult, productId);
              }).catch(function() {
                renderMembersContent(domainKey, user, null, productId);
              });
            }).catch(function() {
              var stripeId = (domainData.stripeMembersPriceId || '').toString().trim();
              var hasStripe = stripeId.startsWith('price_') || stripeId.startsWith('prod_');
              var embedEl = document.getElementById('members-checkout-embed');
              if (embedEl && embedEl.parentNode) {
                mountStripeEmbedInPlace(domainKey, user, productId, hasStripe);
              } else {
                renderMembersPaymentInline(domainKey, user, productId, hasStripe);
              }
            });
          });
        });
      }

      function membersAuthErrorMessage(err) {
        var msg = (err && err.message) ? err.message : '';
        var code = (err && err.code) ? err.code : '';
        if (code === 'internal' || msg.toLowerCase().indexOf('internal') >= 0) {
          return 'Something went wrong. Please try again.';
        }
        if (msg) return msg;
        return 'Something went wrong. Please try again.';
      }

      function renderMembersSignupFlow(domainKey, productId, domainData, fromSignup) {
        domainData = domainData || {};
        var signupWidgets = Array.isArray(domainData.signupFlowWidgets) ? domainData.signupFlowWidgets : [];
        function getStepConfig(stepNum) {
          for (var i = 0; i < signupWidgets.length; i++) {
            var w = signupWidgets[i];
            if (w && w.config && Number(w.config.stepNumber) === stepNum) return w.config;
          }
          return null;
        }
        var step = 1;
        footerEl.textContent = '';
        function render() {
          var stepLabel = 'STEP ' + step + ' of 2';
          var cfg = getStepConfig(step);
          var productName = (cfg && cfg.productName) ? cfg.productName : 'Members area';
          var price = (cfg && cfg.price) ? cfg.price : '';
          var leftTitle = (cfg && cfg.title) ? cfg.title : (step === 1 ? 'Create your account' : 'Enter payment details');
          var leftDesc = (cfg && cfg.description) ? cfg.description : (step === 1
            ? 'Create an account to access the members area. You\'ll enter your payment information in the next step.'
            : 'Complete your payment to get full access. Your card will be charged according to your subscription plan.');
          var trustHtml = (cfg && cfg.trustText) ? cfg.trustText.split('\n').filter(Boolean).map(function(p) { return '<p>' + escapeHtml(p) + '</p>'; }).join('') : '<p><strong>Secure server.</strong> We use SSL encryption to protect your information. Your payment details are never stored on our servers.</p><p>Cancel anytime from your account settings.</p>';
          var html = '<section class="members-signup-flow">';
          html += '<div class="step-side">';
          html += '<div class="step-counter">' + escapeHtml(stepLabel) + '</div>';
          if (productName) html += '<div class="step-product">' + escapeHtml(productName) + '</div>';
          if (price) html += '<div class="step-price">' + escapeHtml(price) + '</div>';
          html += '<h2>' + escapeHtml(leftTitle) + '</h2>';
          html += '<div class="step-desc"><p>' + escapeHtml(leftDesc) + '</p>' + trustHtml + '</div>';
          html += '</div>';
          html += '<div class="form-side">';
          if (step === 1) {
            html += '<div class="members-auth-tabs" id="members-auth-tabs">';
            html += '<button type="button" id="members-tab-login" class="' + (fromSignup ? '' : 'is-active') + '">Sign in</button>';
            html += '<button type="button" id="members-tab-signup" class="' + (fromSignup ? 'is-active' : '') + '">Sign up</button></div>';
            html += '<form id="members-auth-form" class="members-auth-form">';
            html += '<div id="members-auth-error" class="members-auth-error"></div>';
            html += '<div class="form-group"><label for="members-email">Email</label><input type="email" id="members-email" required placeholder="you@example.com" autocomplete="email"></div>';
            html += '<div class="form-group"><label for="members-password">Password</label><div class="password-wrap"><input type="password" id="members-password" required minlength="6" placeholder="At least 6 characters" autocomplete="current-password"><button type="button" class="password-toggle" id="members-password-toggle" aria-label="Show password"><span class="icon-show"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="icon-hide" style="display:none"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span></button></div></div>';
            html += '<div class="form-group" id="members-password-confirm-wrap" style="display:' + (fromSignup ? 'block' : 'none') + '"><label for="members-password-confirm">Confirm password</label><div class="password-wrap"><input type="password" id="members-password-confirm" minlength="6" placeholder="Re-enter your password" autocomplete="new-password"><button type="button" class="password-toggle" id="members-password-confirm-toggle" aria-label="Show password"><span class="icon-show"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="icon-hide" style="display:none"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span></button></div></div>';
            html += '<button type="submit" class="cta cta-primary auth-submit" id="members-auth-btn">' + (fromSignup ? 'Create account' : 'Sign in') + '</button>';
            html += '</form>';
            html += '<div class="payment-placeholder disabled" id="members-payment-placeholder"><span>Complete step 1 to enter payment details</span></div>';
          } else {
            html += '<div id="members-checkout-embed" style="min-height:400px"></div>';
            html += '<p style="margin-top:1rem;display:none" id="members-pay-fallback-wrap"><button type="button" class="cta cta-primary" id="members-pay-fallback-btn">Continue to payment</button></p>';
          }
          html += '</div></section>';
          html += '<p style="margin-top:1.5rem;text-align:center"><a href="/" class="members-auth-back">← Back to home</a></p>';
          contentEl.innerHTML = html;
          if (step === 1) {
            var tabLogin = document.getElementById('members-tab-login');
            var tabSignup = document.getElementById('members-tab-signup');
            var confirmWrap = document.getElementById('members-password-confirm-wrap');
            var confirmInput = document.getElementById('members-password-confirm');
            var authBtn = document.getElementById('members-auth-btn');
            var form = document.getElementById('members-auth-form');
            var errorEl = document.getElementById('members-auth-error');
            var isSignup = fromSignup;
            function setMode(signup) {
              isSignup = signup;
              if (tabLogin) tabLogin.classList.toggle('is-active', !signup);
              if (tabSignup) tabSignup.classList.toggle('is-active', signup);
              if (confirmWrap) confirmWrap.style.display = signup ? 'block' : 'none';
              if (confirmInput) confirmInput.required = signup;
              if (authBtn) authBtn.textContent = signup ? 'Create account' : 'Sign in';
            }
            if (tabLogin) tabLogin.onclick = function() { setMode(false); if (errorEl) errorEl.textContent = ''; };
            if (tabSignup) tabSignup.onclick = function() { setMode(true); if (errorEl) errorEl.textContent = ''; };
            function setupPasswordToggle(btnId, inputId) {
              var btn = document.getElementById(btnId);
              var input = document.getElementById(inputId);
              if (!btn || !input) return;
              btn.onclick = function() {
                var isHidden = input.type === 'password';
                input.type = isHidden ? 'text' : 'password';
                btn.setAttribute('aria-label', isHidden ? 'Hide password' : 'Show password');
                var show = btn.querySelector('.icon-show');
                var hide = btn.querySelector('.icon-hide');
                if (show) show.style.display = isHidden ? 'none' : '';
                if (hide) hide.style.display = isHidden ? '' : 'none';
              };
            }
            setupPasswordToggle('members-password-toggle', 'members-password');
            setupPasswordToggle('members-password-confirm-toggle', 'members-password-confirm');
            form.onsubmit = function(e) {
              e.preventDefault();
              var email = document.getElementById('members-email').value.trim().toLowerCase();
              var password = document.getElementById('members-password').value;
              if (isSignup && password !== confirmInput.value) { errorEl.textContent = 'Passwords do not match'; return; }
              authBtn.disabled = true;
              authBtn.textContent = isSignup ? 'Creating account…' : 'Signing in…';
              errorEl.textContent = '';
              var fn = isSignup ? firebase.app().functions('us-central1').httpsCallable('membersSignUp') : firebase.app().functions('us-central1').httpsCallable('membersSignIn');
              fn({ domain: domainKey, email: email, password: password }).then(function(res) {
                var token = res.data && res.data.customToken;
                if (!token) { errorEl.textContent = 'Something went wrong.'; authBtn.disabled = false; authBtn.textContent = isSignup ? 'Create account' : 'Sign in'; return; }
                if (isSignup) sessionStorage.setItem('membersPendingCheckout', '1');
                return firebase.auth().signInWithCustomToken(token);
              }).then(function() {
                authBtn.disabled = false;
                authBtn.textContent = isSignup ? 'Create account' : 'Sign in';
                step = 2;
                render();
                mountStripeEmbedInPlace(domainKey, firebase.auth().currentUser, productId, true);
                setupPayFallback(domainKey);
              }).catch(function(err) {
                errorEl.textContent = membersAuthErrorMessage(err);
                authBtn.disabled = false;
                authBtn.textContent = isSignup ? 'Create account' : 'Sign in';
              });
            };
          } else {
            mountStripeEmbedInPlace(domainKey, firebase.auth().currentUser, productId, true);
            setupPayFallback(domainKey);
          }
        }
        render();
      }

      function renderMembersLoginSignup(domainKey, productId, domainData) {
        domainData = domainData || {};
        var params = new URLSearchParams(window.location.search || '');
        var fromSignup = params.get('signup') === '1' || params.get('action') === 'signup';
        var plan = params.get('plan') || '';
        var stripeId = (domainData.stripeMembersPriceId || '').toString().trim();
        var hasStripe = stripeId.startsWith('price_') || stripeId.startsWith('prod_');
        if (hasStripe) {
          renderMembersSignupFlow(domainKey, productId, domainData, fromSignup);
          return;
        }
        var subtitle = fromSignup ? 'Create an account to get started.' : 'Sign in or create an account to access the assessment.';
        if (fromSignup && plan) {
          var planNames = { explorer: 'Explorer', engager: 'Engager', activator: 'Activator', premium: 'Premium' };
          var planLabel = planNames[plan] || plan;
          subtitle = 'Create an account to continue with the ' + escapeHtml(planLabel) + ' plan.';
        }

        var html = '<section class="members-auth">';
        html += '<h1 class="domain">Members area</h1>';
        html += '<p class="members-auth-subtitle">' + escapeHtml(subtitle) + '</p>';
        html += '<div class="members-auth-card">';
        html += '<div class="members-auth-tabs" id="members-auth-tabs">';
        html += '<button type="button" id="members-tab-login" class="is-active">Sign in</button>';
        html += '<button type="button" id="members-tab-signup">Sign up</button>';
        html += '</div>';
        html += '<form id="members-auth-form" class="members-auth-form">';
        html += '<div id="members-auth-error" class="members-auth-error"></div>';
        html += '<div class="form-group"><label for="members-email">Email</label><input type="email" id="members-email" required placeholder="you@example.com" autocomplete="email"></div>';
        html += '<div class="form-group"><label for="members-password">Password</label><div class="password-wrap"><input type="password" id="members-password" required minlength="6" placeholder="At least 6 characters" autocomplete="current-password"><button type="button" class="password-toggle" id="members-password-toggle" aria-label="Show password" title="Show password"><span class="icon-show"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="icon-hide" style="display:none"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span></button></div></div>';
        html += '<div class="form-group" id="members-password-confirm-wrap" style="display:none"><label for="members-password-confirm">Confirm password</label><div class="password-wrap"><input type="password" id="members-password-confirm" minlength="6" placeholder="Re-enter your password" autocomplete="new-password"><button type="button" class="password-toggle" id="members-password-confirm-toggle" aria-label="Show password" title="Show password"><span class="icon-show"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="icon-hide" style="display:none"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span></button></div></div>';
        html += '<button type="submit" class="cta cta-primary auth-submit" id="members-auth-btn">Sign in</button>';
        html += '</form></div>';
        html += '<p style="margin-top:1.5rem"><a href="/" class="members-auth-back">← Back to home</a></p></section>';
        contentEl.innerHTML = html;
        var isSignup = false;
        var tabLogin = document.getElementById('members-tab-login');
        var tabSignup = document.getElementById('members-tab-signup');
        var confirmWrap = document.getElementById('members-password-confirm-wrap');
        var confirmInput = document.getElementById('members-password-confirm');
        var authBtn = document.getElementById('members-auth-btn');
        var form = document.getElementById('members-auth-form');
        var errorEl = document.getElementById('members-auth-error');
        function setMode(signup) {
          isSignup = signup;
          tabLogin.classList.toggle('is-active', !signup);
          tabSignup.classList.toggle('is-active', signup);
          confirmWrap.style.display = signup ? 'block' : 'none';
          confirmInput.required = signup;
          authBtn.textContent = signup ? 'Create account' : 'Sign in';
        }
        tabLogin.onclick = function() { setMode(false); errorEl.textContent = ''; };
        tabSignup.onclick = function() { setMode(true); errorEl.textContent = ''; };
        if (fromSignup) setMode(true);
        function setupPasswordToggle(btnId, inputId) {
          var btn = document.getElementById(btnId);
          var input = document.getElementById(inputId);
          if (!btn || !input) return;
          btn.onclick = function() {
            var isHidden = input.type === 'password';
            input.type = isHidden ? 'text' : 'password';
            btn.setAttribute('aria-label', isHidden ? 'Hide password' : 'Show password');
            btn.setAttribute('title', isHidden ? 'Hide password' : 'Show password');
            btn.querySelector('.icon-show').style.display = isHidden ? 'none' : '';
            btn.querySelector('.icon-hide').style.display = isHidden ? '' : 'none';
          };
        }
        setupPasswordToggle('members-password-toggle', 'members-password');
        setupPasswordToggle('members-password-confirm-toggle', 'members-password-confirm');
        form.onsubmit = function(e) {
          e.preventDefault();
          var email = document.getElementById('members-email').value.trim().toLowerCase();
          var password = document.getElementById('members-password').value;
          if (isSignup) {
            if (password !== confirmInput.value) { errorEl.textContent = 'Passwords do not match'; return; }
          }
          authBtn.disabled = true;
          authBtn.textContent = isSignup ? 'Creating account…' : 'Signing in…';
          errorEl.textContent = '';
          var fn = isSignup ? firebase.app().functions('us-central1').httpsCallable('membersSignUp') : firebase.app().functions('us-central1').httpsCallable('membersSignIn');
          fn({ domain: domainKey, email: email, password: password }).then(function(res) {
            var token = res.data && res.data.customToken;
            if (!token) { errorEl.textContent = 'Something went wrong.'; authBtn.disabled = false; authBtn.textContent = isSignup ? 'Create account' : 'Sign in'; return; }
            if (isSignup && fromSignup) sessionStorage.setItem('membersPendingCheckout', '1');
            return firebase.auth().signInWithCustomToken(token);
          }).then(function() {
            authBtn.disabled = false;
            authBtn.textContent = isSignup ? 'Create account' : 'Sign in';
          }).catch(function(err) {
            errorEl.textContent = membersAuthErrorMessage(err);
            authBtn.disabled = false;
            authBtn.textContent = isSignup ? 'Create account' : 'Sign in';
          });
        };
      }

      function setupPayFallback(domainKey) {
        var btn = document.getElementById('members-pay-fallback-btn');
        var wrap = document.getElementById('members-pay-fallback-wrap');
        if (!btn || !wrap) return;
        btn.onclick = function() {
          if (btn.disabled) return;
          btn.disabled = true;
          btn.textContent = 'Redirecting…';
          var createCheckout = firebase.app().functions('us-central1').httpsCallable('createMembersCheckout');
          createCheckout({ domain: domainKey, successUrl: window.location.origin + '/members', cancelUrl: window.location.origin + '/members' }).then(function(r) {
            if (r.data && r.data.url) window.location.href = r.data.url;
            else { btn.disabled = false; btn.textContent = 'Continue to payment'; }
          }).catch(function(err) {
            btn.disabled = false;
            btn.textContent = 'Continue to payment';
            var msg = (err && err.message) ? err.message : 'Something went wrong';
            if (msg === 'INTERNAL' || msg.toLowerCase().indexOf('internal') >= 0) {
              msg = 'Payment setup failed. Check Page Settings: Stripe Product ID, Publishable Key, and Secret Key must be set. Use the Guide for help.';
            }
            var existing = wrap.querySelector('.pay-fallback-err');
            if (existing) existing.remove();
            var errEl = document.createElement('p');
            errEl.className = 'pay-fallback-err';
            errEl.style.cssText = 'color:var(--error,#c00);font-size:0.9rem;margin-top:0.5rem';
            errEl.textContent = msg;
            btn.parentNode.insertBefore(errEl, btn.nextSibling);
          });
        };
      }

      function mountStripeEmbedInPlace(domainKey, user, productId, hasStripe) {
        hasStripe = hasStripe !== false;
        var embedEl = document.getElementById('members-checkout-embed');
        if (!embedEl) return;
        embedEl.innerHTML = '<p style="color:var(--text-muted)">Loading payment form…</p>';
        if (hasStripe) setupPayFallback(domainKey);
        var functions = firebase.app().functions('us-central1');
        var createEmbedded = functions.httpsCallable('createMembersEmbeddedCheckout');
        createEmbedded({ domain: domainKey, returnUrl: window.location.origin + '/members' }).then(function(res) {
          var clientSecret = res.data && res.data.clientSecret;
          var publishableKey = res.data && res.data.publishableKey;
          if (!clientSecret || !publishableKey) {
            embedEl.innerHTML = '<p style="color:var(--text-muted)">Payment not configured.</p>';
            return;
          }
          if (typeof Stripe === 'undefined') {
            embedEl.innerHTML = '<p style="color:var(--text-muted)">Unable to load payment form. Refresh the page.</p>';
            return;
          }
          var stripe = Stripe(publishableKey);
          var fetchClientSecret = function() { return Promise.resolve(clientSecret); };
          if (typeof stripe.initEmbeddedCheckout !== 'function') {
            embedEl.innerHTML = '<p style="color:var(--text-muted)">Redirecting to payment…</p>';
            var createCheckout = functions.httpsCallable('createMembersCheckout');
            createCheckout({ domain: domainKey, successUrl: window.location.origin + '/members', cancelUrl: window.location.origin + '/members' }).then(function(r) {
              if (r.data && r.data.url) window.location.href = r.data.url;
              else embedEl.innerHTML = '<p style="color:var(--text-muted)">Click "Continue to payment" below.</p>';
            }).catch(function(err) {
              embedEl.innerHTML = '<p style="color:var(--text-muted)">' + escapeHtml((err && err.message) || 'Something went wrong') + '. Click "Continue to payment" below.</p>';
            });
            return;
          }
          stripe.initEmbeddedCheckout({ fetchClientSecret: fetchClientSecret }).then(function(checkout) {
            embedEl.innerHTML = '';
            checkout.mount('#members-checkout-embed');
            var w = document.getElementById('members-pay-fallback-wrap');
            if (w) w.style.display = 'none';
          }).catch(function() {
            var createCheckout = functions.httpsCallable('createMembersCheckout');
            var fallbackWrap = document.getElementById('members-pay-fallback-wrap');
            if (fallbackWrap) fallbackWrap.style.display = '';
            createCheckout({ domain: domainKey, successUrl: window.location.origin + '/members', cancelUrl: window.location.origin + '/members' }).then(function(r) {
              if (r.data && r.data.url) { embedEl.innerHTML = '<p style="color:var(--text-muted)">Redirecting to payment…</p>'; window.location.href = r.data.url; }
              else embedEl.innerHTML = '<p style="color:var(--text-muted)">Click "Continue to payment" below.</p>';
            }).catch(function(err) {
              embedEl.innerHTML = '<p style="color:var(--text-muted)">' + escapeHtml((err && err.message) || 'Something went wrong') + '. Click "Continue to payment" below to try again.</p>';
            });
          });
        }).catch(function(err) {
          var msg = (err && err.message) ? err.message : 'Something went wrong.';
          if (!hasStripe && msg.indexOf('not configured') >= 0) {
            db.collection('members_access').doc(domainKey + '_' + user.uid).set({ domain: domainKey, userId: user.uid, status: 'active', createdAt: firebase.firestore.FieldValue.serverTimestamp() });
            initMembersArea();
          } else {
            var fallbackWrap = document.getElementById('members-pay-fallback-wrap');
            if (fallbackWrap) fallbackWrap.style.display = '';
            embedEl.innerHTML = '<p style="color:var(--text-muted)">' + escapeHtml(msg) + '</p><p style="margin-top:0.75rem;font-size:0.9rem;color:var(--text-muted)">Check Page Settings → Members area — Stripe and ensure Product ID, Publishable Key, and Secret Key are set. Use the Guide for help. Or click "Continue to payment" below to try the redirect.</p>';
          }
        });
      }

      function renderMembersPaymentInline(domainKey, user, productId, hasStripe) {
        var html = '<section class="members-subscribe" style="max-width:480px;margin:0 auto;padding:2rem 1.5rem;text-align:center">';
        html += '<h1 class="domain">Complete your purchase</h1>';
        html += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Enter your payment details below to get access.</p>';
        html += '<div id="members-checkout-embed" style="min-height:400px"></div>';
        html += '<p style="margin-top:1rem" id="members-pay-fallback-wrap"><button type="button" class="cta cta-primary" id="members-pay-fallback-btn">Continue to payment</button></p>';
        html += '<p style="margin-top:1.5rem"><button type="button" class="cta" style="background:transparent;border:none;color:var(--text-muted);font-size:0.9rem" id="members-signout-btn">Sign out</button></p>';
        html += '<p style="margin-top:0.5rem"><a href="/" style="color:var(--accent);font-size:0.9rem">Back to home</a></p></section>';
        contentEl.innerHTML = html;
        document.getElementById('members-signout-btn').onclick = function() { firebase.auth().signOut(); };
        mountStripeEmbedInPlace(domainKey, user, productId, hasStripe);
      }

      function renderMembersContent(domainKey, user, latestResult, productId) {
        var testType = productId === 'npi_test' ? 'npi' : productId === 'mbti' ? 'mbti' : productId;
        var takingTest = !latestResult || latestResult.testType !== testType;
        var html = '<section class="members-content" style="max-width:560px;margin:0 auto;padding:2rem 1.5rem;text-align:left">';
        html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:2rem;flex-wrap:wrap;gap:1rem">';
        html += '<h1 class="domain" style="margin:0">Members area</h1>';
        html += '<div style="display:flex;align-items:center;gap:0.5rem">';
        html += '<button type="button" class="cta" style="padding:0.5rem 1rem;font-size:0.9rem" id="members-manage-subscription-btn">Manage subscription</button>';
        html += '<button type="button" class="cta" style="padding:0.5rem 1rem;font-size:0.9rem" id="members-signout-btn">Sign out</button></div></div>';
        if (takingTest) {
          html += renderTestForm(productId);
        } else {
          html += renderTestResults(productId, latestResult);
        }
        html += '<div id="members-resources-placeholder" style="margin-top:3rem"><p style="color:var(--text-muted)">Loading resources…</p></div>';
        html += '<p style="margin-top:2rem"><a href="/" style="color:var(--accent)">Back to home</a></p></section>';
        contentEl.innerHTML = html;
        fetchAndRenderResources(domainKey, productId, takingTest ? null : latestResult, 'members-resources-placeholder');
        if (takingTest) {
          bindTestFormSubmit(domainKey, user, productId);
        } else {
          document.getElementById('members-retake-btn').onclick = function() {
            renderMembersContent(domainKey, user, null, productId);
          };
        }
        document.getElementById('members-signout-btn').onclick = function() { firebase.auth().signOut(); };
        var manageBtn = document.getElementById('members-manage-subscription-btn');
        if (manageBtn) {
          manageBtn.onclick = function() {
            var fn = firebase.app().functions('us-central1').httpsCallable('createStripePortalSession');
            fn({ domain: domainKey }).then(function(res) {
              var url = res && res.data && res.data.url;
              if (url) window.location.href = url;
            }).catch(function() {
              alert('Unable to open subscription management. You may need to contact support.');
            });
          };
        }
      }

      function renderTestForm(productId) {
        if (productId === 'npi_test') {
          var h = '<h2 style="margin-bottom:0.5rem">Narcissistic Personality Inventory (NPI-16)</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Choose the statement in each pair that comes closest to describing you. This takes about 5 minutes. For educational use only.</p>';
          h += '<form id="members-test-form">';
          NPI_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item npi-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. Choose one:</p>';
            h += '<label style="display:flex;align-items:flex-start;gap:0.5rem;cursor:pointer;margin-bottom:0.5rem"><input type="radio" name="q_' + i + '" value="a"><span>' + item.a + '</span></label>';
            h += '<label style="display:flex;align-items:flex-start;gap:0.5rem;cursor:pointer"><input type="radio" name="q_' + i + '" value="b"><span>' + item.b + '</span></label>';
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'phq9') {
          var h = '<h2 style="margin-bottom:0.5rem">PHQ-9 Depression Screening</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Over the last 2 weeks, how often have you been bothered by the following? For educational use only — not a diagnosis.</p>';
          h += '<form id="members-test-form">';
          PHQ9_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item + '</p>';
            PHQ9_LABELS.forEach(function(lbl, j) {
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            });
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'gad7') {
          var h = '<h2 style="margin-bottom:0.5rem">GAD-7 Anxiety Screening</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Over the last 2 weeks, how often have you been bothered by the following? For educational use only — not a diagnosis.</p>';
          h += '<form id="members-test-form">';
          GAD7_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item + '</p>';
            PHQ9_LABELS.forEach(function(lbl, j) {
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            });
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'pss10') {
          var h = '<h2 style="margin-bottom:0.5rem">Perceived Stress Scale (PSS-10)</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">In the last month, how often have you felt or thought each of the following?</p>';
          h += '<form id="members-test-form">';
          PSS10_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item.text + '</p>';
            PSS10_LABELS.forEach(function(lbl, j) {
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            });
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'who5') {
          var h = '<h2 style="margin-bottom:0.5rem">WHO-5 Well-Being Index</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Over the last 2 weeks, how much of the time have you felt each of the following?</p>';
          h += '<form id="members-test-form">';
          WHO5_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item + '</p>';
            WHO5_LABELS.forEach(function(lbl, j) {
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            });
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'big_five') {
          var h = '<h2 style="margin-bottom:0.5rem">Big Five Inventory (BFI-10)</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Rate how much you agree with each statement. 1 = Disagree strongly, 5 = Agree strongly.</p>';
          h += '<form id="members-test-form">';
          BFI10_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item.text + '</p>';
            for (var j = 1; j <= 5; j++) {
              var lbl = j === 1 ? 'Disagree strongly' : j === 2 ? 'Disagree a little' : j === 3 ? 'Neither agree nor disagree' : j === 4 ? 'Agree a little' : 'Agree strongly';
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            }
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'dark_triad') {
          var h = '<h2 style="margin-bottom:0.5rem">Short Dark Triad (SD3)</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Rate how much you agree with each statement. 1 = Strongly disagree, 5 = Strongly agree.</p>';
          h += '<form id="members-test-form">';
          SD3_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item.text + '</p>';
            for (var j = 1; j <= 5; j++) {
              var lbl = j === 1 ? 'Strongly disagree' : j === 2 ? 'Disagree' : j === 3 ? 'Neutral' : j === 4 ? 'Agree' : 'Strongly agree';
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            }
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'holland') {
          var h = '<h2 style="margin-bottom:0.5rem">Holland Career Interest Assessment</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">How much would you enjoy doing each activity? 1 = Dislike, 5 = Enjoy very much.</p>';
          h += '<form id="members-test-form">';
          HOLLAND_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. ' + item.text + '</p>';
            for (var j = 1; j <= 5; j++) {
              var lbl = j === 1 ? 'Dislike' : j === 2 ? 'Slightly dislike' : j === 3 ? 'Neutral' : j === 4 ? 'Slightly enjoy' : 'Enjoy very much';
              h += '<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-bottom:0.35rem"><input type="radio" name="q_' + i + '" value="' + j + '"><span>' + lbl + '</span></label>';
            }
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        if (productId === 'mbti') {
          var h = '<h2 style="margin-bottom:0.5rem">Myers-Briggs Type Indicator (MBTI)</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:2rem;font-size:0.95rem">Choose the statement in each pair that comes closest to describing you. Discover your type (e.g. Architect, Advocate) for team dynamics and self-awareness. For educational use only.</p>';
          h += '<form id="members-test-form">';
          MBTI_ITEMS.forEach(function(item, i) {
            h += '<div class="assessment-item npi-item">';
            h += '<p style="font-weight:500;margin-bottom:0.75rem">' + (i + 1) + '. Choose one:</p>';
            h += '<label style="display:flex;align-items:flex-start;gap:0.5rem;cursor:pointer;margin-bottom:0.5rem"><input type="radio" name="q_' + i + '" value="a"><span>' + item.a + '</span></label>';
            h += '<label style="display:flex;align-items:flex-start;gap:0.5rem;cursor:pointer"><input type="radio" name="q_' + i + '" value="b"><span>' + item.b + '</span></label>';
            h += '</div>';
          });
          h += '<button type="submit" class="cta cta-primary" style="width:100%;padding:1rem">See results</button></form>';
          return h;
        }
        return '<p>Unknown assessment type.</p>';
      }

      function renderTestResults(productId, result) {
        var score = result.score != null ? result.score : 0;
        var scores = result.scores || {};
        var answers = result.answers || [];
        if (productId === 'npi_test') {
          var total = NPI_ITEMS.length;
          var pct = Math.round((score / total) * 100);
          var band = pct <= 31 ? 'low' : pct <= 62 ? 'average' : 'high';
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your NPI-16 score: ' + score + ' / ' + total + ' (' + pct + '%)</p>';
          h += '<p style="margin-bottom:1.5rem">Interpretation: ' + band + ' range. This is for educational use only and does not diagnose any condition.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake test</button>';
          return h;
        }
        if (productId === 'phq9') {
          var band = score <= 4 ? 'Minimal' : score <= 9 ? 'Mild' : score <= 14 ? 'Moderate' : score <= 19 ? 'Moderately severe' : 'Severe';
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your PHQ-9 score: ' + score + ' / 27</p>';
          h += '<p style="margin-bottom:1.5rem">Interpretation: ' + band + ' range. This is for educational use only — not a diagnosis. If you have concerns, please speak with a healthcare provider.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake screening</button>';
          return h;
        }
        if (productId === 'gad7') {
          var band = score <= 4 ? 'Minimal' : score <= 9 ? 'Mild' : score <= 14 ? 'Moderate' : 'Severe';
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your GAD-7 score: ' + score + ' / 21</p>';
          h += '<p style="margin-bottom:1.5rem">Interpretation: ' + band + ' range. This is for educational use only — not a diagnosis. If you have concerns, please speak with a healthcare provider.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake screening</button>';
          return h;
        }
        if (productId === 'pss10') {
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your PSS-10 score: ' + score + ' / 40</p>';
          h += '<p style="margin-bottom:1.5rem">Higher scores indicate greater perceived stress. This scale has no clinical cut-offs — it allows comparison over time. For educational use only.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake assessment</button>';
          return h;
        }
        if (productId === 'who5') {
          var pct = Math.round((score / 25) * 100);
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your WHO-5 score: ' + score + ' / 25 (' + pct + '% of maximum wellbeing)</p>';
          h += '<p style="margin-bottom:1.5rem">Scores below 28% (raw score &lt; 7) may suggest poor wellbeing. This is for educational use only. If you are struggling, please speak with a healthcare provider.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake assessment</button>';
          return h;
        }
        if (productId === 'big_five') {
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your Big Five profile:</p>';
          h += '<ul style="margin-bottom:1.5rem;padding-left:1.25rem">';
          ['E','A','C','N','O'].forEach(function(k) {
            var v = scores[k] != null ? scores[k] : 0;
            h += '<li><strong>' + BFI10_FACTORS[k] + '</strong>: ' + v.toFixed(1) + ' / 5</li>';
          });
          h += '</ul>';
          h += '<p style="margin-bottom:1.5rem">For educational use only. Each dimension is scored 1–5.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake test</button>';
          return h;
        }
        if (productId === 'dark_triad') {
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your Dark Triad scores:</p>';
          h += '<ul style="margin-bottom:1.5rem;padding-left:1.25rem">';
          ['N','M','P'].forEach(function(k) {
            var v = scores[k] != null ? scores[k] : 0;
            h += '<li><strong>' + SD3_FACTORS[k] + '</strong>: ' + v.toFixed(1) + ' / 5</li>';
          });
          h += '</ul>';
          h += '<p style="margin-bottom:1.5rem">These traits exist on a continuum. For educational use only.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake test</button>';
          return h;
        }
        if (productId === 'holland') {
          var code = result.hollandCode || '';
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your Holland code: <strong>' + code + '</strong></p>';
          h += '<p style="margin-bottom:0.5rem">Scores by type:</p><ul style="margin-bottom:1.5rem;padding-left:1.25rem">';
          ['R','I','A','S','E','C'].forEach(function(k) {
            var v = scores[k] != null ? scores[k] : 0;
            h += '<li><strong>' + k + '</strong> (' + HOLLAND_TYPES[k] + '): ' + v.toFixed(1) + '</li>';
          });
          h += '</ul>';
          h += '<p style="margin-bottom:1.5rem">Your top three types form your Holland code. Use it to explore careers that match your interests.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake assessment</button>';
          return h;
        }
        if (productId === 'mbti') {
          var code = result.mbtiCode || '';
          var archetype = MBTI_ARCHETYPES[code] || '';
          var h = '<h2 style="margin-bottom:0.5rem">Your results</h2>';
          h += '<p style="color:var(--text-muted);margin-bottom:1.5rem">Your type: <strong>' + code + '</strong>' + (archetype ? ' — ' + archetype : '') + '</p>';
          h += '<p style="margin-bottom:1.5rem">Use your type to understand team dynamics, communication preferences, and how you work best with others. For educational use only.</p>';
          h += '<button type="button" class="cta cta-primary" id="members-retake-btn">Retake test</button>';
          return h;
        }
        return '<p>Unknown assessment type.</p>';
      }

      function bindTestFormSubmit(domainKey, user, productId) {
        var form = document.getElementById('members-test-form');
        if (!form) return;
        form.onsubmit = function(e) {
          e.preventDefault();
          var payload = { domain: domainKey, userId: user.uid, testType: productId === 'npi_test' ? 'npi' : productId === 'mbti' ? 'mbti' : productId, answers: [], completedAt: firebase.firestore.FieldValue.serverTimestamp() };
          if (productId === 'npi_test') {
            var answers = [];
            var allDone = true;
            for (var i = 0; i < NPI_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { allDone = false; break; }
              var item = NPI_ITEMS[i];
              answers.push(sel.value === 'a' ? item.scoreA : (1 - item.scoreA));
            }
            if (!allDone) { alert('Please answer all questions.'); return; }
            payload.score = answers.reduce(function(a, b) { return a + b; }, 0);
            payload.answers = answers;
          } else if (productId === 'phq9' || productId === 'gad7') {
            var answers = [];
            for (var i = 0; i < (productId === 'phq9' ? PHQ9_ITEMS : GAD7_ITEMS).length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              answers.push(parseInt(sel.value, 10));
            }
            payload.score = answers.reduce(function(a, b) { return a + b; }, 0);
            payload.answers = answers;
          } else if (productId === 'pss10') {
            var answers = [];
            for (var i = 0; i < PSS10_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              var v = parseInt(sel.value, 10);
              var item = PSS10_ITEMS[i];
              answers.push(item.reverse ? (4 - v) : v);
            }
            payload.score = answers.reduce(function(a, b) { return a + b; }, 0);
            payload.answers = answers;
          } else if (productId === 'who5') {
            var answers = [];
            for (var i = 0; i < WHO5_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              answers.push(parseInt(sel.value, 10));
            }
            payload.score = answers.reduce(function(a, b) { return a + b; }, 0);
            payload.answers = answers;
          } else if (productId === 'big_five') {
            var factorSums = { E: [0,0], A: [0,0], C: [0,0], N: [0,0], O: [0,0] };
            for (var i = 0; i < BFI10_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              var v = parseInt(sel.value, 10);
              var item = BFI10_ITEMS[i];
              var score = item.reverse ? (6 - v) : v;
              factorSums[item.factor][0] += score;
              factorSums[item.factor][1]++;
            }
            var scores = {};
            for (var k in factorSums) { scores[k] = factorSums[k][1] > 0 ? factorSums[k][0] / factorSums[k][1] : 0; }
            payload.scores = scores;
            payload.score = 0;
            payload.answers = [];
          } else if (productId === 'dark_triad') {
            var factorSums = { N: [0,0], M: [0,0], P: [0,0] };
            for (var i = 0; i < SD3_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              var v = parseInt(sel.value, 10);
              var item = SD3_ITEMS[i];
              var score = item.reverse ? (6 - v) : v;
              factorSums[item.factor][0] += score;
              factorSums[item.factor][1]++;
            }
            var scores = {};
            for (var k in factorSums) { scores[k] = factorSums[k][1] > 0 ? factorSums[k][0] / factorSums[k][1] : 0; }
            payload.scores = scores;
            payload.score = 0;
            payload.answers = [];
          } else if (productId === 'holland') {
            var typeSums = { R: 0, I: 0, A: 0, S: 0, E: 0, C: 0 };
            for (var i = 0; i < HOLLAND_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { alert('Please answer all questions.'); return; }
              var v = parseInt(sel.value, 10);
              typeSums[HOLLAND_ITEMS[i].type] += v;
            }
            var sorted = Object.keys(typeSums).sort(function(a, b) { return typeSums[b] - typeSums[a]; });
            payload.scores = typeSums;
            payload.hollandCode = sorted.slice(0, 3).join('');
            payload.score = 0;
            payload.answers = [];
          } else if (productId === 'mbti') {
            var dimScores = { E: 0, S: 0, T: 0, J: 0 };
            var dimTotals = { E: 5, S: 5, T: 5, J: 5 };
            var answers = [];
            var allDone = true;
            for (var i = 0; i < MBTI_ITEMS.length; i++) {
              var sel = document.querySelector('input[name="q_' + i + '"]:checked');
              if (!sel) { allDone = false; break; }
              var item = MBTI_ITEMS[i];
              var pts = sel.value === 'a' ? item.scoreA : (1 - item.scoreA);
              var dim = item.factor;
              dimScores[dim] += pts;
              answers.push(pts);
            }
            if (!allDone) { alert('Please answer all questions.'); return; }
            var code = '';
            code += dimScores.E >= dimTotals.E / 2 ? 'E' : 'I';
            code += dimScores.S >= dimTotals.S / 2 ? 'S' : 'N';
            code += dimScores.T >= dimTotals.T / 2 ? 'T' : 'F';
            code += dimScores.J >= dimTotals.J / 2 ? 'J' : 'P';
            payload.scores = dimScores;
            payload.mbtiCode = code;
            payload.answers = answers;
            payload.score = 0;
          } else {
            alert('Unknown assessment type.');
            return;
          }
          db.collection('test_results').add(payload).then(function() {
            initMembersArea();
          }).catch(function() { alert('Could not save results.'); });
        };
      }

      function runExperiment(domainKey, onDone) {
        db.collection('domains').doc(domainKey).get().then(function(domainSnap) {
          if (!domainSnap.exists) { onDone(false); return; }
          var exp = domainSnap.data().experiment;
          if (!exp || !exp.enabled) { onDone(false); return; }
          var entryPath = (exp.path || '').toString().trim().replace(/^\/+|\/+$/g, '');
          var matches = (entryPath === '' && path === '') || (entryPath !== '' && path === entryPath);
          if (!matches) { onDone(false); return; }
          var cookieVal = getCookie('domain-placeholder-variant');
          db.collection('domains').doc(domainKey).collection('pages').get().then(function(pagesSnap) {
            var pageIds = pagesSnap.docs.map(function(d) { return d.id; }).filter(function(id) { return id && id.length > 0; });
            if (pageIds.length === 0) { onDone(false); return; }
            var chosen = null;
            if (cookieVal && pageIds.indexOf(cookieVal) >= 0) {
              chosen = cookieVal;
            } else if (pageIds.length === 1) {
              chosen = pageIds[0];
            } else {
              chosen = pageIds[Math.floor(Math.random() * pageIds.length)];
              setCookie('domain-placeholder-variant', chosen, 30);
            }
            if (chosen) {
              window.location.replace('/' + chosen);
              return;
            }
            onDone(false);
          }).catch(function() { onDone(false); });
        }).catch(function() { onDone(false); });
      }
      runExperiment(hostname, function(redirected) {
        if (redirected) return;
        runExperiment(altHostname, function(redirected2) {
          if (redirected2) return;
          if (path === 'members') {
            var params = new URLSearchParams(window.location.search || '');
            if (params.get('session_id')) {
              history.replaceState({}, '', window.location.pathname);
            }
            initMembersArea();
            return;
          }
          initAndLoad();
        });
      });

      function initAndLoad() {
      var viewKey = 'domainPlaceholderViewRecorded_' + hostname + '_' + (path || '');
      if (!sessionStorage.getItem(viewKey)) {
        var functions = firebase.app().functions('us-central1');
        var recordView = functions.httpsCallable('recordView');
        recordView({ hostname: hostname, path: path || null }).then(function() {
          sessionStorage.setItem(viewKey, '1');
        }).catch(function() {
          var safe = hostname.replace(/^www\./, '').toLowerCase().slice(0, 253);
          if (safe) {
            var ref = path
              ? db.collection('stats').doc(safe).collection('pages').doc(path.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 253))
              : db.collection('stats').doc(safe);
            ref.set({
              viewCount: firebase.firestore.FieldValue.increment(1),
              lastViewAt: firebase.firestore.FieldValue.serverTimestamp()
            }, { merge: true }).then(function() {
              sessionStorage.setItem(viewKey, '1');
            }).catch(function() {});
          }
        });
      }

      function relativeLuminance(hex) {
        var h = hex.replace(/^#/, '');
        if (h.length !== 6) return 0.5;
        var r = parseInt(h.slice(0, 2), 16) / 255;
        var g = parseInt(h.slice(2, 4), 16) / 255;
        var b = parseInt(h.slice(4, 6), 16) / 255;
        r = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
        g = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
        b = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);
        return 0.2126 * r + 0.7152 * g + 0.0722 * b;
      }

      function initScrollAnimations(container) {
        if (!container) return;
        var sections = container.querySelectorAll('.widget.animate-reveal');
        if (sections.length === 0) return;
        var hero = container.querySelector('.widget-hero.animate-reveal');
        if (hero) {
          requestAnimationFrame(function() {
            requestAnimationFrame(function() { hero.classList.add('animate-in'); });
          });
        }
        var observer = new IntersectionObserver(function(entries) {
          entries.forEach(function(entry) {
            if (entry.isIntersecting) {
              entry.target.classList.add('animate-in');
              observer.unobserve(entry.target);
            }
          });
        }, { rootMargin: '0px 0px -10% 0px', threshold: 0 });
        sections.forEach(function(s) {
          if (s !== hero) observer.observe(s);
        });
      }

      function renderWidgets(widgets, host) {
        contentEl.innerHTML = '';
        widgets.forEach(function(w) {
          var id = w.id;
          var config = w.config || {};
          var section = document.createElement('section');
          section.className = 'widget widget-' + id + ' animate-reveal';
          var anchor = (config.anchor || '').trim().replace(/[^a-zA-Z0-9_-]/g, '');
          if (anchor) section.id = anchor;
          var gradient = config.backgroundGradient;
          if (gradient && gradient.type === 'linear' && Array.isArray(gradient.stops) && gradient.stops.length >= 2) {
            var angle = typeof gradient.angle === 'number' ? gradient.angle : 135;
            var stops = gradient.stops;
            var parts = stops.map(function(s, i) {
              var color = (s.color || '').trim();
              if (!/^#[0-9A-Fa-f]{6}$/.test(color) && !/^#[0-9A-Fa-f]{8}$/.test(color)) color = '#000000';
              var offset = typeof s.offset === 'number' ? Math.round(s.offset * 100) : (stops.length === 1 ? 100 : Math.round((i / (stops.length - 1)) * 100));
              return color + ' ' + offset + '%';
            });
            section.style.background = 'linear-gradient(' + angle + 'deg, ' + parts.join(', ') + ')';
            section.classList.add('widget-full-bg');
          } else {
            var bg = (config.backgroundColor || '').trim();
            if (bg && /^#[0-9A-Fa-f]{6}$/.test(bg)) {
              section.style.backgroundColor = bg;
              section.classList.add('widget-full-bg');
            }
          }
          if (section.classList.contains('widget-full-bg')) {
            var textStyle = (config.sectionTextStyle || config.textOnBackground || 'auto').toString().trim().toLowerCase();
            if (textStyle !== 'light' && textStyle !== 'dark') textStyle = 'auto';
            if (textStyle === 'auto') {
              var sampleHex = null;
              if (gradient && gradient.stops && gradient.stops[0] && gradient.stops[0].color)
                sampleHex = (gradient.stops[0].color || '').trim().replace(/^#/, '');
              else
                sampleHex = (config.backgroundColor || '').trim().replace(/^#/, '');
              if (sampleHex && /^[0-9A-Fa-f]{6}$/.test(sampleHex)) {
                var lum = relativeLuminance('#' + sampleHex);
                textStyle = lum <= 0.45 ? 'light' : 'dark';
              } else
                textStyle = 'light';
            }
            section.classList.add('section-text-' + textStyle);
          }
          if (id === 'hero') {
            var theme = (config.theme || 'primary').trim();
            var cta2Theme = (config.cta2Theme || 'outline').trim();
            var cta1 = (config.ctaLabel && config.ctaUrl) ? '<a href="' + escapeHtml(config.ctaUrl) + '" class="cta cta-' + escapeHtml(theme) + '">' + escapeHtml(config.ctaLabel) + '</a>' : '';
            var cta2 = (config.cta2Label && config.cta2Url) ? ' <a href="' + escapeHtml(config.cta2Url) + '" class="cta cta-' + escapeHtml(cta2Theme) + '">' + escapeHtml(config.cta2Label) + '</a>' : '';
            section.innerHTML = '<h1 class="domain">' + escapeHtml(config.title || host) + '</h1>' +
              (config.tagline ? '<p class="tagline">' + escapeHtml(config.tagline) + '</p>' : '') +
              (cta1 || cta2 ? '<p class="hero-ctas">' + cta1 + cta2 + '</p>' : '');
          } else if (id === 'text') {
            var heading = (config.heading || '').trim();
            var body = (config.body || '').trim();
            var bodyHtml = body ? '<div class="body">' + escapeHtml(body).replace(/\n/g, '<br>') + '</div>' : '';
            var headingHtml = heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '';
            section.innerHTML = headingHtml + bodyHtml;
            var align = (config.align || 'left').trim();
            if (['left', 'center', 'right', 'justify'].indexOf(align) >= 0) section.classList.add('align-' + align);
            else section.classList.add('align-left');
          } else if (id === 'contact') {
            var contactHeading = (config.heading || config.title || 'Get in touch').trim();
            if (!contactHeading) contactHeading = 'Get in touch';
            section.innerHTML = '<h2 class="section-heading">' + escapeHtml(contactHeading) + '</h2><form id="contact-form"><label for="email">Your email</label><input type="email" id="email" name="email" required placeholder="you@example.com"><label for="message">Message</label><textarea id="message" name="message" required placeholder="Your message…"></textarea><button type="submit" id="submit-btn">Send</button><p class="form-status" id="form-status" aria-live="polite"></p></form>';
          } else if (id === 'social' && config.links && config.links.length) {
            var list = config.links.map(function(link) {
              var url = (link.url || '').trim();
              var label = (link.label || url || 'Link').trim();
              return url ? '<li><a href="' + escapeHtml(url) + '" target="_blank" rel="noopener">' + escapeHtml(label) + '</a></li>' : '';
            }).filter(Boolean).join('');
            if (list) section.innerHTML = '<ul class="social-links">' + list + '</ul>';
          } else if (id === 'notifyme') {
            var label = (config.label || 'Notify me when we launch').trim();
            var notifymeTheme = (config.theme || 'primary').trim();
            section.innerHTML = '<p class="tagline">' + escapeHtml(label) + '</p><form class="notifyme-form notifyme-inline"><input type="email" name="email" required placeholder="you@example.com"><button type="submit" class="cta cta-' + escapeHtml(notifymeTheme) + '">Notify me</button></form><p class="form-status notifyme-status" aria-live="polite"></p>';
          } else if (id === 'image' && config.url) {
            var url = (config.url || '').trim();
            var alt = (config.alt || '').trim();
            var linkUrl = (config.linkUrl || '').trim();
            var fit = (config.fit || 'contain').trim();
            if (!/^(contain|cover|fill|none)$/.test(fit)) fit = 'contain';
            var pos = (config.objectPosition || 'center').trim();
            var posMap = { 'center': 'center', 'top': 'top', 'bottom': 'bottom', 'left': 'left', 'right': 'right', 'top left': 'top left', 'top right': 'top right', 'bottom left': 'bottom left', 'bottom right': 'bottom right' };
            if (!posMap[pos]) pos = 'center';
            var w = (config.width || '').toString().trim();
            var h = (config.height || '').toString().trim();
            var wrapStyle = '';
            if (w) wrapStyle += 'width:' + (/^\d+$/.test(w) ? w + 'px' : w) + ';';
            if (h && h !== 'auto') wrapStyle += 'height:' + (/^\d+$/.test(h) ? h + 'px' : h) + ';';
            var innerClass = 'widget-image-inner' + (wrapStyle ? ' sized' : '');
            if (wrapStyle) fit = 'cover';
            var imgStyle = 'object-fit:' + fit + ';object-position:' + pos;
            if (wrapStyle) imgStyle += ';width:100%;height:100%';
            else imgStyle += ';max-width:100%;height:auto';
            var img = '<img src="' + escapeHtml(url) + '" alt="' + escapeHtml(alt) + '" loading="lazy" style="' + imgStyle + '">';
            var inner = '<div class="' + innerClass + '"' + (wrapStyle ? ' style="' + wrapStyle + '"' : '') + '>' + img + '</div>';
            section.innerHTML = linkUrl ? '<a href="' + escapeHtml(linkUrl) + '">' + inner + '</a>' : inner;
          } else if (id === 'countdown' && config.targetDate) {
            var target = (config.targetDate || '').trim();
            var label = (config.label || 'Launching in').trim();
            section.innerHTML = '<p class="countdown-label">' + escapeHtml(label) + '</p><p class="countdown-value" id="countdown-value">—</p>';
            section.dataset.target = target;
          } else if (id === 'button' && config.label && config.url) {
            var btnTheme = (config.theme || 'primary').trim();
            section.innerHTML = '<a href="' + escapeHtml((config.url || '').trim()) + '" class="cta cta-' + escapeHtml(btnTheme) + '">' + escapeHtml((config.label || '').trim()) + '</a>';
          } else if (id === 'faq' && config.items && config.items.length) {
            var items = config.items.filter(function(item) { return (item.question || '').trim(); });
            var html = items.map(function(item) {
              var q = escapeHtml((item.question || '').trim());
              var a = escapeHtml((item.answer || '').trim()).replace(/\n/g, '<br>');
              return '<details><summary>' + q + '</summary><div class="faq-answer">' + a + '</div></details>';
            }).join('');
            if (html) section.innerHTML = html;
          } else if (id === 'testimonial' && config.items && config.items.length) {
            var items = config.items.filter(function(t) { return (t.quote || '').trim(); });
            if (items.length) {
              var current = 0;
              function renderTestimonial(idx) {
                var t = items[idx];
                var quote = escapeHtml((t.quote || '').trim());
                var name = escapeHtml((t.name || '').trim());
                var role = (t.role || '').trim();
                var company = (t.company || '').trim();
                var meta = name + (role ? ', ' + escapeHtml(role) : '') + (company ? ' · ' + escapeHtml(company) : '');
                var avatar = (t.avatarUrl || '').trim();
                var avatarHtml = avatar ? '<img class="testimonial-avatar" src="' + escapeHtml(avatar) + '" alt="">' : '';
                return (avatarHtml ? '<div style="display:flex;align-items:flex-start;gap:0.75rem;">' + avatarHtml + '<div style="flex:1;">' : '<div>') + '<p class="testimonial-quote">"' + quote + '"</p><p class="testimonial-meta">— ' + meta + '</p></div>' + (avatarHtml ? '</div>' : '');
              }
              section.innerHTML = '<div class="testimonial-slides">' + renderTestimonial(0) + '</div>' + (items.length > 1 ? '<div class="testimonial-nav">' + items.map(function(_, i) { return '<button type="button" class="testimonial-dot' + (i === 0 ? ' active' : '') + '" data-idx="' + i + '" aria-label="Testimonial ' + (i + 1) + '"></button>'; }).join('') + '</div>' : '');
              section.className = 'widget widget-testimonial';
              if (items.length > 1) {
                var dots = section.querySelectorAll('.testimonial-dot');
                var slideContainer = section.querySelector('.testimonial-slides');
                var autoplay = typeof config.autoplaySeconds === 'number' && config.autoplaySeconds > 0 ? config.autoplaySeconds * 1000 : 0;
                var timer = null;
                function goTo(i) {
                  current = (i + items.length) % items.length;
                  if (slideContainer) slideContainer.innerHTML = renderTestimonial(current);
                  dots.forEach(function(d, j) { d.classList.toggle('active', j === current); });
                  if (autoplay) { clearInterval(timer); timer = setInterval(function() { goTo(current + 1); }, autoplay); }
                }
                dots.forEach(function(d, i) { d.addEventListener('click', function() { goTo(Number(d.getAttribute('data-idx'))); }); });
                if (autoplay) timer = setInterval(function() { goTo(current + 1); }, autoplay);
              }
            }
          } else if (id === 'features' && config.items && config.items.length) {
            var items = config.items.filter(function(f) { return (f.title || '').trim(); });
            var cols = config.columns === 3 ? 3 : 2;
            if (items.length) {
              var itemsHtml = items.map(function(f) {
                var icon = escapeHtml((f.icon || '✨').trim().slice(0, 4));
                var title = escapeHtml((f.title || '').trim());
                var desc = escapeHtml((f.description || '').trim()).replace(/\n/g, '<br>');
                return '<div class="feature-item"><div class="feature-icon">' + icon + '</div><div class="feature-title">' + title + '</div><div class="feature-desc">' + desc + '</div></div>';
              }).join('');
              /* Always use inner grid wrapper so section is never the grid (fixes layout with bg) */
              section.classList.remove('widget-features', 'cols-2', 'cols-3');
              var innerClass = 'widget-features cols-' + cols;
              if (section.classList.contains('widget-full-bg')) innerClass = 'widget-full-bg-inner ' + innerClass;
              section.innerHTML = '<div class="' + innerClass + '">' + itemsHtml + '</div>';
            }
          } else if (id === 'stats' && config.items && config.items.length) {
            var items = config.items.filter(function(s) { return (s.value !== undefined && s.value !== null && s.value !== ''); });
            if (items.length) section.innerHTML = items.map(function(s) {
              var val = escapeHtml(String(s.value).trim());
              var label = escapeHtml((s.label || '').trim());
              return '<div class="stat-item"><div class="stat-value">' + val + '</div><div class="stat-label">' + label + '</div></div>';
            }).join('');
          } else if (id === 'logos' && config.items && config.items.length) {
            var items = config.items.filter(function(l) { return (l.name || l.imageUrl || '').trim(); });
            if (items.length) section.innerHTML = items.map(function(l) {
              var name = escapeHtml((l.name || '').trim());
              var img = (l.imageUrl || '').trim();
              var link = (l.link || '').trim();
              var content = img ? '<img src="' + escapeHtml(img) + '" alt="' + name + '" loading="lazy">' : name;
              return link ? '<a href="' + escapeHtml(link) + '" target="_blank" rel="noopener">' + content + '</a>' : '<span>' + content + '</span>';
            }).join('');
          } else if (id === 'pricing' && config.items && config.items.length) {
            var items = config.items;
            var sectionTitle = (config.heading || config.title || 'Plans').trim();
            if (!sectionTitle) sectionTitle = 'Plans';
            var titleHtml = '<h2 class="section-heading">' + escapeHtml(sectionTitle) + '</h2>';
            var cols = items.length >= 3 ? 3 : (items.length === 2 ? 2 : 1);
            if (cols > 1) section.classList.add('cols-' + cols);
            section.innerHTML = titleHtml + items.map(function(p) {
              var name = escapeHtml((p.name || 'Plan').trim());
              var price = escapeHtml((p.price || '').trim());
              var period = escapeHtml((p.period || '').trim());
              var features = Array.isArray(p.features) ? p.features : [];
              var featuresHtml = features.map(function(f) { return '<li>' + escapeHtml(String(f).trim()) + '</li>'; }).join('');
              var ctaLabel = (p.ctaLabel || '').trim();
              var ctaUrl = (p.ctaUrl || '').trim();
              var planTheme = (p.theme || 'primary').trim();
              var isExternal = ctaUrl && (ctaUrl.indexOf('http://') === 0 || ctaUrl.indexOf('https://') === 0);
              var targetRel = isExternal ? ' target="_blank" rel="noopener"' : '';
              var ctaHtml = (ctaLabel && ctaUrl) ? '<a href="' + escapeHtml(ctaUrl) + '"' + targetRel + ' class="cta cta-' + escapeHtml(planTheme) + ' plan-cta">' + escapeHtml(ctaLabel) + '</a>' : '';
              var featured = p.featured ? ' featured' : '';
              return '<div class="plan' + featured + '"><div class="plan-name">' + name + '</div><div class="plan-price">' + price + (period ? '<span style="font-size:0.85rem;font-weight:400;color:var(--text-muted)">' + period + '</span>' : '') + '</div><ul class="plan-features">' + featuresHtml + '</ul>' + ctaHtml + '</div>';
            }).join('');
          } else if (id === 'product' && config.items && config.items.length) {
            var items = config.items.filter(function(p) { return (p.name || '').trim(); });
            if (items.length) {
              var sectionTitle = (config.heading || config.title || 'Our products').trim();
              if (!sectionTitle) sectionTitle = 'Our products';
              var titleHtml = '<h2 class="section-heading">' + escapeHtml(sectionTitle) + '</h2>';
              var cols = items.length >= 3 ? 3 : (items.length === 2 ? 2 : 1);
              if (cols > 1) section.classList.add('cols-' + cols);
              section.innerHTML = titleHtml + items.map(function(p) {
                var name = escapeHtml((p.name || 'Product').trim());
                var desc = escapeHtml((p.description || '').trim()).replace(/\n/g, '<br>');
                var price = escapeHtml((p.price || '').trim());
                var img = (p.imageUrl || '').trim();
                var buyUrl = (p.buyUrl || '').trim();
                var buyLabel = (p.buyLabel || 'Buy now').trim();
                if (!buyLabel) buyLabel = 'Buy now';
                var productTheme = (p.theme || 'primary').trim();
                var imgHtml = img ? '<img class="product-image" src="' + escapeHtml(img) + '" alt="' + name + '" loading="lazy">' : '<div class="product-image" style="display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:2rem">?</div>';
                var isExternal = buyUrl && (buyUrl.indexOf('http://') === 0 || buyUrl.indexOf('https://') === 0);
                var targetRel = isExternal ? ' target="_blank" rel="noopener"' : '';
                var buyHtml = buyUrl ? '<a href="' + escapeHtml(buyUrl) + '"' + targetRel + ' class="cta cta-' + escapeHtml(productTheme) + ' product-cta">' + escapeHtml(buyLabel) + '</a>' : '';
                return '<div class="product-card">' + imgHtml + '<div class="product-name">' + name + '</div>' + (desc ? '<div class="product-description">' + desc + '</div>' : '') + '<div class="product-price">' + price + '</div>' + buyHtml + '</div>';
              }).join('');
            }
          } else if (id === 'team' && config.items && config.items.length) {
            var items = config.items.filter(function(m) { return (m.name || '').trim(); });
            var cols = items.length >= 3 ? 3 : (items.length === 2 ? 2 : 1);
            if (items.length) {
              section.classList.add('cols-' + cols);
              section.innerHTML = items.map(function(m) {
                var name = escapeHtml((m.name || '').trim());
                var role = escapeHtml((m.role || '').trim());
                var img = (m.imageUrl || '').trim();
                var link = (m.link || '').trim();
                var photoHtml = img ? '<img class="member-photo" src="' + escapeHtml(img) + '" alt="' + name + '" loading="lazy">' : '<div class="member-photo" style="background:var(--border);display:flex;align-items:center;justify-content:center;font-size:1.5rem;color:var(--text-muted)">?</div>';
                var inner = photoHtml + '<div class="member-name">' + name + '</div><div class="member-role">' + role + '</div>';
                return link ? '<a href="' + escapeHtml(link) + '" target="_blank" rel="noopener" style="color:inherit;text-decoration:none">' + inner + '</a>' : '<div>' + inner + '</div>';
              }).join('');
            }
          } else if (id === 'video' && (config.url || '').trim()) {
            var url = (config.url || '').trim();
            var embed = '';
            var yt = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);
            var vimeo = url.match(/vimeo\.com\/(?:video\/)?(\d+)/);
            if (yt) embed = 'https://www.youtube.com/embed/' + yt[1];
            else if (vimeo) embed = 'https://player.vimeo.com/video/' + vimeo[1];
            if (embed) section.innerHTML = '<iframe src="' + escapeHtml(embed) + '" loading="lazy" allowfullscreen></iframe>';
          } else if (id === 'gallery' && config.items && config.items.length) {
            var items = config.items.filter(function(i) { return (i.url || '').trim(); });
            if (items.length) {
              var style = (config.galleryStyle || config.style || 'carousel').trim().toLowerCase();
              if (['carousel', 'grid', 'strip'].indexOf(style) < 0) style = 'carousel';
              var heightVmin = parseInt(config.galleryHeight || config.height, 10);
              if (isNaN(heightVmin) || heightVmin < 20 || heightVmin > 100) heightVmin = 52;
              var cols = parseInt(config.galleryColumns || config.columns, 10);
              if (style === 'grid' && (cols === 2 || cols === 3)) { section.classList.add('gallery-cols-' + cols); }
              else if (style === 'grid') { section.classList.add('gallery-cols-2'); }
              section.classList.add('gallery-style-' + style);
              section.style.setProperty('--gallery-img-height', heightVmin + 'vmin');
              section.innerHTML = '<div class="gallery-track">' + items.map(function(i, idx) {
                var url = (i.url || '').trim();
                var cap = (i.caption || '').trim();
                return '<div class="gallery-slide" data-index="' + idx + '"><figure><img src="' + escapeHtml(url) + '" alt="' + escapeHtml(cap) + '" loading="lazy" data-caption="' + escapeHtml(cap) + '"><figcaption class="gallery-caption">' + escapeHtml(cap) + '</figcaption></figure></div>';
              }).join('') + '</div>';
            }
          } else if (id === 'appstores') {
            var appUrl = (config.appStoreUrl || '').trim();
            var playUrl = (config.playStoreUrl || '').trim();
            var parts = [];
            if (appUrl) parts.push('<a href="' + escapeHtml(appUrl) + '" target="_blank" rel="noopener"><img src="https://tools.applemediaservices.com/api/badges/download-app-store/black/en-us?size=250x83" alt="Download on the App Store" height="40"></a>');
            if (playUrl) parts.push('<a href="' + escapeHtml(playUrl) + '" target="_blank" rel="noopener"><img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png" alt="Get it on Google Play" height="40"></a>');
            if (parts.length) section.innerHTML = parts.join('');
          } else if (id === 'divider') {
            var style = (config.style || 'line').trim();
            var height = Math.max(1, parseInt(config.height, 10) || 2);
            if (style === 'space') section.innerHTML = '<div class="widget-divider-space" style="height:' + height + 'rem"></div>';
            else section.innerHTML = '<hr class="widget-divider-line">';
          } else if (id === 'trust' && config.items && config.items.length) {
            var items = config.items.filter(function(b) { return (b.text || '').trim(); });
            if (items.length) section.innerHTML = items.map(function(b) {
              var icon = escapeHtml((b.icon || '✓').trim().slice(0, 2));
              var text = escapeHtml((b.text || '').trim());
              return '<div class="trust-item"><span class="trust-icon">' + icon + '</span><span>' + text + '</span></div>';
            }).join('');
          } else if (id === 'nav') {
            var logoText = (config.logoText || '').trim();
            var logoUrl = (config.logoUrl || '').trim();
            var links = config.links && config.links.length ? config.links.filter(function(l) { return (l.url || '').trim(); }) : [];
            var logoHtml = (logoUrl ? '<a href="' + escapeHtml(logoUrl) + '" class="nav-logo">' : '<span class="nav-logo">') + escapeHtml(logoText || host) + (logoUrl ? '</a>' : '</span>');
            var linksHtml = links.length ? '<ul class="nav-links">' + links.map(function(l) {
              var rawUrl = (l.url || '').trim();
              var isFragment = rawUrl.charAt(0) === '#' || (rawUrl.length > 0 && rawUrl.indexOf('://') < 0 && rawUrl.indexOf('mailto:') !== 0 && rawUrl.indexOf('tel:') !== 0);
              var href = isFragment ? (rawUrl.charAt(0) === '#' ? rawUrl : '#' + rawUrl) : rawUrl;
              var targetRel = isFragment ? '' : ' target="_blank" rel="noopener"';
              return '<li><a href="' + escapeHtml(href) + '"' + targetRel + '>' + escapeHtml((l.label || l.url || 'Link').trim()) + '</a></li>';
            }).join('') + '</ul>' : '';
            section.innerHTML = '<div class="nav-inner">' + logoHtml + linksHtml + '</div>';
          } else if (id === 'footer') {
            var footerYear = new Date().getFullYear();
            var title = (config.title || '').trim();
            var rawDesc = (config.description || config.text || '').trim().replace(/\[year\]/g, footerYear);
            var isCopyrightOnly = /^\s*©\s*\d{4}/.test(rawDesc) && rawDesc.length < 80;
            var description = isCopyrightOnly ? '' : rawDesc;
            var linksTitle = (config.linksTitle || 'Quick Links').trim();
            var links = config.links && config.links.length ? config.links.filter(function(l) { return (l.url || '').trim(); }) : [];
            var contactTitle = (config.contactTitle || 'Contact').trim();
            var contactText = (config.contactText || '').trim();
            var section1 = (title || description) ? '<div class="footer-section footer-brand">' + (title ? '<div class="footer-section-title">' + escapeHtml(title) + '</div>' : '') + (description ? '<p>' + escapeHtml(description).replace(/\n/g, '<br>') + '</p>' : '') + '</div>' : '';
            var linksList = links.map(function(l) {
              var rawUrl = (l.url || '').trim();
              var isFragment = rawUrl.charAt(0) === '#' || (rawUrl.length > 0 && rawUrl.indexOf('://') < 0 && rawUrl.indexOf('mailto:') !== 0 && rawUrl.indexOf('tel:') !== 0);
              var href = isFragment ? (rawUrl.charAt(0) === '#' ? rawUrl : '#' + rawUrl) : rawUrl;
              var targetRel = isFragment ? '' : ' target="_blank" rel="noopener"';
              return '<li><a href="' + escapeHtml(href) + '"' + targetRel + '>' + escapeHtml((l.label || l.url || 'Link').trim()) + '</a></li>';
            }).join('');
            var section2 = (linksTitle || linksList) ? '<div class="footer-section"><div class="footer-section-title">' + escapeHtml(linksTitle) + '</div><ul class="footer-links">' + linksList + '</ul></div>' : '';
            var section3 = (contactTitle || contactText) ? '<div class="footer-section footer-contact"><div class="footer-section-title">' + escapeHtml(contactTitle) + '</div>' + (contactText ? '<p>' + escapeHtml(contactText).replace(/\n/g, '<br>') + '</p>' : '') + '</div>' : '';
            var copyrightText = (config.copyright && String(config.copyright).trim()) ? String(config.copyright).trim().replace(/\[year\]/g, footerYear) : (isCopyrightOnly ? rawDesc : (config.showCopyright !== false ? ('© ' + footerYear + ' ' + host) : ''));
            section.innerHTML = '<div class="footer-content"><div class="footer-sections">' + section1 + section2 + section3 + '</div>' + (copyrightText ? '<div class="footer-copyright">' + escapeHtml(copyrightText) + '</div>' : '') + '</div>';
          } else if (id === 'map') {
            var mapHeading = (config.heading || config.title || 'Find us').trim();
            var address = (config.address || '').trim();
            var mapUrl = (config.mapUrl || '').trim();
            var mapEmbed = '';
            if (mapUrl && (mapUrl.indexOf('embed') >= 0 || mapUrl.indexOf('output=embed') >= 0)) {
              mapEmbed = '<iframe src="' + escapeHtml(mapUrl) + '" width="100%" height="250" style="border:0;max-width:600px;margin:0 auto;display:block" allowfullscreen loading="lazy"></iframe>';
            } else if (address || mapUrl) {
              var q = address || mapUrl;
              mapEmbed = '<iframe src="https://www.google.com/maps?q=' + encodeURIComponent(q) + '&output=embed" width="100%" height="250" style="border:0;max-width:600px;margin:0 auto;display:block" allowfullscreen loading="lazy"></iframe>';
            }
            section.innerHTML = (mapHeading ? '<h2 class="section-heading">' + escapeHtml(mapHeading) + '</h2>' : '') + (address ? '<p class="widget-map-address">' + escapeHtml(address).replace(/\n/g, '<br>') + '</p>' : '') + (mapEmbed || '');
          } else if (id === 'announcement') {
            var msg = (config.message || config.text || '').trim();
            var linkUrl = (config.linkUrl || '').trim();
            var linkLabel = (config.linkLabel || '').trim();
            var theme = (config.theme || 'primary').trim();
            if (msg) {
              var linkHtml = (linkUrl && linkLabel) ? ' <a href="' + escapeHtml(linkUrl) + '" class="announcement-link">' + escapeHtml(linkLabel) + '</a>' : '';
              section.innerHTML = '<p class="announcement-text">' + escapeHtml(msg) + linkHtml + '</p>';
              section.classList.add('announcement-' + theme);
            }
          } else if (id === 'newsletter') {
            var label = (config.label || 'Subscribe to our newsletter').trim();
            var btnLabel = (config.buttonLabel || config.ctaLabel || 'Subscribe').trim();
            var theme = (config.theme || 'primary').trim();
            section.innerHTML = '<p class="tagline">' + escapeHtml(label) + '</p><form class="newsletter-form notifyme-inline"><input type="email" name="email" required placeholder="you@example.com"><button type="submit" class="cta cta-' + escapeHtml(theme) + '">' + escapeHtml(btnLabel) + '</button></form><p class="form-status newsletter-status" aria-live="polite"></p>';
          } else if (id === 'hours' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'Opening hours').trim();
            var items = config.items.filter(function(h) { return (h.days || '').trim(); });
            if (items.length) {
              var rows = items.map(function(h) { return '<tr><td>' + escapeHtml((h.days || '').trim()) + '</td><td>' + escapeHtml((h.hours || '').trim()) + '</td></tr>'; }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<table class="widget-hours"><tbody>' + rows + '</tbody></table>';
            }
          } else if (id === 'comparison' && config.columns && config.columns.length) {
            var heading = (config.heading || config.title || 'Compare').trim();
            var features = config.features || [];
            var cols = config.columns;
            var headerRow = '<tr><th></th>' + cols.map(function(c) { return '<th>' + escapeHtml((c.name || '').trim()) + '</th>'; }).join('') + '</tr>';
            var bodyRows = features.map(function(f) {
              var name = (f.name || f.feature || '').trim();
              var vals = (f.values || []).length ? f.values : cols.map(function() { return ''; });
              return '<tr><td>' + escapeHtml(name) + '</td>' + cols.map(function(c, i) { var v = vals[i]; return '<td>' + (v === true || v === '✓' || v === 'yes' ? '✓' : escapeHtml(String(v || '').trim())) + '</td>'; }).join('') + '</tr>';
            }).join('');
            section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-comparison-wrap"><table class="widget-comparison"><thead>' + headerRow + '</thead><tbody>' + bodyRows + '</tbody></table></div>';
          } else if (id === 'blog' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'Latest posts').trim();
            var items = config.items.filter(function(p) { return (p.title || '').trim(); });
            if (items.length) {
              var list = items.map(function(p) {
                var title = escapeHtml((p.title || '').trim());
                var excerpt = escapeHtml((p.excerpt || '').trim()).replace(/\n/g, ' ');
                var url = (p.url || '').trim();
                var date = (p.date || '').trim();
                var link = url ? '<a href="' + escapeHtml(url) + '" target="_blank" rel="noopener">' + title + '</a>' : title;
                return '<article class="blog-item"><h3 class="blog-title">' + link + '</h3>' + (excerpt ? '<p class="blog-excerpt">' + excerpt + '</p>' : '') + (date ? '<time class="blog-date">' + escapeHtml(date) + '</time>' : '') + '</article>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-blog">' + list + '</div>';
            }
          } else if (id === 'reviews' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'Reviews').trim();
            var items = config.items.filter(function(r) { return (r.quote || '').trim(); });
            if (items.length) {
              var list = items.map(function(r) {
                var quote = escapeHtml((r.quote || '').trim()).replace(/\n/g, '<br>');
                var name = escapeHtml((r.name || '').trim());
                var rating = parseInt(r.rating, 10) || 5;
                var stars = '★'.repeat(Math.min(5, Math.max(0, rating))) + '☆'.repeat(5 - Math.min(5, Math.max(0, rating)));
                var source = escapeHtml((r.source || '').trim());
                return '<div class="review-item"><div class="review-stars">' + stars + '</div><blockquote class="review-quote">' + quote + '</blockquote><cite>— ' + name + (source ? ', ' + source : '') + '</cite></div>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-reviews">' + list + '</div>';
            }
          } else if (id === 'accordion' && config.items && config.items.length) {
            var heading = (config.heading || config.title || '').trim();
            var items = config.items.filter(function(a) { return (a.title || a.label || '').trim(); });
            if (items.length) {
              var list = items.map(function(a, i) {
                var title = escapeHtml((a.title || a.label || '').trim());
                var content = escapeHtml((a.content || a.body || '').trim()).replace(/\n/g, '<br>');
                return '<details class="accordion-item"><summary>' + title + '</summary><div class="accordion-content">' + content + '</div></details>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-accordion">' + list + '</div>';
            }
          } else if (id === 'ctabanner') {
            var msg = (config.message || config.text || '').trim();
            var ctaLabel = (config.ctaLabel || config.label || '').trim();
            var ctaUrl = (config.ctaUrl || config.url || '').trim();
            var theme = (config.theme || 'primary').trim();
            if (msg) {
              var ctaHtml = (ctaLabel && ctaUrl) ? ' <a href="' + escapeHtml(ctaUrl) + '" class="cta cta-' + escapeHtml(theme) + '">' + escapeHtml(ctaLabel) + '</a>' : '';
              section.innerHTML = '<div class="ctabanner-inner"><p>' + escapeHtml(msg) + ctaHtml + '</p></div>';
              section.classList.add('widget-full-bg');
            }
          } else if (id === 'contactinfo') {
            var heading = (config.heading || config.title || 'Contact').trim();
            var phone = (config.phone || '').trim();
            var email = (config.email || '').trim();
            var address = (config.address || '').trim();
            var links = config.links && config.links.length ? config.links.filter(function(l) { return (l.url || '').trim(); }) : [];
            var parts = [];
            if (phone) parts.push('<p><a href="tel:' + escapeHtml(phone.replace(/\s/g, '')) + '">' + escapeHtml(phone) + '</a></p>');
            if (email) parts.push('<p><a href="mailto:' + escapeHtml(email) + '">' + escapeHtml(email) + '</a></p>');
            if (address) parts.push('<p class="contactinfo-address">' + escapeHtml(address).replace(/\n/g, '<br>') + '</p>');
            if (links.length) parts.push('<ul class="contactinfo-links">' + links.map(function(l) { return '<li><a href="' + escapeHtml(l.url) + '" target="_blank" rel="noopener">' + escapeHtml((l.label || l.url || '').trim()) + '</a></li>'; }).join('') + '</ul>');
            if (parts.length) section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-contactinfo">' + parts.join('') + '</div>';
          } else if (id === 'menu' && config.categories && config.categories.length) {
            var heading = (config.heading || config.title || 'Menu').trim();
            var cats = config.categories.filter(function(c) { return (c.name || '').trim(); });
            if (cats.length) {
              var html = cats.map(function(cat) {
                var items = (cat.items || []).filter(function(i) { return (i.name || '').trim(); });
                var itemsHtml = items.map(function(i) {
                  var name = escapeHtml((i.name || '').trim());
                  var price = escapeHtml((i.price || '').trim());
                  var desc = escapeHtml((i.description || '').trim()).replace(/\n/g, '<br>');
                  return '<div class="menu-item"><span class="menu-item-name">' + name + '</span>' + (price ? '<span class="menu-item-price">' + price + '</span>' : '') + (desc ? '<p class="menu-item-desc">' + desc + '</p>' : '') + '</div>';
                }).join('');
                return '<div class="menu-category"><h3 class="menu-cat-name">' + escapeHtml((cat.name || '').trim()) + '</h3>' + itemsHtml + '</div>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-menu">' + html + '</div>';
            }
          } else if (id === 'events' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'Upcoming events').trim();
            var items = config.items.filter(function(e) { return (e.title || '').trim(); });
            if (items.length) {
              var list = items.map(function(e) {
                var title = escapeHtml((e.title || '').trim());
                var date = escapeHtml((e.date || '').trim());
                var location = escapeHtml((e.location || '').trim());
                var url = (e.url || '').trim();
                var link = url ? '<a href="' + escapeHtml(url) + '" target="_blank" rel="noopener">' + title + '</a>' : title;
                return '<div class="event-item"><div class="event-title">' + link + '</div>' + (date ? '<div class="event-date">' + date + '</div>' : '') + (location ? '<div class="event-location">' + location + '</div>' : '') + '</div>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-events">' + list + '</div>';
            }
          } else if (id === 'tabs' && config.items && config.items.length) {
            var heading = (config.heading || config.title || '').trim();
            var items = config.items.filter(function(t) { return (t.label || t.title || '').trim(); });
            if (items.length) {
              var tabLabels = items.map(function(t, i) { return '<button type="button" class="tab-label' + (i === 0 ? ' active' : '') + '" data-tab="' + i + '">' + escapeHtml((t.label || t.title || '').trim()) + '</button>'; }).join('');
              var tabPanels = items.map(function(t, i) { var c = escapeHtml((t.content || t.body || '').trim()).replace(/\n/g, '<br>'); return '<div class="tab-panel' + (i === 0 ? ' active' : '') + '" data-tab="' + i + '">' + c + '</div>'; }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-tabs"><div class="tab-labels">' + tabLabels + '</div><div class="tab-panels">' + tabPanels + '</div></div>';
            }
          } else if (id === 'initiatives' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'Our impact').trim();
            var viewAllLabel = (config.viewAllLabel || 'View all initiatives').trim();
            var viewAllUrl = (config.viewAllUrl || '').trim();
            var items = config.items.filter(function(i) { return (i.title || '').trim(); });
            if (items.length) {
              var cards = items.map(function(i) {
                var title = escapeHtml((i.title || '').trim());
                var desc = escapeHtml((i.description || '').trim()).replace(/\n/g, '<br>');
                var current = parseInt(i.current, 10) || 0;
                var goal = parseInt(i.goal, 10) || 1;
                var unit = escapeHtml((i.unit || '').trim());
                var pct = goal > 0 ? Math.min(100, Math.round((current / goal) * 100)) : 0;
                var link = (i.linkUrl || i.url || '').trim();
                var linkLabel = escapeHtml((i.linkLabel || 'View initiative').trim());
                var cardContent = '<div class="initiative-card"><h3 class="initiative-title">' + title + '</h3>' + (desc ? '<p class="initiative-desc">' + desc + '</p>' : '') + '<div class="initiative-progress-wrap"><div class="initiative-progress-bar" style="width:' + pct + '%"></div></div><p class="initiative-stats">' + current.toLocaleString() + ' ' + (unit || '') + ' out of ' + goal.toLocaleString() + ' goal</p>' + (link ? '<a href="' + escapeHtml(link) + '" class="initiative-link"' + (link.indexOf('http') === 0 ? ' target="_blank" rel="noopener"' : '') + '>' + linkLabel + '</a>' : '') + '</div>';
                return cardContent;
              }).join('');
              var viewAllHtml = viewAllUrl ? '<p class="initiatives-view-all"><a href="' + escapeHtml(viewAllUrl) + '" class="cta cta-outline"' + (viewAllUrl.indexOf('http') === 0 ? ' target="_blank" rel="noopener"' : '') + '>' + escapeHtml(viewAllLabel) + '</a></p>' : '';
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-initiatives">' + cards + '</div>' + viewAllHtml;
            }
          } else if (id === 'steps' && config.items && config.items.length) {
            var heading = (config.heading || config.title || 'How it works').trim();
            var items = config.items.filter(function(s) { return (s.title || '').trim(); });
            if (items.length) {
              var stepsHtml = items.map(function(s, i) {
                var num = (s.number !== undefined && s.number !== null) ? parseInt(s.number, 10) : (i + 1);
                var title = escapeHtml((s.title || '').trim());
                var desc = escapeHtml((s.description || s.desc || '').trim()).replace(/\n/g, '<br>');
                var link = (s.linkUrl || s.url || '').trim();
                var linkLabel = escapeHtml((s.linkLabel || '').trim());
                return '<div class="step-item"><div class="step-number">' + num + '</div><div class="step-content"><h3 class="step-title">' + title + '</h3>' + (desc ? '<p class="step-desc">' + desc + '</p>' : '') + (link && linkLabel ? '<a href="' + escapeHtml(link) + '" class="step-link"' + (link.indexOf('http') === 0 ? ' target="_blank" rel="noopener"' : '') + '>' + linkLabel + '</a>' : '') + '</div></div>';
              }).join('');
              section.innerHTML = (heading ? '<h2 class="section-heading">' + escapeHtml(heading) + '</h2>' : '') + '<div class="widget-steps">' + stepsHtml + '</div>';
            }
          }
          if (section.classList.contains('widget-full-bg') && section.innerHTML) {
            var first = section.firstElementChild;
            if (first && first.classList && first.classList.contains('widget-full-bg-inner')) {
              /* Features with bg: already built with inner in place, skip wrap */
            } else {
              var inner = document.createElement('div');
              inner.className = 'widget-full-bg-inner';
              for (var i = 0; i < section.classList.length; i++) {
                var c = section.classList[i];
                if (c !== 'widget' && c !== 'widget-full-bg') inner.classList.add(c);
              }
              inner.innerHTML = section.innerHTML;
              section.innerHTML = '';
              section.appendChild(inner);
            }
          }
          if (section.innerHTML || section.firstChild) contentEl.appendChild(section);
        });
        initScrollAnimations(contentEl);
        var countdownEl = contentEl.querySelector('#countdown-value');
        if (countdownEl) {
          var countdownSection = countdownEl.closest('.widget-countdown');
          var targetStr = countdownSection && countdownSection.dataset.target;
          if (targetStr) {
            var targetDate = new Date(targetStr + 'T23:59:59');
            function updateCountdown() {
              var now = new Date();
              if (now >= targetDate) { countdownEl.textContent = '0 days'; return; }
              var days = Math.ceil((targetDate - now) / (24 * 60 * 60 * 1000));
              countdownEl.textContent = days + ' day' + (days === 1 ? '' : 's');
            }
            updateCountdown();
            setInterval(updateCountdown, 60000);
          }
        }
      }

      function renderLegacy(data) {
        var tagline = data.tagline || 'This domain is registered.';
        var showForm = data.showForm !== false;
        contentEl.innerHTML = '<section class="widget widget-hero animate-reveal"><h1 class="domain">' + escapeHtml(hostname) + '</h1><p class="tagline">' + escapeHtml(tagline) + '</p></section>' +
          (showForm ? '<section class="widget widget-contact animate-reveal"><h2 class="section-heading">Get in touch</h2><form id="contact-form"><label for="email">Your email</label><input type="email" id="email" name="email" required placeholder="you@example.com"><label for="message">Message</label><textarea id="message" name="message" required placeholder="Your message…"></textarea><button type="submit" id="submit-btn">Send</button><p class="form-status" id="form-status" aria-live="polite"></p></form></section>' : '');
        initScrollAnimations(contentEl);
      }

      function renderNotFound() {
        var pageTitle = document.getElementById('page-title');
        if (pageTitle) pageTitle.textContent = 'Page not found — ' + hostname;
        contentEl.innerHTML = '<section class="widget widget-hero animate-reveal"><h1 class="domain">Page not found</h1><p class="tagline">The page you\'re looking for doesn\'t exist or has been removed.</p><p class="hero-ctas"><a href="/" class="cta cta-primary">Go to homepage</a></p></section>';
        footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
        initScrollAnimations(contentEl);
      }

      var legalContent = { privacy: '', terms: '' };

      function renderLegal(data, hasWidgets) {
        var privacy = (data.privacyPolicy || '').trim();
        var terms = (data.termsAndConditions || '').trim();
        legalContent.privacy = privacy;
        legalContent.terms = terms;
        if (!privacy && !terms) return;
        var links = [];
        if (privacy) links.push('<a href="#" data-legal="privacy">Privacy Policy</a>');
        if (terms) links.push('<a href="#" data-legal="terms">Terms &amp; Conditions</a>');
        var year = new Date().getFullYear();
        var footerHtml = hasWidgets ? links.join(' &middot; ') : ('© ' + year + (links.length ? ' &middot; ' + links.join(' &middot; ') : ''));
        footerEl.innerHTML = footerHtml;
      }

      function openLegalDialog(type) {
        var title = type === 'privacy' ? 'Privacy Policy' : 'Terms &amp; Conditions';
        var content = type === 'privacy' ? legalContent.privacy : legalContent.terms;
        var dialog = document.getElementById('legal-dialog');
        var titleEl = document.getElementById('legal-dialog-title');
        var bodyEl = document.getElementById('legal-dialog-content');
        if (!dialog || !titleEl || !bodyEl) return;
        titleEl.innerHTML = title;
        bodyEl.textContent = content;
        dialog.classList.add('is-open');
        dialog.setAttribute('aria-hidden', 'false');
      }

      function closeLegalDialog() {
        var dialog = document.getElementById('legal-dialog');
        if (dialog) {
          dialog.classList.remove('is-open');
          dialog.setAttribute('aria-hidden', 'true');
        }
      }

      document.body.addEventListener('click', function(e) {
        var link = e.target.closest('a[data-legal]');
        if (link) {
          e.preventDefault();
          openLegalDialog(link.getAttribute('data-legal'));
          return;
        }
        var tabLabel = e.target.closest('.tab-label');
        if (tabLabel) {
          var tabs = tabLabel.closest('.widget-tabs');
          if (tabs) {
            var idx = tabLabel.getAttribute('data-tab');
            tabs.querySelectorAll('.tab-label').forEach(function(l) { l.classList.remove('active'); });
            tabs.querySelectorAll('.tab-panel').forEach(function(p) { p.classList.remove('active'); });
            tabLabel.classList.add('active');
            var panel = tabs.querySelector('.tab-panel[data-tab="' + idx + '"]');
            if (panel) panel.classList.add('active');
          }
        }
      });
      var legalCloseBtn = document.getElementById('legal-dialog-close');
      if (legalCloseBtn) legalCloseBtn.addEventListener('click', closeLegalDialog);
      var legalDialog = document.getElementById('legal-dialog');
      if (legalDialog) {
        legalDialog.addEventListener('click', function(e) {
          if (e.target === legalDialog) closeLegalDialog();
        });
      }

      function applyPageSettings(data, cacheBust) {
        cacheBust = cacheBust || Date.now();
        var title = data.pageTitle || hostname;
        var titleEl = document.getElementById('page-title');
        if (titleEl) titleEl.textContent = title;
        var favicon = data.favicon;
        if (favicon && favicon.trim()) {
          var link = document.querySelector('link[rel="icon"]') || document.createElement('link');
          link.rel = 'icon';
          link.href = favicon.trim() + (favicon.indexOf('?') >= 0 ? '&' : '?') + 'v=' + cacheBust;
          if (!link.parentNode) document.head.appendChild(link);
        }
        var gtmId = data.gtmContainerId;
        if (gtmId && /^GTM-[A-Z0-9]+$/i.test(gtmId.trim())) {
          (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer',gtmId.trim());
          var noscript = document.createElement('noscript');
          var iframe = document.createElement('iframe');
          iframe.src = 'https://www.googletagmanager.com/ns.html?id=' + gtmId.trim();
          iframe.height = '0';
          iframe.width = '0';
          iframe.style.cssText = 'display:none;visibility:hidden';
          noscript.appendChild(iframe);
          document.body.insertBefore(noscript, document.body.firstChild);
        }
        var scripts = data.customScripts;
        if (scripts && scripts.trim()) {
          var div = document.createElement('div');
          div.innerHTML = scripts.trim();
          [].forEach.call(div.querySelectorAll('script'), function(s) {
            var el = document.createElement('script');
            if (s.src) el.src = s.src;
            else el.textContent = s.textContent;
            for (var i = 0; i < s.attributes.length; i++) {
              var a = s.attributes[i];
              if (a.name !== 'src') el.setAttribute(a.name, a.value);
            }
            document.head.appendChild(el);
          });
          [].forEach.call(div.querySelectorAll('link'), function(l) {
            document.head.appendChild(l.cloneNode(true));
          });
        }
        var customStyles = data.customButtonStyles;
        var oldEl = document.getElementById('domain-placeholder-custom-button-styles');
        if (oldEl) oldEl.remove();
        if (Array.isArray(customStyles) && customStyles.length > 0) {
          var css = '';
          customStyles.forEach(function(s) {
            var id = (s.id || '').toString().replace(/[^a-zA-Z0-9_-]/g, '');
            if (!id) return;
            var bg = (s.backgroundColor || '#0f766e').trim();
            var tc = (s.textColor || '#ffffff').trim();
            if (!/^#[0-9A-Fa-f]{6}$/.test(bg)) bg = '#0f766e';
            if (!/^#[0-9A-Fa-f]{6}$/.test(tc)) tc = '#ffffff';
            css += '.cta-' + id + '{color:' + tc + ';background:' + bg + ';}.cta-' + id + ':hover{filter:brightness(1.08);}';
          });
          if (css) {
            var styleEl = document.createElement('style');
            styleEl.id = 'domain-placeholder-custom-button-styles';
            styleEl.textContent = css;
            document.head.appendChild(styleEl);
          }
        }
      }

      function tryDomain(domainKey, onSuccess, onFallback) {
        var docRef = path
          ? db.collection('domains').doc(domainKey).collection('pages').doc(path)
          : db.collection('domains').doc(domainKey);
        docRef.get().then(function(snap) {
          if (snap.exists) {
            var data = snap.data();
            var cacheBust = data.updatedAt && data.updatedAt.toMillis ? data.updatedAt.toMillis() : Date.now();
            applyPageSettings(data, cacheBust);
            var widgets = data.widgets;
            if (Array.isArray(widgets) && widgets.length > 0) {
              footerEl.textContent = '';
              renderWidgets(widgets, domainKey);
              renderLegal(data, true);
            } else {
              footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
              renderLegacy(data);
              renderLegal(data, false);
            }
            onSuccess();
          } else {
            onFallback();
          }
        }).catch(function() { onFallback(); });
      }

      function loadAndRender() {
        var altHostname = hostname.startsWith('www.') ? hostname.replace(/^www\./, '') : 'www.' + hostname;
        function fallbackToRoot() {
          function tryRoot(domainKey) {
            db.collection('domains').doc(domainKey).get().then(function(rootSnap) {
              if (rootSnap.exists) {
                var data = rootSnap.data();
                var cacheBust = data.updatedAt && data.updatedAt.toMillis ? data.updatedAt.toMillis() : Date.now();
                applyPageSettings(data, cacheBust);
                var widgets = data.widgets;
                if (Array.isArray(widgets) && widgets.length > 0) {
                  footerEl.textContent = '';
                  renderWidgets(widgets, domainKey);
                  renderLegal(data, true);
                } else {
                  footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
                  renderLegacy(data);
                  renderLegal(data, false);
                }
              } else if (domainKey === hostname) {
                tryRoot(altHostname);
              } else {
                footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
                renderLegacy({ tagline: 'This domain is registered.', showForm: true });
              }
            }).catch(function() {
              if (domainKey === hostname) { tryRoot(altHostname); } else {
                footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
                renderLegacy({ tagline: 'This domain is registered.', showForm: true });
              }
            });
          }
          tryRoot(hostname);
        }

        if (path) {
          tryDomain(hostname, function() {}, function() {
            tryDomain(altHostname, function() {}, renderNotFound);
          });
        } else {
          tryDomain(hostname, function() {}, function() {
            tryDomain(altHostname, function() {}, function() {
              footerEl.textContent = '\u00a9 ' + new Date().getFullYear();
              renderLegacy({ tagline: 'This domain is registered.', showForm: true });
            });
          });
        }
      }
      loadAndRender();

      document.body.addEventListener('submit', function(e) {
        if (e.target.classList && (e.target.classList.contains('notifyme-form') || e.target.classList.contains('newsletter-form'))) {
          e.preventDefault();
          var form = e.target;
          var btn = form.querySelector('button[type="submit"]');
          var statusEl = form.parentElement && form.parentElement.querySelector('.notifyme-status, .newsletter-status');
          var email = (form.querySelector('input[type="email"]') && form.querySelector('input[type="email"]').value || '').trim();
          var source = e.target.classList.contains('newsletter-form') ? 'newsletter' : 'notifyme';
          if (btn) btn.disabled = true;
          if (statusEl) { statusEl.textContent = ''; statusEl.className = 'form-status ' + (source === 'newsletter' ? 'newsletter-status' : 'notifyme-status'); }
          db.collection('signups').add({ domain: hostname, path: path || null, email: email, source: source, createdAt: firebase.firestore.FieldValue.serverTimestamp() }).then(function() {
            if (statusEl) { statusEl.textContent = source === 'newsletter' ? 'Thanks! You\'re subscribed.' : 'Thanks! We\'ll notify you.'; statusEl.className = 'form-status success ' + (source === 'newsletter' ? 'newsletter-status' : 'notifyme-status'); }
            form.reset();
          }).catch(function() {
            if (statusEl) { statusEl.textContent = 'Something went wrong.'; statusEl.className = 'form-status error ' + (source === 'newsletter' ? 'newsletter-status' : 'notifyme-status'); }
          }).finally(function() { if (btn) btn.disabled = false; });
          return;
        }
        if (e.target.id !== 'contact-form') return;
        e.preventDefault();
        var form = e.target;
        var btn = form.querySelector('#submit-btn') || form.querySelector('button[type="submit"]');
        var statusEl = form.querySelector('#form-status');
        var email = (form.querySelector('#email') && form.querySelector('#email').value || '').trim();
        var message = (form.querySelector('#message') && form.querySelector('#message').value || '').trim();
        if (btn) btn.disabled = true;
        if (statusEl) { statusEl.textContent = ''; statusEl.className = 'form-status'; }
        var meta = collectMetadata();
        var ipPromise = getClientIp().then(function(ip) { return ip || getIpFromIpify(); });
        ipPromise.then(function(ip) {
          var payload = { domain: hostname, path: path || null, email: email, message: message, createdAt: firebase.firestore.FieldValue.serverTimestamp(), userAgent: meta.userAgent, language: meta.language, referrer: meta.referrer || null, screen: meta.screen, timezone: meta.timezone };
          if (ip) payload.ip = ip;
          return db.collection('submissions').add(payload);
        }).then(function() {
          if (statusEl) { statusEl.textContent = 'Thanks, your message was sent.'; statusEl.className = 'form-status success'; }
          form.reset();
        }).catch(function() {
          if (statusEl) { statusEl.textContent = 'Something went wrong. Please try again.'; statusEl.className = 'form-status error'; }
        }).finally(function() { if (btn) btn.disabled = false; });
      });

      function getClientIp() {
        return fetch(window.location.origin + '/cdn-cgi/trace')
          .then(function(r) { return r.text(); })
          .then(function(t) {
            var m = t.match(/ip=([^\s]+)/);
            return m ? m[1] : null;
          })
          .catch(function() { return null; });
      }

      function getIpFromIpify() {
        return fetch('https://api.ipify.org?format=json', { mode: 'cors' })
          .then(function(r) { return r.json(); })
          .then(function(o) { return o.ip || null; })
          .catch(function() { return null; });
      }

      function collectMetadata() {
        var meta = {
          userAgent: navigator.userAgent || null,
          language: navigator.language || null,
          languages: Array.isArray(navigator.languages) ? navigator.languages.join(',') : null,
          referrer: document.referrer || null,
          screen: (window.screen ? (window.screen.width + 'x' + window.screen.height) : null),
          timezone: typeof Intl !== 'undefined' && Intl.DateTimeFormat ? Intl.DateTimeFormat().resolvedOptions().timeZone : null
        };
        return meta;
      }

      (function galleryLightbox() {
        var lightbox = document.getElementById('gallery-lightbox');
        if (!lightbox) return;
        var imgEl = lightbox.querySelector('.lightbox-img');
        var captionEl = lightbox.querySelector('.lightbox-caption');
        var closeBtn = lightbox.querySelector('.lightbox-close');
        var prevBtn = lightbox.querySelector('.lightbox-prev');
        var nextBtn = lightbox.querySelector('.lightbox-next');
        var backdrop = lightbox.querySelector('.lightbox-backdrop');
        var sources = [];
        var captions = [];
        var currentIndex = 0;

        function open(index) {
          if (sources.length === 0) return;
          currentIndex = (index + sources.length) % sources.length;
          imgEl.src = sources[currentIndex];
          imgEl.alt = captions[currentIndex] || '';
          captionEl.textContent = captions[currentIndex] || '';
          captionEl.style.display = (captions[currentIndex] || '').trim() ? '' : 'none';
          lightbox.classList.add('is-open');
          lightbox.setAttribute('aria-hidden', 'false');
        }

        function close() {
          lightbox.classList.remove('is-open');
          lightbox.setAttribute('aria-hidden', 'true');
        }

        function goPrev() {
          currentIndex = (currentIndex - 1 + sources.length) % sources.length;
          imgEl.src = sources[currentIndex];
          imgEl.alt = captions[currentIndex] || '';
          captionEl.textContent = captions[currentIndex] || '';
          captionEl.style.display = (captions[currentIndex] || '').trim() ? '' : 'none';
        }

        function goNext() {
          currentIndex = (currentIndex + 1) % sources.length;
          imgEl.src = sources[currentIndex];
          imgEl.alt = captions[currentIndex] || '';
          captionEl.textContent = captions[currentIndex] || '';
          captionEl.style.display = (captions[currentIndex] || '').trim() ? '' : 'none';
        }

        document.body.addEventListener('click', function(e) {
          var galleryImg = e.target.closest('.widget-gallery .gallery-slide img');
          if (galleryImg) {
            e.preventDefault();
            var gallery = galleryImg.closest('.widget-gallery');
            var slides = gallery.querySelectorAll('.gallery-slide img');
            sources = Array.prototype.map.call(slides, function(s) { return s.src || ''; });
            captions = Array.prototype.map.call(slides, function(s) { return (s.getAttribute('data-caption') || s.alt || '').trim(); });
            var idx = parseInt(galleryImg.closest('.gallery-slide').getAttribute('data-index'), 10) || 0;
            open(idx);
            return;
          }
          if (e.target === closeBtn || e.target === backdrop) {
            close();
            return;
          }
          if (e.target === prevBtn) {
            goPrev();
            return;
          }
          if (e.target === nextBtn) {
            goNext();
            return;
          }
        });

        document.addEventListener('keydown', function(e) {
          if (!lightbox.classList.contains('is-open')) return;
          if (e.key === 'Escape') { close(); return; }
          if (e.key === 'ArrowLeft') { goPrev(); return; }
          if (e.key === 'ArrowRight') { goNext(); return; }
        });
      })();
      }

    })();
  </script>
  <!-- Cloudflare Web Analytics: replace YOUR_BEACON_TOKEN with the token from Cloudflare Dashboard > Web Analytics -->
  <script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon='{"token": "YOUR_BEACON_TOKEN"}'></script>
</body>
</html>
