// main.el - Neuron landing page server.
//
// Serves the Neuron marketing landing page at port 3001.
// Written in El (the Engram language). Runs on the El VM (elvm).
//
// The El HTTP server intercepts GET / and serves __html_file__ directly.
// We generate the page at startup with El components, write it to
// src/index.html, and set __html_file__ to that path.
//
// This means the document is always El-generated - never hand-authored.
// The El runtime serves it with the correct Content-Type: text/html header.
//
// Execution:
//   el run   (builds + executes via the El VM)
//
// Routes:
//   GET /                    → landing page (El-rendered, served by runtime)
//   GET /api/health          → {"status":"ok"}
//   GET /api/founding-count  → {"remaining":N,"sold":N,"total":N}
//   GET /assets/*            → static assets (served by runtime from src/assets/)
//   GET /brand/*             → brand assets via handle_request
//   GET *                    → 404 JSON (non-/ paths not used by this SPA)

from nav              import { nav }
from hero             import { hero }
from pillars          import { pillars }
from how_it_works     import { how_it_works }
from inference        import { inference }
from efficiency       import { efficiency }
from comparison       import { comparison }
from environmental    import { environmental }
from enterprise       import { enterprise }
from mission          import { mission }
from local_first      import { local_first }
from pricing          import { pricing }
from marketplace      import { marketplace }
from viral            import { viral }
from footer           import { footer }
from styles           import { page_open, page_close }
from about            import { about_page }
from founding_badge   import { founding_badge, founding_badge_css }
from terms            import { terms_page }
from enterprise_terms import { enterprise_terms_page }
from checkout        import { checkout_page }
from safety          import { safety }
from gallery         import { gallery_page }
from account         import { account_page }

// ── Founding counter ──────────────────────────────────────────────────────────

let FOUNDING_TOTAL: Int = 1000
let FOUNDING_SOLD:  Int = 0   // no artificial floor - real count comes from Stripe

// ── Founding count helpers ─────────────────────────────────────────────────────

fn get_sold() -> Int {
    let s: String = state_get("__founding_sold__")
    if str_eq(s, "") {
        return FOUNDING_SOLD
    }
    return str_to_int(s)
}

fn get_total() -> Int {
    let s: String = state_get("__founding_total__")
    if str_eq(s, "") {
        return FOUNDING_TOTAL
    }
    return str_to_int(s)
}

// fetch_founding_count_stripe — queries Stripe PaymentIntents search for the
// real founding count. Uses the secret key with Bearer auth. Falls back to the
// FOUNDING_SOLD floor if Stripe is unavailable or not yet configured.
fn fetch_founding_count_stripe(stripe_key: String) -> Int {
    if str_eq(stripe_key, "") {
        return FOUNDING_SOLD
    }
    let count: Int = 0

    // 1) PaymentIntents (Stripe Elements path - this is what the live site uses)
    let pi_url:  String = "https://api.stripe.com/v1/payment_intents?limit=100"
    let pi_resp: String = http_get_auth(pi_url, stripe_key)
    let pi_data: String = if str_eq(pi_resp, "") { "" } else { json_get_raw(pi_resp, "data") }
    if !str_eq(pi_data, "") {
        let pi_total: Int = json_array_len(pi_data)
        let pi_idx:   Int = 0
        while pi_idx < pi_total {
            let pi: String = json_array_get(pi_data, pi_idx)
            let status: String = json_get(pi, "status")
            let metadata: String = json_get_raw(pi, "metadata")
            let plan: String = if str_eq(metadata, "") { "" } else { json_get(metadata, "plan") }
            // Count only fully-charged founding PIs that are not refunded
            let amt_refunded: String = json_get(pi, "amount_refunded")
            let refunded_n: Int = str_to_int(amt_refunded)
            if str_eq(status, "succeeded") && str_eq(plan, "founding") && refunded_n <= 0 {
                let count = count + 1
            }
            let pi_idx = pi_idx + 1
        }
    }

    // 2) Hosted Checkout Sessions (legacy /api/checkout path - kept for completeness)
    let cs_url:  String = "https://api.stripe.com/v1/checkout/sessions?status=complete&limit=100"
    let cs_resp: String = http_get_auth(cs_url, stripe_key)
    let cs_data: String = if str_eq(cs_resp, "") { "" } else { json_get_raw(cs_resp, "data") }
    if !str_eq(cs_data, "") {
        let cs_total: Int = json_array_len(cs_data)
        let cs_idx:   Int = 0
        while cs_idx < cs_total {
            let session: String = json_array_get(cs_data, cs_idx)
            let metadata: String = json_get_raw(session, "metadata")
            let plan: String = if str_eq(metadata, "") { "" } else { json_get(metadata, "plan") }
            if str_eq(plan, "founding") {
                let count = count + 1
            }
            let cs_idx = cs_idx + 1
        }
    }

    return count
}

// load_founding_count — reads from persist file first (survives restarts),
// falls back to Stripe query if file doesn't exist yet.
fn load_founding_count(sold_file: String, stripe_key: String) -> Int {
    if fs_exists(sold_file) {
        let s: String = str_trim(fs_read(sold_file))
        let n: Int = str_to_int(s)
        if n > 0 {
            return n
        }
    }
    return fetch_founding_count_stripe(stripe_key)
}

// persist_founding_count — writes current sold count to disk so it survives
// server restarts. Called at startup and on every Stripe webhook increment.
fn persist_founding_count(sold: Int) {
    let sold_file: String = state_get("__founding_sold_file__")
    if !str_eq(sold_file, "") {
        fs_write(sold_file, int_to_str(sold))
    }
}

// ── Page assembly ─────────────────────────────────────────────────────────────

fn page(sold: Int, total: Int) -> String {
    return page_open()
        + nav()
        + hero()
        + pillars()
        + how_it_works()
        + inference()
        + efficiency()
        + comparison()
        + enterprise()
        + mission()
        + local_first()
        + safety()
        + environmental()
        + pricing(sold, total)
        + marketplace()
        + viral()
        + footer()
        + page_close()
}

// ── Share card page ───────────────────────────────────────────────────────────

