from pathlib import Path
from html import escape

THEME = Path('/opt/cosmosluminosity/content/themes/clean')

COPY = {
'ru': {
'layout':'default','url':'https://www.cosmosluminosity.com/next-chapter-experiment/','alt':'https://www.cosmosluminosity.com/next-chapter-experiment-en/',
'page_title':'Создай свой эксперимент — Cosmos Luminosity','description':'Бесплатный самостоятельный опыт: преврати один профессиональный вопрос в небольшой обратимый эксперимент и получи личную Experiment Card.','label':'Бесплатный самостоятельный опыт','title':'Создай свой эксперимент','lead':'Преврати один профессиональный вопрос в небольшой обратимый эксперимент — без необходимости заранее решать всё будущее.','promise':'Один вопрос · одна рабочая гипотеза · один обратимый шаг · личная Experiment Card','time':'10–15 минут','privacy':'Без регистрации. Ответы остаются в твоём браузере.','start':'Создать эксперимент','about_title':'Что ты получишь за одну сессию','about_body':'Ты назовёшь то, что стало тесным, сохранишь важное, услышишь разные источники собственной информации и создашь действие, которое способно дать реальные данные. Это не тест личности, не предсказание и не совет увольняться.','steps':['Вопрос','Поле перехода','Сигналы','Эксперимент','Результат'],
'back':'Назад','next':'Продолжить','create':'Создать мою Experiment Card','required':'Пожалуйста, заполни это поле, чтобы продолжить.','choose':'Выбери хотя бы один вариант.','step1_title':'Открой один живой вопрос','step1_help':'Не ищи идеальную формулировку. Выбери вопрос, которому сейчас полезнее встретиться с реальностью, чем получить ещё один окончательный ответ.','q_label':'Какой профессиональный вопрос ты исследуешь?','q_placeholder':'Например: я хочу уйти из профессии — или изменить способ, которым я в ней работаю?','stage_label':'Где ты сейчас?','stage_opts':[('signal','Я чувствую, что прежний способ стал тесным'),('threshold','Я вижу несколько направлений и не могу различить их'),('experiment','У меня есть направление, которое я хочу проверить'),('after','Прежняя глава уже завершилась, следующая ещё не ясна')],
'step2_title':'Собери поле перехода','step2_help':'Отдели то, что стало тесным, от того, что по-прежнему принадлежит тебе.','tight_label':'Что сейчас стало тесным?','tight_opts':[('role','Роль или уровень ответственности'),('rhythm','Ритм и цена успеха'),('environment','Среда, культура или отношения'),('identity','Профессиональная идентичность'),('direction','Само направление работы'),('income','Способ зарабатывать')],'preserve_label':'Что важно сохранить?','preserve_opts':[('mastery','Мастерство и опыт'),('relationships','Связи и профессиональное сообщество'),('reputation','Репутацию и влияние'),('income','Доходный потенциал'),('rhythm','Подходящие элементы образа жизни'),('meaning','Смысл и живые части работы')],'other_label':'Добавить своё','other_placeholder':'Коротко назови то, что важно не потерять','unknown_label':'Что пока рано решать окончательно?','unknown_placeholder':'Например: требуется ли мне полностью уходить из профессии','step3_title':'Услышь источники собственной информации','step3_help':'Им не требуется соглашаться между собой. Здесь нет одного главного голоса.','mind_label':'Что говорит мышление?','mind_placeholder':'Факты, аргументы, возможности, ограничения','body_label':'Что сообщает тело?','body_placeholder':'Напряжение, расширение, усталость, дыхание, энергия','state_label':'Что меняется в состоянии, когда ты представляешь разные варианты?','state_placeholder':'Темп, ясность, присутствие, любопытство, сопротивление','desire_label':'Чего тебе хочется, если на минуту убрать обязанность всё объяснить?','desire_placeholder':'Не решение — только живое желание','step4_title':'Создай рабочую гипотезу','step4_help':'Гипотеза не является истиной. Она даёт направлению возможность встретиться с реальной жизнью.','hyp_label':'Рабочая гипотеза','hypotheses':{'role':'Возможно, завершилась не профессия, а нынешняя роль внутри неё.','rhythm':'Возможно, тебе требуется не меньший масштаб, а другая цена этого масштаба.','environment':'Возможно, проблема не в работе, а в среде и отношениях, внутри которых она происходит.','identity':'Возможно, прежняя профессиональная идентичность стала тесной раньше, чем появилось имя для следующей.','direction':'Возможно, одно новое направление стоит проверить до большого решения.','income':'Возможно, способ зарабатывать можно пересобрать, не обнуляя мастерство.'},'hyp_custom':'Изменить гипотезу','experiment_label':'Какой обратимый шаг даст тебе новые данные?','experiments':{'role':['Провести один разговор о другой роли или конфигурации ответственности.','На один рабочий блок действовать из желаемой роли и записать, что изменилось.'],'rhythm':['Создать один рабочий блок в желаемом ритме и сравнить состояние и результат.','Убрать одну привычную нагрузку на один день и наблюдать, что стало возможным.'],'environment':['Провести один профессиональный разговор за пределами привычной среды.','Попробовать один рабочий блок с другой границей или способом взаимодействия.'],'identity':['Представиться без привычного титула в одном безопасном разговоре и заметить реакцию.','Описать своё мастерство без названия должности и показать одному доверенному человеку.'],'direction':['Сделать маленький прототип, пробную встречу или короткий фрагмент новой работы.','Поговорить с одним человеком, уже находящимся в рассматриваемом направлении.'],'income':['Собрать один черновой сценарий доходного моста без обязательства его реализовывать.','Проверить интерес к одной небольшой оплачиваемой ценности без изменения основной работы.']},'custom_experiment':'Или сформулируй собственный эксперимент','boundary_label':'Что остаётся неизменным во время эксперимента?','boundary_placeholder':'Например: я не увольняюсь, не объявляю решение и не беру финансовых обязательств','evidence_label':'Что ты будешь наблюдать?','evidence_opts':[('energy','Энергию и доступную ёмкость'),('curiosity','Любопытство и желание продолжить'),('reality','Реальную обратную связь от людей или среды'),('skill','Как используется моё мастерство'),('money','Материальную жизнеспособность'),('resistance','Сопротивление, страх и то, что за ними находится')],
'result_label':'Твоя личная карточка','result_title':'The Next Chapter Experiment','result_intro':'Это не решение за тебя. Это способ дать одному вопросу встретиться с жизнью, сохраняя твоё авторство.','card_question':'Мой вопрос','card_tight':'Что стало тесным','card_preserve':'Что я сохраняю','card_unknown':'Что пока не решаю','card_signals':'Что сообщают мои источники информации','card_hyp':'Рабочая гипотеза','card_exp':'Мой обратимый эксперимент','card_boundary':'Граница эксперимента','card_evidence':'Что я наблюдаю','card_review':'Когда я пересмотрю данные','review_options':[('today','Сегодня позже'),('72h','Через 72 часа'),('week','В течение недели'),('own','Я выберу свой момент')],'print':'Сохранить / распечатать','copy':'Скопировать карточку','copied':'Карточка скопирована','restart':'Создать другой эксперимент','after_title':'Что дальше','after_body':'Карточка уже является завершённым результатом бесплатного опыта. Ты можешь взять её в жизнь и вернуться к данным самостоятельно. Если вопрос требует более глубокой карты перехода, продолжи в Gateway: Between Identities.','gateway':'Исследовать Gateway','home':'Вернуться на главную','empty':'Не указано','signal_names':{'mind':'Мышление','body':'Тело','state':'Состояние','desire':'Желание'},'tight_names':{'role':'Роль','rhythm':'Ритм и цена успеха','environment':'Среда и отношения','identity':'Профессиональная идентичность','direction':'Направление работы','income':'Способ зарабатывать'},'preserve_names':{'mastery':'Мастерство и опыт','relationships':'Связи и сообщество','reputation':'Репутация и влияние','income':'Доходный потенциал','rhythm':'Образ жизни','meaning':'Смысл и живые части работы'},'evidence_names':{'energy':'Энергия и ёмкость','curiosity':'Любопытство','reality':'Обратная связь','skill':'Использование мастерства','money':'Материальная жизнеспособность','resistance':'Сопротивление и страх'}
},
'en': {
'layout':'default-en','url':'https://www.cosmosluminosity.com/next-chapter-experiment-en/','alt':'https://www.cosmosluminosity.com/next-chapter-experiment/','page_title':'Create Your Experiment — Cosmos Luminosity','description':'A free self-guided experience: turn one professional question into a small reversible experiment and receive your personal Experiment Card.','label':'A free self-guided experience','title':'Create your experiment','lead':'Turn one professional question into a small reversible experiment—without deciding your whole future first.','promise':'One question · one working hypothesis · one reversible step · your Experiment Card','time':'10–15 minutes','privacy':'No sign-up. Your answers stay in your browser.','start':'Create your experiment','about_title':'What you receive in one session','about_body':'Name what has become too small, preserve what matters, listen to different sources of your own information, and create an action capable of producing real evidence. This is not a personality test, prediction, or advice to resign.','steps':['Question','Transition field','Signals','Experiment','Result'],
'back':'Back','next':'Continue','create':'Create my Experiment Card','required':'Complete this field to continue.','choose':'Choose at least one option.','step1_title':'Open one living question','step1_help':'Do not search for the perfect wording. Choose a question that would benefit more from meeting reality than from receiving another final answer.','q_label':'What professional question are you exploring?','q_placeholder':'For example: do I want to leave my profession—or change the way I work inside it?','stage_label':'Where are you now?','stage_opts':[('signal','The old way has started to feel too small'),('threshold','I see several directions and cannot yet discern between them'),('experiment','I have a direction I want to explore'),('after','The old chapter has ended; the next one is not yet clear')],
'step2_title':'Create your transition field','step2_help':'Separate what has become too small from what still belongs to you.','tight_label':'What has become too small?','tight_opts':[('role','Role or level of responsibility'),('rhythm','Rhythm and the price of success'),('environment','Environment, culture, or relationships'),('identity','Professional identity'),('direction','The direction of the work itself'),('income','The way you earn')],'preserve_label':'What matters enough to preserve?','preserve_opts':[('mastery','Mastery and experience'),('relationships','Relationships and professional community'),('reputation','Reputation and influence'),('income','Earning potential'),('rhythm','Elements of your way of life'),('meaning','Meaning and the living parts of the work')],'other_label':'Add your own','other_placeholder':'Name what you do not want to lose','unknown_label':'What is too early to decide?','unknown_placeholder':'For example: whether I need to leave the profession entirely','step3_title':'Listen to your sources of information','step3_help':'They do not have to agree. No single voice is given absolute authority.','mind_label':'What does your mind say?','mind_placeholder':'Facts, arguments, possibilities, constraints','body_label':'What is your body communicating?','body_placeholder':'Tension, expansion, fatigue, breath, energy','state_label':'What changes in your state when you imagine different options?','state_placeholder':'Pace, clarity, presence, curiosity, resistance','desire_label':'What do you want when you briefly release the need to explain it?','desire_placeholder':'Not a decision—only a living desire','step4_title':'Create a working hypothesis','step4_help':'A hypothesis is not the truth. It gives a direction a chance to meet real life.','hyp_label':'Working hypothesis','hypotheses':{'role':'Perhaps the profession has not ended; the current role inside it has.','rhythm':'Perhaps you do not want a smaller life, but a different price for its scale.','environment':'Perhaps the work is not the problem; the environment and relationships around it are.','identity':'Perhaps the old professional identity became too small before the next one had a name.','direction':'Perhaps one new direction is worth exploring before a major decision.','income':'Perhaps the way you earn can be redesigned without erasing your mastery.'},'hyp_custom':'Edit the hypothesis','experiment_label':'What reversible step could give you new evidence?','experiments':{'role':['Have one conversation about a different role or configuration of responsibility.','Spend one work block acting from the desired role and record what changes.'],'rhythm':['Create one work block at your desired pace and compare state and outcome.','Remove one habitual pressure for a day and notice what becomes possible.'],'environment':['Have one professional conversation outside your usual environment.','Try one work block with a different boundary or way of interacting.'],'identity':['Introduce yourself without your usual title in one safe conversation and notice your response.','Describe your mastery without a job title and share it with one trusted person.'],'direction':['Create a small prototype, trial conversation, or short fragment of the new work.','Speak with one person already working in the direction you are considering.'],'income':['Sketch one income-bridge scenario without committing to implement it.','Test interest in one small paid value without changing your main work.']},'custom_experiment':'Or write your own experiment','boundary_label':'What remains unchanged during the experiment?','boundary_placeholder':'For example: I am not resigning, announcing a decision, or taking on a financial commitment','evidence_label':'What will you observe?','evidence_opts':[('energy','Energy and available capacity'),('curiosity','Curiosity and desire to continue'),('reality','Real feedback from people or the environment'),('skill','How my mastery is used'),('money','Material viability'),('resistance','Resistance, fear, and what sits beneath them')],
'result_label':'Your personal card','result_title':'The Next Chapter Experiment','result_intro':'This does not decide for you. It lets one question meet life while you keep your authorship.','card_question':'My question','card_tight':'What became too small','card_preserve':'What I preserve','card_unknown':'What I am not deciding yet','card_signals':'What my sources of information say','card_hyp':'Working hypothesis','card_exp':'My reversible experiment','card_boundary':'Experiment boundary','card_evidence':'What I will observe','card_review':'When I will review the evidence','review_options':[('today','Later today'),('72h','In 72 hours'),('week','Within a week'),('own','I will choose my own moment')],'print':'Save / print','copy':'Copy the card','copied':'Card copied','restart':'Create another experiment','after_title':'What comes next','after_body':'The card is already a complete result of this free experience. Take it into life and return to the evidence in your own time. If the question needs a deeper transition map, continue into Gateway: Between Identities.','gateway':'Explore Gateway','home':'Return home','empty':'Not specified','signal_names':{'mind':'Mind','body':'Body','state':'State','desire':'Desire'},'tight_names':{'role':'Role','rhythm':'Rhythm and the price of success','environment':'Environment and relationships','identity':'Professional identity','direction':'Direction of work','income':'Way of earning'},'preserve_names':{'mastery':'Mastery and experience','relationships':'Relationships and community','reputation':'Reputation and influence','income':'Earning potential','rhythm':'Way of life','meaning':'Meaning and living parts of work'},'evidence_names':{'energy':'Energy and capacity','curiosity':'Curiosity','reality':'Real-world feedback','skill':'Use of mastery','money':'Material viability','resistance':'Resistance and fear'}
}}

