---
/**
 * Cookie consent banner — the user-facing writer for `kiln_consent`.
 *
 * Rendered into BaseLayout.astro for every page on `kiln3d.com`.
 * Self-gates: renders nothing unless at least one tracking provider
 * is configured at build time (PUBLIC_META_PIXEL_ID,
 * PUBLIC_GA4_MEASUREMENT_ID, or PUBLIC_GOOGLE_ADS_CONVERSION_ID).
 * Without that gate, shipping the banner before activation creates
 * a confusing surface — "consent for what tracking?" — and a small
 * legitimacy gap with PRIVACY.md, which discloses no tracking until
 * env vars are set.
 *
 * Also gates the visible UI on cookie absence: if the visitor has
 * already saved a preference, the banner stays hidden until they
 * click the footer's "Cookie preferences" link, which clears the
 * cookie and reloads.
 *
 * Three buttons follow the GDPR-friendliest pattern:
 *   - "Accept all"             grants analytics + advertising
 *   - "Save preferences"       grants exactly the checkbox state
 *   - "Reject non-essential"   grants neither
 * Strictly necessary cookies (auth on app.kiln3d.com, CSRF) are
 * always implicit — there is no opt-out for those, by design.
 *
 * After save, the page reloads so the env-gated pixel components
 * see the new consent state at script-init time.  A reload (rather
 * than a SPA-style state update) is the safest because each pixel
 * inlines its own `readConsent()` snippet at HTML emit, not at
 * runtime — they need a fresh page render to pick up the change.
 *
 * @see ../lib/consent.ts — canonical state shape
 * @see ./MetaPixel.astro — first reader
 * @see ../../../PRIVACY.md §3.2 — public disclosure
 */
const PIXEL_ID = import.meta.env.PUBLIC_META_PIXEL_ID;
const GA4_ID = import.meta.env.PUBLIC_GA4_MEASUREMENT_ID;
const ADS_ID = import.meta.env.PUBLIC_GOOGLE_ADS_CONVERSION_ID;
const ANY_TRACKING_CONFIGURED = Boolean(PIXEL_ID || GA4_ID || ADS_ID);
---

{ANY_TRACKING_CONFIGURED && (
  <div id="kiln-cookie-banner" class="cookie-banner" hidden>
    <div class="inner">
      <p class="copy">
        We use strictly-necessary cookies to keep the site working, and (with
        your consent) analytics + advertising cookies to understand what works.
        <a href="/privacy#cookies">Learn more</a>.
      </p>
      <div class="checkboxes">
        <label>
          <input type="checkbox" checked disabled />
          <span>Necessary (always on)</span>
        </label>
        <label>
          <input type="checkbox" id="kiln-consent-analytics" checked />
          <span>Analytics</span>
        </label>
        <label>
          <input type="checkbox" id="kiln-consent-advertising" checked />
          <span>Advertising</span>
        </label>
      </div>
      <div class="buttons">
        <button type="button" id="kiln-consent-accept-all" class="primary">
          Accept all
        </button>
        <button type="button" id="kiln-consent-save" class="secondary">
          Save preferences
        </button>
        <button type="button" id="kiln-consent-reject" class="tertiary">
          Reject non-essential
        </button>
      </div>
    </div>
  </div>

  <script is:inline>
    (() => {
      const COOKIE = "kiln_consent";
      const ONE_YEAR = 60 * 60 * 24 * 365;
      const banner = document.getElementById("kiln-cookie-banner");
      if (!banner) return;

      // Show only when no preference has been saved yet.
      const hasCookie = document.cookie.split("; ").some((c) => c.startsWith(COOKIE + "="));
      if (!hasCookie) banner.hidden = false;

      const write = (analytics, advertising) => {
        const next = { necessary: true, analytics, advertising };
        const value = encodeURIComponent(JSON.stringify(next));
        document.cookie =
          COOKIE + "=" + value +
          "; path=/" +
          "; max-age=" + ONE_YEAR +
          "; SameSite=Lax" +
          "; Secure";
        banner.hidden = true;
        // Reload so the env-gated pixel components pick up consent
        // at script-init time, not via runtime state plumbing.
        window.location.reload();
      };

      document.getElementById("kiln-consent-accept-all")
        ?.addEventListener("click", () => write(true, true));

      document.getElementById("kiln-consent-save")
        ?.addEventListener("click", () => {
          const a = /** @type {HTMLInputElement} */ (document.getElementById("kiln-consent-analytics"));
          const b = /** @type {HTMLInputElement} */ (document.getElementById("kiln-consent-advertising"));
          write(a?.checked === true, b?.checked === true);
        });

      document.getElementById("kiln-consent-reject")
        ?.addEventListener("click", () => write(false, false));
    })();
  </script>
)}

<style>
  .cookie-banner {
    position: fixed;
    inset-inline: 0;
    bottom: 0;
    z-index: 50;
    border-top: 1px solid var(--border);
    background: rgba(15, 15, 15, 0.96);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    padding: 20px 24px;
    box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.4);
    color: var(--text);
    font-size: 14px;
    line-height: 1.5;
  }
  .inner {
    margin: 0 auto;
    max-width: 880px;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  .copy {
    margin: 0;
    color: var(--text-muted);
  }
  .copy a {
    color: var(--accent);
    text-decoration: underline;
    text-underline-offset: 2px;
  }
  .copy a:hover {
    color: var(--accent-hover);
  }
  .checkboxes {
    display: flex;
    flex-wrap: wrap;
    gap: 18px;
    align-items: center;
  }
  .checkboxes label {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--text);
    cursor: pointer;
  }
  .checkboxes input[type="checkbox"] {
    width: 16px;
    height: 16px;
    accent-color: var(--accent);
    cursor: pointer;
  }
  .checkboxes input[type="checkbox"]:disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
  .buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  .buttons button {
    font: inherit;
    padding: 9px 16px;
    border-radius: 6px;
    cursor: pointer;
    border: 1px solid transparent;
    transition: background .12s ease, border-color .12s ease, color .12s ease;
  }
  .buttons .primary {
    background: var(--accent);
    color: #0F0F0F;
    font-weight: 600;
  }
  .buttons .primary:hover {
    background: var(--accent-hover);
  }
  .buttons .secondary,
  .buttons .tertiary {
    background: transparent;
    border-color: var(--border);
    color: var(--text);
  }
  .buttons .secondary:hover,
  .buttons .tertiary:hover {
    border-color: var(--text-muted);
    background: var(--bg-card);
  }
  .buttons .tertiary {
    color: var(--text-muted);
  }

  @media (max-width: 640px) {
    .cookie-banner {
      padding: 16px 18px;
    }
    .checkboxes {
      gap: 12px;
    }
  }
</style>