fn share_card_page(question: String, answer: String, id: String) -> String {
    let q_html: String = str_replace(str_replace(str_replace(question, "&", "&amp;"), "<", "&lt;"), ">", "&gt;")
    let a_html: String = str_replace(str_replace(str_replace(answer, "&", "&amp;"), "<", "&lt;"), ">", "&gt;")
    let og_desc: String = str_slice(answer, 0, 140)
    let base_url: String = state_get("__neuron_origin__")
    let card_url: String = base_url + "/share/" + id
    // Pre-built share hrefs — ID is digits so no URL encoding needed
    let share_text: String = "The+AI+that+remembers+you+%E2%80%94+things+it+said%3A"
    let x_href: String = "https://twitter.com/intent/tweet?url=" + card_url + "&text=" + share_text
    let li_href: String = "https://www.linkedin.com/sharing/share-offsite/?url=" + card_url
    let fb_href: String = "https://www.facebook.com/sharer/sharer.php?u=" + card_url
    let wa_href: String = "https://wa.me/?text=" + share_text + "%20" + card_url
    // TikTok and Snapchat have no web URL share scheme — use clipboard copy
    let tiktok_copy_text: String = "Copied+%E2%80%94+paste+into+TikTok"
    let snap_copy_text: String = "Copied+%E2%80%94+paste+into+Snapchat"
    return "<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">
<title>Things Neuron Said</title>
<meta property=\"og:title\" content=\"Things Neuron Said\">
<meta property=\"og:description\" content=\"" + og_desc + "\">
<meta property=\"og:image\" content=\"https://neurontechnologies.ai/assets/brand/neuron-wordmark-on-light@2x.png\">
<meta property=\"og:type\" content=\"website\">
<meta property=\"og:url\" content=\"" + card_url + "\">
<meta name=\"twitter:card\" content=\"summary_large_image\">
<meta name=\"twitter:title\" content=\"Things Neuron Said\">
<meta name=\"twitter:description\" content=\"" + og_desc + "\">
<meta name=\"twitter:image\" content=\"https://neurontechnologies.ai/assets/brand/neuron-wordmark-on-light@2x.png\">
<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">
<link href=\"https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600&display=swap\" rel=\"stylesheet\">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--navy:#0052A0;--navy-dark:#003d7a;--t1:#0D0D14;--t2:#3A3A4A;--t3:#6B6B7E;--bg:#FAFAF8}
body{font-family:'IBM Plex Sans',system-ui,sans-serif;background:var(--bg);color:var(--t1);min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:2rem 1rem}
body::before{content:'';position:fixed;inset:0;pointer-events:none;z-index:0;background-image:linear-gradient(rgba(0,0,0,.018) 1px,transparent 1px),linear-gradient(90deg,rgba(0,0,0,.018) 1px,transparent 1px);background-size:48px 48px}
.page{width:100%;max-width:580px;display:flex;flex-direction:column;gap:1.75rem;position:relative;z-index:1}
.page-header{display:flex;align-items:center;justify-content:space-between;gap:1rem}
.wordmark img{height:22px;width:auto;display:block}
.eyebrow{font-size:.65rem;font-weight:400;letter-spacing:.16em;text-transform:uppercase;color:var(--t3)}
.chat-frame{background:#fff;border:1px solid rgba(0,0,0,.09);box-shadow:0 4px 32px rgba(0,0,0,.07),0 1px 4px rgba(0,0,0,.04);padding:1.5rem;display:flex;flex-direction:column;gap:1rem}
.chat-row-user{display:flex;flex-direction:row-reverse}
.chat-row-ai{display:flex;flex-direction:row;align-items:flex-end;gap:.625rem}
.bubble-user{background:#0052A0;color:#fff;border-radius:18px 18px 4px 18px;padding:11px 15px;max-width:78%;font-size:.875rem;line-height:1.55;word-break:break-word}
.bubble-ai{background:var(--bg);color:var(--t1);border:1px solid rgba(0,0,0,.07);border-radius:18px 18px 18px 4px;padding:11px 15px;max-width:88%;font-size:.875rem;font-weight:300;line-height:1.65;word-break:break-word;white-space:pre-wrap;box-shadow:0 2px 6px rgba(0,0,0,.05)}
.ai-col{display:flex;flex-direction:column;gap:.25rem}
.ai-label{font-size:.6rem;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--navy)}
.avatar{width:26px;height:26px;border-radius:50%;flex-shrink:0;background:#fff;border:1px solid rgba(0,82,160,.15);display:flex;align-items:center;justify-content:center}
.avatar img{width:14px;height:14px;object-fit:contain}
.vote-row{display:flex;align-items:center;gap:.75rem}
.vote-label{font-size:.65rem;font-weight:400;letter-spacing:.12em;text-transform:uppercase;color:var(--t3)}
.vote-btn{background:none;border:1px solid rgba(0,0,0,.12);cursor:pointer;padding:.3rem .6rem;font-size:.8rem;color:var(--t2);transition:all .15s;line-height:1}
.vote-btn:hover{border-color:var(--navy);color:var(--navy)}
.vote-btn.voted-up{background:var(--navy);color:#fff;border-color:var(--navy)}
.vote-btn.voted-down{background:#f0f0ec;color:var(--t3);border-color:rgba(0,0,0,.12)}
.vote-count{font-size:.8rem;font-weight:500;color:var(--t1);min-width:1.5rem;text-align:center}
.share-section{display:flex;flex-direction:column;gap:.625rem}
.share-label{font-size:.65rem;font-weight:500;letter-spacing:.12em;text-transform:uppercase;color:var(--t3)}
.share-row{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}
.share-btn{display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border-radius:50%;border:none;text-decoration:none;cursor:pointer;transition:opacity .15s,transform .15s;flex-shrink:0}
.share-btn:hover{opacity:.85;transform:scale(1.08)}
.share-btn.copied{outline:2px solid var(--navy)}
.divider{height:1px;background:rgba(0,0,0,.07)}
.footer-row{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap}
.footer-note{font-size:.75rem;color:var(--t3)}
.cta-btn{display:inline-flex;align-items:center;gap:.5rem;background:var(--navy);color:#fff;text-decoration:none;font-size:.7rem;font-weight:500;letter-spacing:.14em;text-transform:uppercase;padding:.7rem 1.4rem;white-space:nowrap;transition:background .15s}
.cta-btn:hover{background:var(--navy-dark)}
@media(max-width:480px){.chat-frame{padding:1.25rem}.footer-row{flex-direction:column;align-items:flex-start}}
</style>
</head>
<body>
<div class=\"page\">
  <div class=\"page-header\">
    <a href=\"https://neurontechnologies.ai\" class=\"wordmark\">
      <img src=\"/assets/brand/neuron-wordmark-on-light.png\"
           srcset=\"/assets/brand/neuron-wordmark-on-light@2x.png 2x\"
           alt=\"Neuron\" height=\"22\">
    </a>
    <span class=\"eyebrow\">Things Neuron Said</span>
  </div>

  <div class=\"chat-frame\">
    <div class=\"chat-row-user\">
      <div class=\"bubble-user\">" + q_html + "</div>
    </div>
    <div class=\"chat-row-ai\">
      <div class=\"avatar\"><img src=\"/assets/neuron-icon.png\" alt=\"\"></div>
      <div class=\"ai-col\">
        <span class=\"ai-label\">Neuron</span>
        <div class=\"bubble-ai\">" + a_html + "</div>
      </div>
    </div>
  </div>

  <div class=\"vote-row\">
    <span class=\"vote-label\">Helpful?</span>
    <button class=\"vote-btn\" id=\"vote-up\">&#9650;</button>
    <span class=\"vote-count\" id=\"vote-score\">0</span>
    <button class=\"vote-btn\" id=\"vote-down\">&#9660;</button>
  </div>

  <div class=\"share-section\">
    <span class=\"share-label\">Share</span>
    <div class=\"share-row\">
      <a href=\"" + x_href + "\" target=\"_blank\" rel=\"noopener\" class=\"share-btn\" title=\"Post on X\" style=\"background:#000\">
        <img src=\"https://cdn.simpleicons.org/x/ffffff\" width=\"18\" height=\"18\" alt=\"X\">
      </a>
      <a href=\"" + li_href + "\" target=\"_blank\" rel=\"noopener\" class=\"share-btn\" title=\"Share on LinkedIn\" style=\"background:#0A66C2\">
        <img src=\"https://cdn.simpleicons.org/linkedin/ffffff\" width=\"18\" height=\"18\" alt=\"LinkedIn\">
      </a>
      <a href=\"" + fb_href + "\" target=\"_blank\" rel=\"noopener\" class=\"share-btn\" title=\"Share on Facebook\" style=\"background:#1877F2\">
        <img src=\"https://cdn.simpleicons.org/facebook/ffffff\" width=\"18\" height=\"18\" alt=\"Facebook\">
      </a>
      <a href=\"" + wa_href + "\" target=\"_blank\" rel=\"noopener\" class=\"share-btn\" title=\"Send via WhatsApp\" style=\"background:#25D366\">
        <img src=\"https://cdn.simpleicons.org/whatsapp/ffffff\" width=\"18\" height=\"18\" alt=\"WhatsApp\">
      </a>
      <button class=\"share-btn\" id=\"copy-tiktok\" onclick=\"copyForPlatform('tiktok', this)\" title=\"Copy for TikTok\" style=\"background:#010101;border:none\">
        <img src=\"https://cdn.simpleicons.org/tiktok/ffffff\" width=\"18\" height=\"18\" alt=\"TikTok\">
      </button>
      <button class=\"share-btn\" id=\"copy-snapchat\" onclick=\"copyForPlatform('snapchat', this)\" title=\"Copy for Snapchat\" style=\"background:#FFFC00;border:none\">
        <img src=\"https://cdn.simpleicons.org/snapchat/000000\" width=\"18\" height=\"18\" alt=\"Snapchat\">
      </button>
    </div>
  </div>

  <div class=\"divider\"></div>

  <div class=\"footer-row\">
    <span class=\"footer-note\">From a live conversation with Neuron.</span>
    <a href=\"https://neurontechnologies.ai\" class=\"cta-btn\">Try Neuron &#8599;</a>
  </div>
</div>
<script>window.NEURON_CFG=window.NEURON_CFG||{};window.NEURON_CFG.id=\"" + id + "\";window.NEURON_CFG.card_url=\"" + card_url + "\";</script><script src=\"/assets/js/94727a87c328.js\" defer></script>
</body>
</html>"
}

// ── Static asset serving ──────────────────────────────────────────────────────

// waitlist_upsert — writes a row to the Supabase waitlist table.
// member_num: pass 0 to omit, positive for founding member number.
fn waitlist_upsert(email: String, name: String, plan: String, source: String, attestation: String, user_agent: String, member_num: Int) {
    let sb_url: String = state_get("__supabase_project_url__")
    let sb_key: String = state_get("__supabase_service_key__")
    if str_eq(sb_key, "") {
        println("[waitlist] no service key — skipping Supabase write")
        return ""
    }
    let e_safe:  String = str_replace(str_replace(email,       "\\", "\\\\"), "\"", "\\\"")
    let n_safe:  String = str_replace(str_replace(name,        "\\", "\\\\"), "\"", "\\\"")
    let a_safe:  String = str_replace(str_replace(attestation, "\\", "\\\\"), "\"", "\\\"")
    let ua_safe: String = str_replace(str_replace(user_agent,  "\\", "\\\\"), "\"", "\\\"")
    let num_field: String = if member_num > 0 { ",\"member_number\":" + int_to_str(member_num) } else { "" }
    let row: String = "{\"email\":\"" + e_safe + "\",\"name\":\"" + n_safe + "\",\"plan\":\"" + plan + "\",\"source\":\"" + source + "\",\"attestation\":\"" + a_safe + "\",\"user_agent\":\"" + ua_safe + "\"" + num_field + "}"
    let resp: String = supabase_insert(sb_url, sb_key, "waitlist", row)
    println("[waitlist] supabase insert -> " + resp)
    return ""
}

fn read_asset(abs_path: String) -> String {
    let exists: Bool = fs_exists(abs_path)
    if !exists {
        return ""
    }
    return fs_read(abs_path)
}

// ── Request handler ───────────────────────────────────────────────────────────
//
// NOTE: GET / is intercepted by the El HTTP runtime before reaching this
// function - it serves __html_file__ directly with text/html.
// This handler covers /api/* and /brand/* routes.

fn handle_request(method: String, path: String, body: String) -> String {
    let src_dir: String = state_get("__src_dir__")

    // ── Root — serve El-generated landing page ────────────────────────────────
    if str_eq(path, "/") {
        let index_path: String = state_get("__html_file__")
        if !str_eq(index_path, "") {
            return fs_read(index_path)
        }
    }

    // ── llms.txt — for AI crawlers (Perplexity, ChatGPT, Google SGE) ─────────
    if str_eq(path, "/llms.txt") {
        return fs_read(src_dir + "/llms.txt")
    }

    // ── robots.txt ────────────────────────────────────────────────────────────
    if str_eq(path, "/robots.txt") {
        return "User-agent: *\nAllow: /\nSitemap: https://neurontechnologies.ai/sitemap.xml\n"
    }

    // ── About page ────────────────────────────────────────────────────────────
    if str_eq(path, "/about") {
        let about_path: String = state_get("__about_html_file__")
        if !str_eq(about_path, "") {
            return fs_read(about_path)
        }
        return "{\"__status__\":404,\"error\":\"not found\"}"
    }

    // ── Terms of Service ──────────────────────────────────────────────────────
    if str_eq(path, "/legal/terms") {
        let terms_path: String = state_get("__terms_html_file__")
        if !str_eq(terms_path, "") {
            return fs_read(terms_path)
        }
        return "{\"__status__\":404,\"error\":\"not found\"}"
    }

    // ── Enterprise Agreement ──────────────────────────────────────────────────
    if str_eq(path, "/legal/enterprise-terms") {
        let ent_path: String = state_get("__enterprise_terms_html_file__")
        if !str_eq(ent_path, "") {
            return fs_read(ent_path)
        }
        return "{\"__status__\":404,\"error\":\"not found\"}"
    }

    // ── Checkout page ─────────────────────────────────────────────────────────
    if str_starts_with(path, "/checkout") {
        let plan: String = "founding"
        if str_contains(path, "plan=professional") {
            plan = "professional"
        }
        if str_contains(path, "plan=free") {
            plan = "free"
        }
        let pub_key: String = state_get("__stripe_publishable_key__")
        return page_open() + checkout_page(plan, pub_key) + page_close()
    }

    // ── Stripe payment intent ─────────────────────────────────────────────────
    if str_eq(path, "/api/payment-intent") {
        let stripe_key: String = state_get("__stripe_secret_key__")
        if str_eq(stripe_key, "") {
            return "{\"__status__\":503,\"error\":\"Stripe not configured\"}"
        }
        let plan: String = "founding"
        if str_contains(body, "\"professional\"") {
            plan = "professional"
        }
        // Hard cap: block founding checkouts when 1,000 spots are filled
        if str_eq(plan, "founding") {
            let current_sold: Int = get_sold()
            let total_spots: Int = get_total()
            if current_sold >= total_spots {
                return "{\"__status__\":410,\"error\":\"sold_out\",\"message\":\"All 1,000 Founding Member spots have been claimed.\"}"
            }
        }
        let amount: String = "19900"
        if str_eq(plan, "professional") {
            amount = "1900"
        }
        let pi_body: String = "amount=" + amount
            + "&currency=usd"
            + "&automatic_payment_methods[enabled]=true"
            + "&metadata[plan]=" + plan
        let auth_header: String = "Bearer " + stripe_key
        let response: String = http_post_form_auth(
            "https://api.stripe.com/v1/payment_intents",
            pi_body,
            auth_header
        )
        return response
    }

    // ── Link Stripe Customer to PaymentIntent + Supabase waitlist row ────────
    // Called from checkout.js right before stripe.confirmPayment. Three jobs:
    //   1. Find or create a Stripe Customer for this email (so they aren't a Guest)
    //   2. Attach the Customer to the live PaymentIntent
    //   3. Stamp stripe_customer_id + plan on the Supabase waitlist row (upsert by email)
    // Non-fatal: if any step errors, we still return 200 so the buyer can complete
    // payment. The Stripe webhook ( /api/webhooks/stripe ) re-links server-side on
    // payment_intent.succeeded as a backstop.
    if str_eq(path, "/api/link-customer") {
        let stripe_key: String = state_get("__stripe_secret_key__")
        if str_eq(stripe_key, "") {
            return "{\"linked\":false,\"error\":\"stripe_not_configured\"}"
        }
        let lc_pi_id: String  = json_get_string(body, "pi_id")
        let lc_email: String  = json_get_string(body, "email")
        let lc_name:  String  = json_get_string(body, "name")
        let lc_plan:  String  = json_get_string(body, "plan")
        if str_eq(lc_pi_id, "") || str_eq(lc_email, "") {
            return "{\"linked\":false,\"error\":\"missing_pi_or_email\"}"
        }
        let lc_auth: String = "Bearer " + stripe_key
        // URL-encode email so + and @ survive the form-body
        let lc_email_enc: String = str_replace(str_replace(lc_email, "@", "%40"), "+", "%2B")
        let lc_name_enc:  String = str_replace(lc_name, " ", "%20")

        // 1. Search existing customers by email
        let lc_search_url: String = "https://api.stripe.com/v1/customers/search?query=email%3A%22" + lc_email_enc + "%22&limit=1"
        let lc_search:     String = http_get_auth(lc_search_url, lc_auth)
        let lc_cus_id:     String = json_get_string(lc_search, "id")

        // 2. If none, create one
        if str_eq(lc_cus_id, "") {
            let lc_create_body: String = "email=" + lc_email_enc + "&name=" + lc_name_enc + "&metadata[plan]=" + lc_plan
            let lc_create:      String = http_post_form_auth("https://api.stripe.com/v1/customers", lc_create_body, lc_auth)
            let lc_cus_id = json_get_string(lc_create, "id")
        }

        // 3. Attach customer + receipt_email to the PaymentIntent
        if !str_eq(lc_cus_id, "") {
            let lc_attach_body: String = "customer=" + lc_cus_id + "&receipt_email=" + lc_email_enc
            let lc_attach_url:  String = "https://api.stripe.com/v1/payment_intents/" + lc_pi_id
            let lc_attach:      String = http_post_form_auth(lc_attach_url, lc_attach_body, lc_auth)
        }

        // 4. Upsert the Supabase waitlist row so /account can find this purchase by email
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_key: String = state_get("__supabase_service_key__")
        if !str_eq(sb_url, "") && !str_eq(sb_key, "") && !str_eq(lc_cus_id, "") {
            let lc_row: String = "{\"email\":\"" + lc_email + "\",\"name\":\"" + lc_name + "\",\"stripe_customer_id\":\"" + lc_cus_id + "\",\"plan\":\"" + lc_plan + "\"}"
            let _wl_resp: String = supabase_insert(sb_url, sb_key, "waitlist?on_conflict=email", lc_row)
        }

        return "{\"linked\":true,\"customer_id\":\"" + lc_cus_id + "\"}"
    }

    // ── Health check ──────────────────────────────────────────────────────────
    if str_eq(path, "/api/health") {
        return "{\"status\":\"ok\",\"service\":\"neuron-web\"}"
    }

    // ── My plan: server-side waitlist read with JWT verification ─────────────
    // POST { "access_token": "<user_jwt>" }. We verify the JWT via Supabase
    // /auth/v1/user, extract the email, then read the waitlist row with the
    // SERVICE key (bypasses RLS). Canonical plan source for /account.
    if str_eq(path, "/api/my-plan") {
        let mp_jwt: String = json_get_string(body, "access_token")
        if str_eq(mp_jwt, "") {
            return "{\"__status__\":401,\"error\":\"missing_jwt\"}"
        }
        let mp_sb_url:  String = state_get("__supabase_project_url__")
        let mp_anon:    String = state_get("__supabase_anon_key__")
        let mp_service: String = state_get("__supabase_service_key__")
        if str_eq(mp_sb_url, "") || str_eq(mp_anon, "") || str_eq(mp_service, "") {
            return "{\"__status__\":503,\"error\":\"supabase_not_configured\"}"
        }
        let mp_user: String = supabase_auth_user(mp_sb_url, mp_anon, mp_jwt)
        let mp_email: String = json_get(mp_user, "email")
        if str_eq(mp_email, "") {
            return "{\"__status__\":401,\"error\":\"invalid_jwt\"}"
        }
        let mp_email_safe: String = str_replace(str_replace(mp_email, "@", "%40"), "+", "%2B")
        let mp_query: String = "waitlist?select=plan,member_number,source,created_at,stripe_customer_id,name&email=eq." + mp_email_safe + "&order=created_at.desc&limit=1"
        let mp_resp: String = supabase_get(mp_sb_url, mp_service, mp_query)
        if str_eq(mp_resp, "") || str_eq(mp_resp, "[]") {
            return "{\"plan\":null,\"email\":\"" + mp_email + "\"}"
        }
        // Strip outer array brackets to return a plain object
        if str_starts_with(mp_resp, "[") {
            let mp_inner: String = str_slice(mp_resp, 1, str_len(mp_resp) - 1)
            return mp_inner
        }
        return mp_resp
    }


    // ── Founding count ────────────────────────────────────────────────────────
    if str_eq(path, "/api/founding-count") {
        // Query Stripe live so counter always reflects real purchases
        let stripe_key: String = state_get("__stripe_secret_key__")
        let live_sold: Int = fetch_founding_count_stripe(stripe_key)
        if live_sold > get_sold() {
            state_set("__founding_sold__", int_to_str(live_sold))
            persist_founding_count(live_sold)
        }
        let sold:      Int    = get_sold()
        let total:     Int    = get_total()
        let remaining: Int    = total - sold
        let sold_s:    String = int_to_str(sold)
        let total_s:   String = int_to_str(total)
        let rem_s:     String = int_to_str(remaining)
        return "{\"sold\":" + sold_s + ",\"total\":" + total_s + ",\"remaining\":" + rem_s + "}"
    }

    // ── Static assets: /assets/* ──────────────────────────────────────────────
    if str_starts_with(path, "/assets/") {
        let rel: String = str_slice(path, 8, str_len(path))
        let abs: String = src_dir + "/assets/" + rel
        let content: String = read_asset(abs)
        if str_eq(content, "") {
            return "{\"__status__\":404,\"error\":\"not found\"}"
        }
        return content
    }

    // ── Brand assets: /brand/* ────────────────────────────────────────────────
    if str_starts_with(path, "/brand/") {
        let rel: String = str_slice(path, 7, str_len(path))
        let abs: String = src_dir + "/brand/" + rel
        let content: String = read_asset(abs)
        if str_eq(content, "") {
            return "{\"__status__\":404,\"error\":\"not found\"}"
        }
        return content
    }

    // ── Stripe checkout ───────────────────────────────────────────────────────
    if str_eq(path, "/api/checkout") {
        let stripe_key: String = state_get("__stripe_secret_key__")
        if str_eq(stripe_key, "") {
            return "{\"__status__\":503,\"error\":\"Stripe not configured\"}"
        }
        let plan: String = "founding"
        if str_contains(body, "\"professional\"") {
            plan = "professional"
        }
        let origin: String = state_get("__origin__")
        let price_id: String = ""
        let mode: String = "subscription"
        if str_eq(plan, "founding") {
            price_id = state_get("__stripe_price_founding__")
            mode = "payment"
        }
        if str_eq(plan, "professional") {
            price_id = state_get("__stripe_price_professional__")
            mode = "subscription"
        }
        if str_eq(price_id, "") {
            return "{\"__status__\":503,\"error\":\"Plan price not configured\"}"
        }
        let form_body: String = "mode=" + mode
            + "&line_items[0][price]=" + price_id
            + "&line_items[0][quantity]=1"
            + "&success_url=" + origin + "/marketplace/success?session_id={CHECKOUT_SESSION_ID}"
            + "&cancel_url=" + origin + "/#pricing"
            + "&allow_promotion_codes=true"
            + "&metadata[plan]=" + plan
        let auth_hdr: String = "Bearer " + stripe_key
        let response: String = http_post_form_auth(
            "https://api.stripe.com/v1/checkout/sessions",
            form_body,
            auth_hdr
        )
        if str_contains(response, "\"url\"") {
            return response
        }
        return "{\"__status__\":500,\"error\":\"Stripe session creation failed\"}"
    }

    // ── Enterprise inquiry ────────────────────────────────────────────────────
    if str_eq(path, "/api/enterprise-inquiry") {
        let resend_key: String = state_get("__resend_api_key__")
        let name_val: String = if str_contains(body, "\"name\"") { "submitted" } else { "" }
        if str_eq(name_val, "") {
            return "{\"error\":\"invalid request\"}"
        }
        // Log to stdout regardless of email delivery
        println("[enterprise-inquiry] " + body)
        // Send via Resend if key is configured
        if !str_eq(resend_key, "") {
            let email_body: String = "{\"from\":\"Neuron Enterprise <enterprise@neurontechnologies.ai>\",\"to\":[\"enterprise@neurontechnologies.ai\"],\"subject\":\"Enterprise Inquiry\",\"text\":" + body + "}"
            let resp: String = http_post_auth(
                "https://api.resend.com/emails",
                resend_key,
                email_body
            )
            println("[enterprise-inquiry] resend: " + resp)
        }
        return "{\"received\":true}"
    }

    // ── Free tier waitlist ────────────────────────────────────────────────────
    if str_eq(path, "/api/waitlist") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let wl_email: String = json_get(body, "email")
        if str_eq(wl_email, "") {
            return "{\"error\":\"email required\"}"
        }
        // Write to Supabase waitlist table
        waitlist_upsert(wl_email, "", "free", "preorder", "", "", 0)
        // Email notification
        let e_safe: String = str_replace(str_replace(wl_email, "\\", "\\\\"), "\"", "\\\"")
        let resend_key: String = state_get("__resend_api_key__")
        if !str_eq(resend_key, "") {
            let email_body: String = "{\"from\":\"Neuron <no-reply@neurontechnologies.ai>\",\"to\":[\"will.anderson@neurontechnologies.ai\"],\"subject\":\"Free tier preorder: " + e_safe + "\",\"text\":\"New free tier preorder\\nEmail: " + e_safe + "\"}"
            let resp: String = http_post_auth("https://api.resend.com/emails", resend_key, email_body)
            println("[waitlist] email: " + resp)
        }
        return "{\"ok\":true}"
    }

    // ── Founding member attestation record ───────────────────────────────────
    // Fired from the checkout form just before Stripe confirmPayment().
    // Saves to GCS (attestations/<ts>-founding-<email>.json) and emails Will.
    if str_eq(path, "/api/attest") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let attest_name:  String = json_get(body, "name")
        let attest_email: String = json_get(body, "email")
        let attest_plan:  String = json_get(body, "plan")
        let attest_ts:    String = json_get(body, "timestamp")
        let attest_text:  String = json_get(body, "attestation")
        let attest_ua:    String = json_get(body, "user_agent")
        if str_eq(attest_email, "") {
            return "{\"error\":\"email required\"}"
        }
        let n_safe: String = str_replace(str_replace(attest_name, "\\", "\\\\"), "\"", "\\\"")
        let e_safe: String = str_replace(str_replace(attest_email, "\\", "\\\\"), "\"", "\\\"")
        let t_safe: String = str_replace(str_replace(attest_text, "\\", "\\\\"), "\"", "\\\"")
        let ua_safe: String = str_replace(str_replace(attest_ua, "\\", "\\\\"), "\"", "\\\"")
        // Write to Supabase waitlist (attestation in dedicated column)
        waitlist_upsert(attest_email, attest_name, attest_plan, "founding-attestation", attest_text, attest_ua, 0)
        // Also save to GCS as immutable legal record
        let record: String = "{\"plan\":\"" + attest_plan + "\",\"name\":\"" + n_safe + "\",\"email\":\"" + e_safe + "\",\"timestamp\":\"" + attest_ts + "\",\"attestation\":\"" + t_safe + "\",\"user_agent\":\"" + ua_safe + "\"}"
        let gcs_bucket: String = env("GCS_SHARE_BUCKET")
        if !str_eq(gcs_bucket, "") {
            let attest_key: String = "attestations/" + attest_ts + "-" + attest_email + ".json"
            let gcs_ok: String = gcs_write(gcs_bucket, attest_key, record)
            println("[attest] gcs write " + attest_key + " -> " + gcs_ok)
        }
        // Email notification
        let resend_key: String = state_get("__resend_api_key__")
        if !str_eq(resend_key, "") {
            let subject: String = "Founding member attestation: " + attest_name + " <" + attest_email + ">"
            let email_body: String = "{\"from\":\"Neuron <no-reply@neurontechnologies.ai>\",\"to\":[\"will.anderson@neurontechnologies.ai\"],\"subject\":\"" + str_replace(subject, "\"", "\\\"") + "\",\"text\":\"Plan: " + attest_plan + "\\nName: " + n_safe + "\\nEmail: " + e_safe + "\\nTime: " + attest_ts + "\\n\\nAttestation: " + t_safe + "\"}"
            let resp: String = http_post_auth("https://api.resend.com/emails", resend_key, email_body)
            println("[attest] email: " + resp)
        }
        return "{\"ok\":true}"
    }

    // ── Developer interest form ───────────────────────────────────────────────
    if str_eq(path, "/api/developer-interest") {
        let resend_key: String = state_get("__resend_api_key__")
        if !str_contains(body, "\"email\"") {
            return "{\"error\":\"invalid request\"}"
        }
        // Write to Supabase waitlist
        let dev_email: String = json_get(body, "email")
        let dev_name: String = json_get(body, "name")
        let dev_idea: String = json_get(body, "idea")
        waitlist_upsert(dev_email, dev_name, "developer", "developer-interest", dev_idea, "", 0)
        println("[developer-interest] " + body)
        if !str_eq(resend_key, "") {
            let email_body: String = "{\"from\":\"Neuron Developer Program <developers@neurontechnologies.ai>\",\"to\":[\"will.anderson@neurontechnologies.ai\"],\"subject\":\"Developer Interest\",\"text\":" + body + "}"
            let resp: String = http_post_auth(
                "https://api.resend.com/emails",
                resend_key,
                email_body
            )
            println("[developer-interest] resend: " + resp)
        }
        return "{\"received\":true}"
    }

    // ── Supabase public config ────────────────────────────────────────────────
    if str_eq(path, "/api/supabase-config") {
        let proj_url: String = "https://ocojsghaonltunidkzpw.supabase.co"
        let anon_key: String = state_get("__supabase_anon_key__")
        return "{\"url\":\"" + proj_url + "\",\"anon_key\":\"" + anon_key + "\"}"
    }

    // ── Demo chat — proxies to the demo soul at 7772 ─────────────────────────
    if str_eq(path, "/api/demo") {
        if str_eq(method, "POST") {
            let msg: String = json_get(body, "message")
            if str_eq(msg, "") {
                return "{\"error\":\"message required\"}"
            }
            // Rate limit: 25 requests per uid per hour (stored in process state)
            let rate_uid: String = json_get(body, "uid")
            if !str_eq(rate_uid, "") {
                let rate_key: String = "__rate__" + rate_uid
                let rate_val: String = state_get(rate_key)
                let rate_count: Int = if str_eq(rate_val, "") { 0 } else { str_to_int(rate_val) }
                if rate_count >= 25 {
                    return "{\"response\":\"You've hit the rate limit. Come back in an hour.\"}"
                }
                state_set(rate_key, int_to_str(rate_count + 1))
            }
            // Turnstile: verify on first message only (tokens are single-use).
            // Per-message verification breaks chat flow. Forms get full verification.
            let cf_token: String = json_get(body, "cf_token")
            if !str_eq(cf_token, "") {
                let ts_secret: String = "0x4AAAAAADHAZTok46L-l2sa9biSGpgN3GY"
                let verify_body: String = "secret=" + ts_secret + "&response=" + cf_token
                let verify_resp: String = http_post("https://challenges.cloudflare.com/turnstile/v0/siteverify", verify_body)
                let is_valid: String = json_get(verify_resp, "success")
                if str_eq(is_valid, "false") {
                    return "{\"error\":\"Bot check failed. Please try again.\"}"
                }
            }
            // Per-user channel ID — prevents conversation bleed between users
            let uid: String = json_get(body, "uid")
            let channel: String = if str_eq(uid, "") { "ntn-demo" } else { "ntn-demo-" + uid }
            // Escape the message for embedding in JSON strings
            let msg_safe: String = str_replace(str_replace(msg, "\\", "\\\\"), "\"", "\\\"")
            // Include conversation history so soul has full thread context
            // even after restarts. history is a JSON array of {role, content} from browser.
            let hist_raw: String = json_get_raw(body, "history")
            let hist_safe: String = if str_eq(hist_raw, "") { "[]" } else { hist_raw }
            // Include browser-local engram activation for this turn
            let an_raw: String = json_get_raw(body, "an")
            let ec_str: String = json_get(body, "ec")
            let an_safe: String = if str_eq(an_raw, "") { "[]" } else { an_raw }
            let ec_safe: String = if str_eq(ec_str, "") { "0" } else { ec_str }
            // Build inner content with history and engram context for thread context
            let inner: String = "{\"event_type\":\"chat\",\"payload\":{\"message\":\"" + msg_safe + "\",\"history\":" + hist_safe + ",\"an\":" + an_safe + ",\"ec\":" + ec_safe + "}}"
            // Escape inner for the outer content field
            let inner_safe: String = str_replace(str_replace(inner, "\\", "\\\\"), "\"", "\\\"")
            // Build dharma envelope with per-user channel
            let envelope: String = "{\"channel\":\"" + channel + "\",\"from\":\"ntn-site\",\"content\":\"" + inner_safe + "\"}"
            let soul_endpoint: String = state_get("__soul_url__") + "/dharma/recv"
            let resp: String = http_post(soul_endpoint, envelope)
            if str_eq(resp, "") {
                return "{\"response\":\"Stepped out for a moment. Try again.\"}"
            }
            // SECURITY: Strip internal fields before returning to browser.
            // activation_nodes and context_nodes expose the full knowledge graph —
            // internal architecture, roadmap, self-model, DHARMA details.
            // sn and se are safe: they are derived from
            // the user's own conversation and contain only content they already saw.
            let response_text: String = json_get(resp, "response")
            if str_eq(response_text, "") {
                let err: String = json_get(resp, "error")
                if !str_eq(err, "") {
                    return "{\"response\":\"Stepped out for a moment. Try again.\"}"
                }
                return "{\"response\":\"Stepped out for a moment. Try again.\"}"
            }
            let safe_text: String = str_replace(str_replace(str_replace(str_replace(response_text, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n"), "\r", "\\r")
            let model: String = json_get(resp, "model")
            let sn_raw: String = json_get_raw(resp, "sn")
            let se_raw: String = json_get_raw(resp, "se")
            let sn_safe: String = if str_eq(sn_raw, "") { "[]" } else { sn_raw }
            let se_safe: String = if str_eq(se_raw, "") { "[]" } else { se_raw }
            return "{\"response\":\"" + safe_text + "\",\"model\":\"" + model + "\",\"sn\":" + sn_safe + ",\"se\":" + se_safe + "}"
        }
        return "{\"error\":\"POST required\"}"
    }

    // ── Stripe webhook ────────────────────────────────────────────────────────
    if str_eq(path, "/api/webhooks/stripe") {
        if str_contains(body, "checkout.session.completed") {
            // Extract customer email from session
            let customer_email: String = json_get(body, "customer_details.email")
            let customer_name: String = json_get(body, "customer_details.name")
            let customer_id: String = json_get(body, "customer")
            // Increment founding counter and add to waitlist
            if str_contains(body, "\"founding\"") {
                let current_sold: Int = get_sold()
                let new_sold: Int = current_sold + 1
                state_set("__founding_sold__", int_to_str(new_sold))
                persist_founding_count(new_sold)
                println("[webhook] founding sold: " + int_to_str(new_sold))
                if !str_eq(customer_email, "") {
                    waitlist_upsert(customer_email, customer_name, "founding", "stripe-purchase", "", "", new_sold)
                }
            }
            // Professional preorder
            if str_contains(body, "\"professional\"") {
                if !str_eq(customer_email, "") {
                    waitlist_upsert(customer_email, customer_name, "professional", "stripe-purchase", "", "", 0)
                }
            }
            // Save stripe_customer_id to waitlist row
            if !str_eq(customer_email, "") && !str_eq(customer_id, "") {
                let wb_sb_url: String = state_get("__supabase_project_url__")
                let wb_sb_key: String = state_get("__supabase_service_key__")
                if !str_eq(wb_sb_key, "") {
                    let cid_safe: String = str_replace(customer_id, "\"", "\\\"")
                    let update_row: String = "{\"stripe_customer_id\":\"" + cid_safe + "\"}"
                    supabase_insert(wb_sb_url, wb_sb_key, "waitlist?email=eq." + customer_email + "&on_conflict=email,plan", update_row)
                }
            }
            // Forward to license API for key provisioning.
            let license_api: String = state_get("__license_api_url__")
            if !str_eq(license_api, "") {
                let resp: String = http_post(license_api + "/api/v1/webhooks/stripe", body)
                println("[webhook] forwarded to license API: " + resp)
            }
        }
        return "{\"received\":true}"
    }

    // ── Share card — POST /api/share ──────────────────────────────────────────
    if str_eq(path, "/api/share") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let question: String = json_get(body, "question")
        let answer: String = json_get(body, "answer")
        if str_eq(question, "") || str_eq(answer, "") {
            return "{\"error\":\"question and answer required\"}"
        }
        let ts: String = int_to_str(unix_timestamp())
        let id: String = str_slice(ts, str_len(ts) - 8, str_len(ts))
        let html_share: String = share_card_page(question, answer, id)
        let gcs_bucket: String = env("GCS_SHARE_BUCKET")
        if !str_eq(gcs_bucket, "") {
            // GCS — durable across Cloud Run instances and restarts
            let gcs_ok: String = gcs_write(gcs_bucket, "cards/" + id + ".html", html_share)
            println("[share] gcs write cards/" + id + ".html -> " + gcs_ok)
        } else {
            // Local dev fallback
            fs_write(src_dir + "/shares/" + id + ".html", html_share)
        }
        // Write to Supabase share_cards for the gallery + voting
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_key: String = state_get("__supabase_service_key__")
        if !str_eq(sb_key, "") {
            let q_safe: String = str_replace(str_replace(question, "\\", "\\\\"), "\"", "\\\"")
            let a_safe: String = str_replace(str_replace(str_replace(str_replace(answer, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n"), "\r", "\\r")
            let card_row: String = "{\"id\":\"" + id + "\",\"question\":\"" + q_safe + "\",\"answer\":\"" + a_safe + "\"}"
            let sb_resp: String = supabase_insert(sb_url, sb_key, "share_cards", card_row)
            println("[share] supabase insert " + id + " -> " + sb_resp)
        }
        return "{\"id\":\"" + id + "\"}"
    }

    // ── Vote on a share card — POST /api/vote ────────────────────────────────
    if str_eq(path, "/api/vote") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let vote_id: String = json_get(body, "id")
        let direction: String = json_get(body, "direction")
        if str_eq(vote_id, "") || str_eq(direction, "") {
            return "{\"error\":\"id and direction required\"}"
        }
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_key: String = state_get("__supabase_service_key__")
        if str_eq(sb_key, "") {
            return "{\"error\":\"not configured\"}"
        }
        // Use Supabase RPC to atomically increment the right column
        let col: String = if str_eq(direction, "up") { "upvotes" } else { "downvotes" }
        let score_delta: String = if str_eq(direction, "up") { "1" } else { "-1" }
        // PATCH via Supabase REST — increment upvotes or downvotes + recalculate score
        let update_json: String = "{\"" + col + "\":\"" + col + " + 1\",\"score\":\"score + " + score_delta + "\"}"
        // Use Postgres RPC for atomic increment
        let rpc_body: String = "{\"p_id\":\"" + vote_id + "\",\"p_col\":\"" + col + "\",\"p_delta\":" + score_delta + "}"
        // Fallback: direct update via REST with computed columns
        let up_resp: String = http_post_auth(
            sb_url + "/rest/v1/rpc/vote_card",
            sb_key,
            rpc_body
        )
        println("[vote] " + direction + " on " + vote_id + " -> " + up_resp)
        return "{\"ok\":true}"
    }

    // ── Vote count — GET /api/vote-count/<id> ────────────────────────────────
    if str_starts_with(path, "/api/vote-count/") {
        let vc_id: String = str_slice(path, 16, str_len(path))
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_key: String = state_get("__supabase_service_key__")
        if str_eq(sb_key, "") {
            return "{\"score\":0,\"upvotes\":0,\"downvotes\":0}"
        }
        let vc_resp: String = supabase_get(
            sb_url, sb_key,
            "share_cards?select=score,upvotes,downvotes&id=eq." + vc_id
        )
        let score_raw: String = json_get(vc_resp, "0.score")
        let up_raw: String = json_get(vc_resp, "0.upvotes")
        let down_raw: String = json_get(vc_resp, "0.downvotes")
        let score_str: String = if str_eq(score_raw, "") { "0" } else { score_raw }
        let up_str: String = if str_eq(up_raw, "") { "0" } else { up_raw }
        let down_str: String = if str_eq(down_raw, "") { "0" } else { down_raw }
        return "{\"score\":" + score_str + ",\"upvotes\":" + up_str + ",\"downvotes\":" + down_str + "}"
    }

    // ── Gallery — GET /said ───────────────────────────────────────────────────
    if str_eq(path, "/said") {
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_key: String = state_get("__supabase_service_key__")
        let cards_json: String = ""
        if !str_eq(sb_key, "") {
            // Use supabase_get which sends both apikey and Authorization headers
            let cards_json = supabase_get(
                sb_url,
                sb_key,
                "share_cards?select=id,question,answer,score,upvotes,downvotes,created_at&order=score.desc,created_at.desc&limit=100"
            )
        }
        return gallery_page(cards_json)
    }

    // ── Share card — GET /share/<id> ──────────────────────────────────────────
    if str_starts_with(path, "/share/") {
        let id: String = str_slice(path, 7, str_len(path))
        let share_html: String = ""
        let gcs_bucket2: String = env("GCS_SHARE_BUCKET")
        if !str_eq(gcs_bucket2, "") {
            let share_html = gcs_read(gcs_bucket2, "cards/" + id + ".html")
        } else {
            let share_html = fs_read(src_dir + "/shares/" + id + ".html")
        }
        if str_eq(share_html, "") {
            return "{\"__status__\":404,\"error\":\"not found\"}"
        }
        return share_html
    }

    // ── Checkout success ──────────────────────────────────────────────────────
    // Stripe appends ?payment_intent=...&payment_intent_client_secret=...&redirect_status=succeeded
    // to the return_url. Use prefix match so the query string does not 404.
    if str_starts_with(path, "/marketplace/success") {
        let badge_html: String = founding_badge(get_sold())
        let badge_css: String = founding_badge_css()
        return page_open() + badge_css + "
<div style=\"min-height:80vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:4rem 2rem\">
  <p class=\"label\" style=\"margin-bottom:1.5rem\">You&#39;re in.</p>
  <h1 class=\"display-lg\" style=\"margin-bottom:1.25rem\">Welcome to Neuron.</h1>
  <p style=\"font-family:var(--body);font-weight:300;font-size:1.1rem;color:var(--t2);max-width:28rem;line-height:1.7;margin-bottom:3rem\">
    Your license is being provisioned. Check your email - your license key and download instructions will be there in the next few minutes.
  </p>
  <div style=\"margin-bottom:3rem\">" + badge_html + "</div>
  <div style=\"display:flex;gap:1rem;flex-wrap:wrap;justify-content:center\">
    <a href=\"/account\" class=\"btn-primary\">View your account &#8594;</a>
    <a href=\"/\" class=\"btn-ghost\">Back to home</a>
  </div>
</div>
" + page_close()
    }

    // ── Account dashboard ─────────────────────────────────────────────────────
    // Use prefix match so OAuth/email-confirmation redirects with query strings still hit.
    if str_starts_with(path, "/account") {
        let sb_url: String = state_get("__supabase_project_url__")
        let sb_anon: String = state_get("__supabase_anon_key__")
        return account_page(sb_url, sb_anon)
    }

    // ── Founding badge fragment ───────────────────────────────────────────────
    if str_starts_with(path, "/api/founding-badge") {
        let n_str: String = "1"
        let q: Int = str_index_of(path, "n=")
        if q >= 0 {
            let n_str = str_slice(path, q + 2, str_len(path))
        }
        let badge_html: String = founding_badge(str_to_int(n_str))
        let badge_css: String = founding_badge_css()
        return badge_css + badge_html
    }

    // ── Family plan — POST /api/family/invite ────────────────────────────────
    if str_eq(path, "/api/family/invite") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let parent_email: String = json_get(body, "parent_email")
        let child_email: String = json_get(body, "child_email")
        let child_dob_year_str: String = json_get(body, "child_dob_year")
        let attested_str: String = json_get(body, "attested")
        if str_eq(parent_email, "") || str_eq(child_email, "") || str_eq(child_dob_year_str, "") {
            return "{\"error\":\"parent_email, child_email, and child_dob_year are required\"}"
        }
        if !str_eq(attested_str, "true") {
            return "{\"error\":\"attestation required\"}"
        }
        let child_dob_year: Int = str_to_int(child_dob_year_str)
        if child_dob_year < 2008 {
            return "{\"error\":\"Child must be under 18. Birth year must be 2008 or later.\"}"
        }
        // Check existing family member count
        let fam_sb_url: String = state_get("__supabase_project_url__")
        let fam_sb_key: String = state_get("__supabase_service_key__")
        if str_eq(fam_sb_key, "") {
            return "{\"error\":\"not configured\"}"
        }
        let pe_safe: String = str_replace(str_replace(parent_email, "\\", "\\\\"), "\"", "\\\"")
        let ce_safe: String = str_replace(str_replace(child_email, "\\", "\\\\"), "\"", "\\\"")
        let members_resp: String = http_get_auth(
            fam_sb_url + "/rest/v1/family_members?parent_email=eq." + parent_email + "&status=neq.cancelled&select=child_email",
            fam_sb_key
        )
        let member_count: Int = json_array_len(members_resp)
        if member_count >= 5 {
            return "{\"error\":\"Maximum of 5 family members reached.\"}"
        }
        // Check child not already added
        let dup_resp: String = http_get_auth(
            fam_sb_url + "/rest/v1/family_members?parent_email=eq." + parent_email + "&child_email=eq." + child_email + "&select=child_email",
            fam_sb_key
        )
        let dup_count: Int = json_array_len(dup_resp)
        if dup_count > 0 {
            return "{\"error\":\"This child email is already in your family plan.\"}"
        }
        // Create Stripe customer for child
        let fam_stripe_key: String = state_get("__stripe_secret_key__")
        if str_eq(fam_stripe_key, "") {
            return "{\"error\":\"Stripe not configured\"}"
        }
        let child_email_safe: String = str_replace(child_email, "@", "%40")
        let customer_body: String = "email=" + child_email_safe
        let customer_resp: String = http_post_auth("https://api.stripe.com/v1/customers", fam_stripe_key, customer_body)
        let child_customer_id: String = json_get(customer_resp, "id")
        if str_eq(child_customer_id, "") {
            return "{\"error\":\"Failed to create Stripe customer\"}"
        }
        // Create Stripe subscription for child
        let price_id: String = state_get("__stripe_price_family_child__")
        if str_eq(price_id, "") {
            return "{\"error\":\"Family child price not configured\"}"
        }
        let parent_email_safe: String = str_replace(parent_email, "@", "%40")
        let sub_body: String = "customer=" + child_customer_id
            + "&items[0][price]=" + price_id
            + "&trial_period_days=7"
            + "&metadata[parent_email]=" + parent_email_safe
            + "&metadata[type]=family_child"
        let sub_resp: String = http_post_auth("https://api.stripe.com/v1/subscriptions", fam_stripe_key, sub_body)
        let sub_id: String = json_get(sub_resp, "id")
        if str_eq(sub_id, "") {
            return "{\"error\":\"Failed to create Stripe subscription\"}"
        }
        // Generate invite token
        let ts_str: String = int_to_str(unix_timestamp())
        let email_prefix: String = str_slice(child_email, 0, 4)
        let invite_token: String = ts_str + email_prefix
        // Insert into family_members table
        let fam_row: String = "{\"parent_email\":\"" + pe_safe + "\",\"parent_user_id\":\"\",\"child_email\":\"" + ce_safe + "\",\"child_dob_year\":" + child_dob_year_str + ",\"status\":\"invited\",\"stripe_subscription_id\":\"" + sub_id + "\",\"invite_token\":\"" + invite_token + "\"}"
        let fam_insert_resp: String = supabase_insert(fam_sb_url, fam_sb_key, "family_members", fam_row)
        println("[family/invite] insert -> " + fam_insert_resp)
        // Send invite email if Resend available
        let fam_resend_key: String = state_get("__resend_api_key__")
        if !str_eq(fam_resend_key, "") {
            let invite_email_body: String = "{\"from\":\"Neuron <no-reply@neurontechnologies.ai>\",\"to\":[\"" + ce_safe + "\"],\"subject\":\"You have been invited to Neuron\",\"text\":\"You have been invited to join Neuron by " + pe_safe + ". Visit https://neurontechnologies.ai/account to set up your account.\"}"
            let invite_email_resp: String = http_post_auth("https://api.resend.com/emails", fam_resend_key, invite_email_body)
            println("[family/invite] email -> " + invite_email_resp)
        }
        return "{\"ok\":true,\"invite_token\":\"" + invite_token + "\"}"
    }

    // ── Family plan — GET /api/family/members ────────────────────────────────
    if str_starts_with(path, "/api/family/members") {
        let fml_sb_url: String = state_get("__supabase_project_url__")
        let fml_sb_key: String = state_get("__supabase_service_key__")
        if str_eq(fml_sb_key, "") {
            return "[]"
        }
        // Extract parent_email from query string
        let fml_parent_email: String = ""
        let q_idx: Int = str_index_of(path, "parent_email=")
        if q_idx >= 0 {
            let fml_parent_email = str_slice(path, q_idx + 13, str_len(path))
        }
        if str_eq(fml_parent_email, "") {
            return "{\"error\":\"parent_email required\"}"
        }
        let fml_resp: String = http_get_auth(
            fml_sb_url + "/rest/v1/family_members?parent_email=eq." + fml_parent_email + "&select=child_email,status,child_dob_year,created_at",
            fml_sb_key
        )
        if str_eq(fml_resp, "") {
            return "[]"
        }
        return fml_resp
    }

    // ── Family plan — POST /api/family/remove ────────────────────────────────
    if str_eq(path, "/api/family/remove") {
        if !str_eq(method, "POST") {
            return "{\"error\":\"POST required\"}"
        }
        let rem_parent_email: String = json_get(body, "parent_email")
        let rem_child_email: String = json_get(body, "child_email")
        if str_eq(rem_parent_email, "") || str_eq(rem_child_email, "") {
            return "{\"error\":\"parent_email and child_email required\"}"
        }
        let rem_sb_url: String = state_get("__supabase_project_url__")
        let rem_sb_key: String = state_get("__supabase_service_key__")
        if str_eq(rem_sb_key, "") {
            return "{\"error\":\"not configured\"}"
        }
        // Fetch the subscription ID
        let sub_lookup: String = http_get_auth(
            rem_sb_url + "/rest/v1/family_members?parent_email=eq." + rem_parent_email + "&child_email=eq." + rem_child_email + "&select=stripe_subscription_id",
            rem_sb_key
        )
        let rem_sub_id: String = json_get(sub_lookup, "0.stripe_subscription_id")
        // Cancel Stripe subscription if present
        if !str_eq(rem_sub_id, "") {
            let rem_stripe_key: String = state_get("__stripe_secret_key__")
            if !str_eq(rem_stripe_key, "") {
                let cancel_resp: String = http_post_auth("https://api.stripe.com/v1/subscriptions/" + rem_sub_id + "/cancel", rem_stripe_key, "")
                println("[family/remove] cancel sub " + rem_sub_id + " -> " + cancel_resp)
            }
        }
        // Update status to cancelled
        let rpe_safe: String = str_replace(str_replace(rem_parent_email, "\\", "\\\\"), "\"", "\\\"")
        let rce_safe: String = str_replace(str_replace(rem_child_email, "\\", "\\\\"), "\"", "\\\"")
        let cancel_row: String = "{\"status\":\"cancelled\"}"
        supabase_insert(rem_sb_url, rem_sb_key, "family_members?parent_email=eq." + rem_parent_email + "&child_email=eq." + rem_child_email, cancel_row)
        println("[family/remove] cancelled " + rce_safe + " from " + rpe_safe)
        return "{\"ok\":true}"
    }

    // ── Fallback ──────────────────────────────────────────────────────────────
    return "{\"__status__\":404,\"error\":\"not found\"}"
}

// ── Startup ───────────────────────────────────────────────────────────────────
//
// Order matters:
//  1. Load Stripe config + origin from env  (needed before founding count)
//  2. Seed founding count from file or Stripe API
//  3. Generate all HTML with the real count
//  4. Register with El HTTP runtime and serve

let landing_root: String = env("LANDING_ROOT")
let src_dir: String = if str_eq(landing_root, "") { cwd() + "/src" } else { landing_root }
let html_path: String = src_dir + "/index.html"

// Soul URL — where the demo soul is reachable.
// Defaults to localhost for local dev; set SOUL_URL for deployed environments.
let soul_url: String = env("SOUL_URL")
if str_eq(soul_url, "") {
    soul_url = "http://localhost:7772"
}
state_set("__soul_url__", soul_url)

// Stripe config from environment — loaded first so founding count can use it.
let stripe_key: String = env("STRIPE_SECRET_KEY")
let stripe_pub_key: String = env("STRIPE_PUBLISHABLE_KEY")
let stripe_price_founding: String = env("STRIPE_PRICE_FOUNDING")
let stripe_price_professional: String = env("STRIPE_PRICE_PROFESSIONAL")
let family_child_price: String = env("STRIPE_PRICE_FAMILY_CHILD")
let license_api_url: String = env("NEURON_LICENSE_API_URL")
let resend_api_key: String = env("RESEND_API_KEY")
let supabase_anon_key: String = env("SUPABASE_ANON_KEY")
let supabase_service_key: String = env("SUPABASE_SERVICE_KEY")
let supabase_project_url: String = "https://ocojsghaonltunidkzpw.supabase.co"

// Origin — drives Stripe redirect URLs; never hardcoded to localhost.
let neuron_origin: String = env("NEURON_ORIGIN")
if str_eq(neuron_origin, "") {
    neuron_origin = "https://neurontechnologies.ai"
}

// Founding count — seeded from persist file or live Stripe query.
let sold_file: String = src_dir + "/founding_sold.txt"
let real_sold: Int = load_founding_count(sold_file, stripe_key)

// Ensure shares directory exists.
fs_mkdir(src_dir + "/shares")

// Generate all page HTML using the real founding count.
let page_html: String = page(real_sold, FOUNDING_TOTAL)
fs_write(html_path, page_html)

// Generate about page HTML.
let about_html_path: String = src_dir + "/about.html"
let about_html: String = page_open() + about_page() + page_close()
fs_write(about_html_path, about_html)

// Generate terms pages HTML.
let terms_html_path: String = src_dir + "/terms.html"
let ent_terms_html_path: String = src_dir + "/enterprise-terms.html"
fs_write(terms_html_path, terms_page())
fs_write(ent_terms_html_path, enterprise_terms_page())

// Register with El HTTP runtime.
state_set("__html_file__",                   html_path)
state_set("__about_html_file__",             about_html_path)
state_set("__terms_html_file__",             terms_html_path)
state_set("__enterprise_terms_html_file__",  ent_terms_html_path)
state_set("__src_dir__",                     src_dir)
state_set("__stripe_secret_key__",           stripe_key)
state_set("__stripe_publishable_key__",      stripe_pub_key)
state_set("__stripe_price_founding__",       stripe_price_founding)
state_set("__stripe_price_professional__",   stripe_price_professional)
state_set("__stripe_price_family_child__",   family_child_price)
state_set("__license_api_url__",             license_api_url)
state_set("__resend_api_key__",              resend_api_key)
state_set("__supabase_anon_key__",           supabase_anon_key)
state_set("__supabase_service_key__",        supabase_service_key)
state_set("__supabase_project_url__",        supabase_project_url)
state_set("__origin__",                      neuron_origin)
state_set("__founding_sold_file__",          sold_file)
state_set("__founding_sold__",               int_to_str(real_sold))
state_set("__founding_total__",              int_to_str(FOUNDING_TOTAL))
persist_founding_count(real_sold)

println(color_bold("Neuron") + " - " + neuron_origin)
println("  HTML generated by El → " + html_path)
println("  About  generated by El → " + about_html_path)
println("  Terms  generated by El → " + terms_html_path)
println("  Ent. Terms generated by El → " + ent_terms_html_path)
println("  Assets  → " + src_dir + "/assets/")
println("")
println("  Routes:")
println("    GET  /                          → El-generated landing page")
println("    GET  /about                     → El-generated about page")
println("    GET  /legal/terms               → Consumer terms of service")
println("    GET  /legal/enterprise-terms    → Enterprise agreement")
println("    GET  /api/health                → health check")
println("    GET  /api/founding-count        → founding counter JSON")
println("    POST /api/checkout              → Stripe checkout session")
println("    POST /api/webhooks/stripe       → Stripe webhook")
println("    GET  /marketplace/success       → post-purchase success page")
println("    GET  /assets/*                  → static files")
println("    GET  /brand/*                   → brand files")
println("    GET  /api/supabase-config       → public Supabase config (URL + anon key)")
println("")

let port: Int = if str_eq(env("PORT"), "") { 3001 } else { str_to_int(env("PORT")) }
http_set_handler("handle_request")
http_serve(port, "handle_request")