def attrs_data(c):
    # Strings are embedded via JSON in the script instead, avoiding data-attribute escaping complexity.
    pass

def options_radio(name, items):
    return ''.join(f'<label class="choice"><input type="radio" name="{name}" value="{v}"><span>{escape(t)}</span></label>' for v,t in items)

def options_check(name, items):
    return ''.join(f'<label class="choice"><input type="checkbox" name="{name}" value="{v}"><span>{escape(t)}</span></label>' for v,t in items)

def field(label, name, placeholder, rows=3):
    return f'<label class="field"><span>{escape(label)}</span><textarea name="{name}" rows="{rows}" placeholder="{escape(placeholder)}"></textarea></label>'

def build(lang):
    import json
    c=COPY[lang]
    home='/' if lang=='ru' else '/en/'
    gateway='/gateways/' if lang=='ru' else '/en/gateways/'
    page=[]
    page.append(f'{{{{!< {c["layout"]}}}}}')
    page.append(f'{{{{#contentFor "page_title"}}}}{c["page_title"]}{{{{/contentFor}}}}')
    page.append(f'{{{{#contentFor "page_description"}}}}{c["description"]}{{{{/contentFor}}}}')
    page.append(f'{{{{#contentFor "canonical_url"}}}}{c["url"]}{{{{/contentFor}}}}')
    ru='https://www.cosmosluminosity.com/next-chapter-experiment/'
    en='https://www.cosmosluminosity.com/next-chapter-experiment-en/'
    page.append(f'{{{{#contentFor "ru_url"}}}}{ru}{{{{/contentFor}}}}')
    page.append(f'{{{{#contentFor "en_url"}}}}{en}{{{{/contentFor}}}}')
    page.append('<link rel="stylesheet" href="{{asset "css/experiment.css"}}">')
    page.append(f'<div class="experiment-page" data-experiment lang="{lang}">')
    page.append(f'<section class="experiment-hero"><div class="experiment-hero-inner"><p class="experiment-label">{escape(c["label"])}</p><h1>{escape(c["title"])}</h1><p class="experiment-lead">{escape(c["lead"])}</p><p class="experiment-promise">{escape(c["promise"])}</p><div class="experiment-meta"><span>{escape(c["time"])}</span><span>{escape(c["privacy"])}</span></div><button class="exp-button primary" type="button" data-start>{escape(c["start"])}</button></div></section>')
    page.append(f'<section class="experiment-about"><div><p class="experiment-label">Cosmos Luminosity</p><h2>{escape(c["about_title"])}</h2></div><p>{escape(c["about_body"])}</p></section>')
    page.append('<section class="experiment-workspace" data-workspace hidden><div class="progress-wrap"><ol class="progress">'+''.join(f'<li data-progress="{i}"><span>{i}</span><b>{escape(t)}</b></li>' for i,t in enumerate(c['steps'],1))+'</ol><div class="progress-bar"><i data-progress-bar></i></div></div><form data-form novalidate>')
    # Step 1
    page.append(f'<fieldset class="exp-step" data-step="1"><legend>{escape(c["step1_title"])}</legend><p class="step-help">{escape(c["step1_help"])}</p>{field(c["q_label"],"question",c["q_placeholder"],4)}<div class="field-group"><span class="group-label">{escape(c["stage_label"])}</span><div class="choice-grid">{options_radio("stage",c["stage_opts"])}</div></div><p class="form-error" data-error></p></fieldset>')
    # Step 2
    page.append(f'<fieldset class="exp-step" data-step="2" hidden><legend>{escape(c["step2_title"])}</legend><p class="step-help">{escape(c["step2_help"])}</p><div class="field-group"><span class="group-label">{escape(c["tight_label"])}</span><div class="choice-grid">{options_radio("tight",c["tight_opts"])}</div></div><div class="field-group"><span class="group-label">{escape(c["preserve_label"])}</span><div class="choice-grid">{options_check("preserve",c["preserve_opts"])}</div></div>{field(c["other_label"],"preserve_other",c["other_placeholder"],2)}{field(c["unknown_label"],"unknown",c["unknown_placeholder"],2)}<p class="form-error" data-error></p></fieldset>')
    # Step 3
    page.append(f'<fieldset class="exp-step" data-step="3" hidden><legend>{escape(c["step3_title"])}</legend><p class="step-help">{escape(c["step3_help"])}</p><div class="signal-grid">{field(c["mind_label"],"mind",c["mind_placeholder"],3)}{field(c["body_label"],"body",c["body_placeholder"],3)}{field(c["state_label"],"state",c["state_placeholder"],3)}{field(c["desire_label"],"desire",c["desire_placeholder"],3)}</div><p class="form-error" data-error></p></fieldset>')
    # Step 4
    page.append(f'<fieldset class="exp-step" data-step="4" hidden><legend>{escape(c["step4_title"])}</legend><p class="step-help">{escape(c["step4_help"])}</p><label class="field"><span>{escape(c["hyp_label"])}</span><textarea name="hypothesis" rows="3"></textarea></label><div class="field-group"><span class="group-label">{escape(c["experiment_label"])}</span><div class="choice-grid" data-experiment-options></div></div>{field(c["custom_experiment"],"experiment_custom","",3)}{field(c["boundary_label"],"boundary",c["boundary_placeholder"],3)}<div class="field-group"><span class="group-label">{escape(c["evidence_label"])}</span><div class="choice-grid">{options_check("evidence",c["evidence_opts"])}</div></div><p class="form-error" data-error></p></fieldset>')
    # nav
    page.append(f'<div class="form-nav"><button class="exp-button" type="button" data-back hidden>{escape(c["back"])}</button><button class="exp-button primary" type="button" data-next>{escape(c["next"])}</button></div></form>')
    # Result
    page.append(f'<section class="exp-result" data-result hidden aria-live="polite"><div class="result-head"><p class="experiment-label">{escape(c["result_label"])}</p><h2>{escape(c["result_title"])}</h2><p>{escape(c["result_intro"])}</p></div><article class="experiment-card" data-card><div class="card-mark">COSMOS LUMINOSITY · THE THOUGHTFUL TRANSITION</div><div class="card-grid">')
    keys=[('question','card_question'),('tight','card_tight'),('preserve','card_preserve'),('unknown','card_unknown'),('signals','card_signals'),('hypothesis','card_hyp'),('experiment','card_exp'),('boundary','card_boundary'),('evidence','card_evidence')]
    for key,label in keys: page.append(f'<section class="card-item card-{key}"><h3>{escape(c[label])}</h3><div data-out="{key}"></div></section>')
    page.append(f'<section class="card-item card-review"><h3>{escape(c["card_review"])}</h3><div class="review-choices">{options_radio("review",c["review_options"])}</div></section></div><footer><span>The Next Chapter Experiment</span><span>cosmosluminosity.com</span></footer></article><div class="result-actions"><button class="exp-button primary" type="button" data-print>{escape(c["print"])}</button><button class="exp-button" type="button" data-copy>{escape(c["copy"])}</button><button class="exp-button quiet" type="button" data-restart>{escape(c["restart"])}</button></div><p class="copy-status" data-copy-status role="status"></p><div class="after-card"><h3>{escape(c["after_title"])}</h3><p>{escape(c["after_body"])}</p><div><a class="exp-button primary" href="{gateway}">{escape(c["gateway"])}</a><a class="exp-button" href="{home}">{escape(c["home"])}</a></div></div></section></section></div>')
    js_copy=json.dumps(c,ensure_ascii=False).replace('</','<\\/')
    page.append('<script>')
    page.append(f'window.EXPERIMENT_COPY={js_copy};')
    page.append(r'''(()=>{const root=document.querySelector('[data-experiment]');if(!root)return;const c=window.EXPERIMENT_COPY,workspace=root.querySelector('[data-workspace]'),form=root.querySelector('[data-form]'),steps=[...root.querySelectorAll('[data-step]')],result=root.querySelector('[data-result]'),next=root.querySelector('[data-next]'),back=root.querySelector('[data-back]');let current=1;const esc=s=>String(s).replace(/[&<>"']/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch])),val=n=>form.elements[n]?.value.trim()||'',checked=n=>[...form.querySelectorAll(`[name="${n}"]:checked`)].map(x=>x.value),radio=n=>form.querySelector(`[name="${n}"]:checked`)?.value||'';function show(n){current=n;steps.forEach(s=>s.hidden=+s.dataset.step!==n);back.hidden=n===1;next.textContent=n===4?c.create:c.next;root.querySelectorAll('[data-progress]').forEach(x=>x.classList.toggle('active',+x.dataset.progress<=n));root.querySelector('[data-progress-bar]').style.width=((n-1)/3*100)+'%';workspace.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});steps[n-1].querySelector('legend').focus?.()}function error(msg){const el=steps[current-1].querySelector('[data-error]');el.textContent=msg;el.focus?.();return false}function validate(){const el=steps[current-1].querySelector('[data-error]');el.textContent='';if(current===1&&(!val('question')||!radio('stage')))return error(c.required);if(current===2&&(!radio('tight')||checked('preserve').length===0))return error(c.choose);if(current===4&&(!val('hypothesis')||(!radio('experiment')&&!val('experiment_custom'))||checked('evidence').length===0))return error(c.choose);return true}function populateExperiment(){const tight=radio('tight'),hyp=c.hypotheses[tight]||'';form.elements.hypothesis.value=hyp;const wrap=root.querySelector('[data-experiment-options]');wrap.innerHTML=(c.experiments[tight]||[]).map((t,i)=>`<label class="choice"><input type="radio" name="experiment" value="${i}"><span>${t}</span></label>`).join('')}function textList(keys,map){return keys.map(k=>map[k]||k).join(' · ')||c.empty}function make(){const tight=radio('tight'),pres=checked('preserve'),evidence=checked('evidence'),expCustom=val('experiment_custom'),expIndex=radio('experiment'),exp=expCustom||((c.experiments[tight]||[])[+expIndex]||c.empty),signals=['mind','body','state','desire'].filter(k=>val(k)).map(k=>`<b>${c.signal_names[k]}:</b> ${val(k)}`).join('<br>')||c.empty;const values={question:val('question'),tight:c.tight_names[tight]||c.empty,preserve:textList(pres,c.preserve_names)+(val('preserve_other')?' · '+val('preserve_other'):''),unknown:val('unknown')||c.empty,signals,hypothesis:val('hypothesis'),experiment:exp,boundary:val('boundary')||c.empty,evidence:textList(evidence,c.evidence_names)};Object.entries(values).forEach(([k,v])=>{root.querySelector(`[data-out="${k}"]`).innerHTML=v});form.hidden=true;root.querySelector('.progress-wrap').hidden=true;result.hidden=false;result.scrollIntoView({behavior:'smooth',block:'start'})}root.querySelector('[data-start]').addEventListener('click',()=>{workspace.hidden=false;show(1)});next.addEventListener('click',()=>{if(!validate())return;if(current===3){populateExperiment();show(4)}else if(current===4)make();else show(current+1)});back.addEventListener('click',()=>show(current-1));root.querySelector('[data-print]').addEventListener('click',()=>window.print());root.querySelector('[data-copy]').addEventListener('click',async()=>{const text=root.querySelector('[data-card]').innerText;try{await navigator.clipboard.writeText(text);root.querySelector('[data-copy-status]').textContent=c.copied}catch(e){root.querySelector('[data-copy-status]').textContent=text}});root.querySelector('[data-restart]').addEventListener('click',()=>{form.reset();form.hidden=false;result.hidden=true;root.querySelector('.progress-wrap').hidden=false;show(1)});})();''')
    page.append('</script>')
    return '\n'.join(page)+'\n'

CSS=r'''
.experiment-page{background:#0b0711;color:var(--ink)}.experiment-hero{min-height:88svh;display:grid;align-items:end;padding:150px clamp(22px,7vw,100px) 82px;position:relative;overflow:hidden;background:radial-gradient(circle at 78% 28%,rgba(143,75,211,.34),transparent 26%),radial-gradient(circle at 88% 15%,rgba(241,218,69,.12),transparent 18%),linear-gradient(145deg,#09050f,#1a0d2a 62%,#09050f)}.experiment-hero:after{content:"";position:absolute;right:-8vw;top:14%;width:42vw;height:42vw;border:1px solid rgba(241,218,69,.22);transform:rotate(18deg);box-shadow:0 0 0 40px rgba(133,75,190,.06),0 0 0 90px rgba(133,75,190,.04);pointer-events:none}.experiment-hero-inner{max-width:920px;position:relative;z-index:1}.experiment-label{color:var(--gold);font-size:12px;letter-spacing:.16em;text-transform:uppercase}.experiment-hero h1{font:500 clamp(60px,10vw,132px)/.84 var(--serif);letter-spacing:-.05em;margin:20px 0 30px;max-width:850px}.experiment-lead{font:400 clamp(22px,3vw,35px)/1.25 var(--serif);max-width:820px}.experiment-promise{color:var(--solar);margin-top:28px}.experiment-meta{display:flex;flex-wrap:wrap;gap:9px 28px;color:var(--muted);font-size:13px;margin:18px 0 30px}.exp-button{min-height:50px;border:1px solid var(--line);border-radius:999px;padding:0 23px;background:transparent;color:var(--ink);font:600 12px var(--sans);letter-spacing:.08em;text-transform:uppercase;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;text-decoration:none}.exp-button:hover{border-color:var(--gold);transform:translateY(-1px)}.exp-button.primary{background:var(--solar);border-color:var(--solar);color:#160d20}.exp-button.quiet{border:0;color:var(--muted)}.experiment-about{display:grid;grid-template-columns:.8fr 1.2fr;gap:clamp(35px,7vw,100px);padding:90px clamp(22px,7vw,100px);max-width:1300px;margin:auto}.experiment-about h2,.result-head h2{font:500 clamp(40px,6vw,76px)/.95 var(--serif);margin:16px 0}.experiment-about>p{color:var(--muted);font-size:18px}.experiment-workspace{padding:90px clamp(18px,6vw,80px) 120px;background:#efe8dc;color:#21152a;scroll-margin-top:70px}.progress-wrap{max-width:1050px;margin:0 auto 44px}.progress{list-style:none;padding:0;margin:0;display:grid;grid-template-columns:repeat(5,1fr);gap:8px}.progress li{opacity:.44}.progress li.active{opacity:1}.progress span{display:block;font:italic 24px var(--serif);color:#663783}.progress b{font-size:11px;text-transform:uppercase;letter-spacing:.08em}.progress-bar{height:2px;background:rgba(49,27,61,.14);margin-top:18px}.progress-bar i{display:block;height:100%;width:0;background:#663783;transition:width .3s}.experiment-workspace form{max-width:1050px;margin:auto}.exp-step{border:0;padding:0;margin:0}.exp-step legend{font:500 clamp(42px,6vw,72px)/.95 var(--serif);letter-spacing:-.03em;max-width:850px}.step-help{color:#685c6e;max-width:720px;margin:20px 0 38px}.field{display:block;margin:28px 0}.field>span,.group-label{display:block;font-weight:700;margin-bottom:10px}.field textarea{width:100%;resize:vertical;min-height:95px;padding:17px;border:1px solid rgba(55,30,71,.25);background:rgba(255,255,255,.5);color:#21152a;font:400 16px/1.55 var(--sans);border-radius:2px}.field textarea:focus{outline:3px solid rgba(95,44,160,.25);border-color:#663783}.field-group{margin:30px 0}.choice-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.choice{position:relative}.choice input{position:absolute;opacity:0;pointer-events:none}.choice span{display:flex;align-items:center;min-height:62px;padding:14px 17px;border:1px solid rgba(55,30,71,.22);background:rgba(255,255,255,.38);cursor:pointer}.choice input:checked+span{background:#5f2ca0;color:white;border-color:#5f2ca0}.choice input:focus-visible+span{outline:3px solid #d0aaff;outline-offset:2px}.signal-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 24px}.form-nav{max-width:1050px;margin:42px auto 0;display:flex;justify-content:space-between;gap:12px}.form-nav .exp-button{border-color:rgba(55,30,71,.3);color:#2a1933}.form-nav .primary{color:#160d20;border-color:#c9ad17}.form-error{color:#8b2032;min-height:24px;font-weight:600}.exp-result{max-width:1180px;margin:auto}.result-head{max-width:760px;margin-bottom:40px}.result-head>p:last-child{color:#685c6e}.experiment-card{background:#100918;color:#f7f1e8;border:1px solid rgba(95,44,160,.45);padding:clamp(24px,5vw,58px);box-shadow:18px 18px 0 #d7c4ec}.card-mark{color:var(--gold);font-size:10px;letter-spacing:.16em;margin-bottom:35px}.card-grid{display:grid;grid-template-columns:1fr 1fr;gap:1px;background:rgba(225,207,255,.18)}.card-item{background:#100918;padding:25px}.card-item h3{font:600 11px var(--sans);letter-spacing:.12em;text-transform:uppercase;color:var(--gold);margin:0 0 12px}.card-item div{font:400 20px/1.35 var(--serif)}.card-question,.card-hypothesis,.card-experiment,.card-signals{grid-column:1/-1}.card-review .review-choices{display:grid;gap:6px}.card-review .choice span{min-height:42px;background:#160d20;border-color:rgba(225,207,255,.2);font:400 13px var(--sans)}.experiment-card footer{display:flex;justify-content:space-between;gap:20px;color:#a99dae;font-size:11px;margin-top:30px}.result-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:35px}.result-actions .exp-button:not(.primary){border-color:rgba(55,30,71,.3);color:#2a1933}.copy-status{min-height:24px;color:#5f2ca0}.after-card{margin-top:60px;padding:35px;border-top:1px solid rgba(55,30,71,.25)}.after-card h3{font:500 38px/1 var(--serif);margin:0 0 15px}.after-card p{max-width:760px;color:#685c6e}.after-card>div{display:flex;flex-wrap:wrap;gap:10px;margin-top:25px}.after-card .exp-button:not(.primary){border-color:rgba(55,30,71,.3);color:#2a1933}@media(max-width:760px){.experiment-hero{min-height:auto;padding-top:130px}.experiment-hero:after{width:75vw;height:75vw;right:-35vw}.experiment-about{grid-template-columns:1fr}.progress b{display:none}.progress{gap:3px}.choice-grid,.signal-grid,.card-grid{grid-template-columns:1fr}.card-question,.card-hypothesis,.card-experiment,.card-signals{grid-column:auto}.experiment-card{box-shadow:8px 8px 0 #d7c4ec}.form-nav{position:sticky;bottom:10px;background:rgba(239,232,220,.94);padding:10px 0}.experiment-card footer{flex-direction:column}.result-actions,.after-card>div{display:grid}.exp-button{width:100%}}@media print{.site-header,.site-footer,.experiment-hero,.experiment-about,.progress-wrap,.result-head,.result-actions,.after-card,.copy-status{display:none!important}.experiment-workspace{padding:0;background:white}.experiment-card{box-shadow:none;border:1px solid #333;print-color-adjust:exact;-webkit-print-color-adjust:exact}.experiment-card .choice{display:none}.experiment-card .choice:has(input:checked){display:block}body{background:white}}
'''

for lang in ('ru','en'):
    name='page-next-chapter-experiment.hbs' if lang=='ru' else 'page-next-chapter-experiment-en.hbs'
    (THEME/name).write_text(build(lang))
(THEME/'assets/css/experiment.css').write_text(CSS)
print('created experiment templates and stylesheet')
