// AmosCommissionModal — the brief composer.
// Lets a signed-in reader submit a question to Amos. 250-word cap, live counter,
// off-topic guard, optional preacher/opinion field, optional source-focus chips,
// cost preview, and a confirm-spend handoff to the wallet.

function AmosCommissionModal({ open, onClose, onSubmitted, initialKind }) {
  const w = window.useWallet();
  const C = window.AMOS_COMMISSIONS;
  const [kind, setKind] = React.useState(initialKind || 'reading'); // 'reading' | 'reaction'
  const [brief, setBrief] = React.useState('');
  const [topic, setTopic] = React.useState('');
  const [opinion, setOpinion] = React.useState('');
  const [opinionOpen, setOpinionOpen] = React.useState(false);
  const [sources, setSources] = React.useState(['patristic']);
  const [allowPromotion, setAllowPromotion] = React.useState(true);
  const [guardShown, setGuardShown] = React.useState(true);
  const [softWarning, setSoftWarning] = React.useState(null); // string | null
  const [phase, setPhase] = React.useState('compose'); // 'compose' | 'submitted' | 'submitted-offtopic' | 'submitted-reaction'

  // Reaction-form state
  const [rxUploadKind, setRxUploadKind] = React.useState('video');  // sermon INPUT format: 'video' | 'audio' | 'text'
  const [rxResponseKind, setRxResponseKind] = React.useState('video'); // Amos' RESPONSE format: 'video' | 'audio' | 'paper'
  const [rxUploadName, setRxUploadName] = React.useState('');
  const [rxInputMinutes, setRxInputMinutes] = React.useState(30);
  const [rxInputChars, setRxInputChars] = React.useState(0);
  const [rxSourceTitle, setRxSourceTitle] = React.useState('');
  const [rxSourcePreacher, setRxSourcePreacher] = React.useState('');
  const [rxPosture, setRxPosture] = React.useState('pastoral'); // 'pastoral' | 'balanced' | 'direct'
  const [rxNote, setRxNote] = React.useState('');
  const [rxTextBody, setRxTextBody] = React.useState('');

  React.useEffect(() => {
    if (!open) return;
    setKind(initialKind || 'reading');
    setBrief(''); setTopic(''); setOpinion(''); setOpinionOpen(false);
    setSources(['patristic']); setAllowPromotion(true);
    setSoftWarning(null); setPhase('compose');
    setRxUploadKind('video'); setRxResponseKind('video');
    setRxUploadName(''); setRxInputMinutes(30);
    setRxInputChars(0); setRxSourceTitle(''); setRxSourcePreacher('');
    setRxPosture('pastoral'); setRxNote(''); setRxTextBody('');
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose, initialKind]);

  const words = C.countWords(brief) + C.countWords(opinion);
  const overLimit = words > C.MAX_WORDS;
  const canSubmit = brief.trim().length >= 40 && !overLimit;

  const rxEstimatedMinutes = React.useMemo(() => {
    if (rxUploadKind === 'text') {
      return rxInputChars > 0 ? Math.max(1, Math.round(rxInputChars / C.REACTION_CHARS_PER_MIN)) : 0;
    }
    return rxInputMinutes;
  }, [rxUploadKind, rxInputMinutes, rxInputChars]);

  const rxCost = React.useMemo(() => {
    return C.reactionCost({
      responseKind: rxResponseKind,
      inputMinutes: rxUploadKind === 'text' ? null : rxInputMinutes,
      inputChars:   rxUploadKind === 'text' ? rxInputChars : null
    });
  }, [rxResponseKind, rxUploadKind, rxInputMinutes, rxInputChars]);

  if (!open) return null;

  const toggleSource = (key) => {
    setSources(s => s.includes(key) ? s.filter(k => k !== key) : [...s, key]);
  };

  const sourceOptions = [
    { key:'patristic',    label:'Pre-Nicene Fathers',         hint:'Didache, Ignatius, Justin, Tertullian, Cyprian' },
    { key:'parabiblical', label:'Preterocanonical',            hint:'1 Enoch, Jubilees, Tobit, Sirach, Testaments' },
    { key:'qumran',       label:'Zadokite Settlement',         hint:'1QS, 1QHa, 1QSb, Songs of the Sabbath' },
    { key:'greek',        label:'Greek New Testament',         hint:'Critical edition · apparatus' },
    { key:'hebrew',       label:'Hebrew Bible',                hint:'Masoretic · LXX comparanda' }
  ];

  const submit = () => {
    const combined = (topic + ' ' + brief + ' ' + opinion).toLowerCase();
    const isOffTopic = C.looksOffTopic(combined);

    if (isOffTopic) {
      // Don't charge. Save as 'off-topic' so the Drafts rail shows Amos's polite refusal.
      const entry = {
        id: 'c-' + Date.now(),
        createdAt: Date.now(),
        status: 'off-topic',
        brief: brief.trim(),
        topic: topic.trim(),
        opinion: opinion.trim(),
        sources,
        words,
        credits: 0,
        amosReply: 'Friend, this is outside the library I was given. I read only what is shelved on The Amos Project — the fathers, the preterocanonical books, the Zadokite hymns, the Greek and Hebrew scriptures. On this topic the shelves are silent, and I will not invent what the sources do not contain. If you rephrase your question so it touches these texts, I will gladly answer.',
        submittedBy: 'You',
        submittedByRole: 'Reader'
      };
      C.store.add(entry);
      setPhase('submitted-offtopic');
      if (onSubmitted) onSubmitted(entry);
      return;
    }

    // Charge via wallet confirm flow
    w.requestSpend({
      credits: C.ARTICLE_COST,
      label: 'Amos commission \u2014 ' + (topic.trim() || brief.slice(0, 40).trim() + '\u2026'),
      description: 'Amos drafts your piece from the Library, then it enters editorial review before publication.',
      onConfirm: () => {
        const id = 'c-' + Date.now();
        const entry = {
          id,
          createdAt: Date.now(),
          status: 'generating',
          brief: brief.trim(),
          topic: topic.trim(),
          opinion: opinion.trim(),
          sources,
          allowPromotion,
          words,
          credits: C.ARTICLE_COST,
          submittedBy: 'You',
          submittedByRole: 'Reader'
        };
        C.store.add(entry);

        // Simulated generation: after a short delay, flip to 'yours' (or 'yours-private' if opted out).
        setTimeout(() => {
          const stub = C.generateStubArticle(entry);
          C.store.update(id, {
            status: allowPromotion ? 'yours' : 'yours-private',
            title: stub.title,
            subtitle: stub.subtitle,
            resultBody: stub
          });
        }, 9200);

        setPhase('submitted');
        if (onSubmitted) onSubmitted(entry);
      }
    });
  };

  const rxCanSubmit = (
    (rxUploadKind === 'text'
      ? rxInputChars >= 400
      : (rxInputMinutes >= 2 && rxInputMinutes <= C.MAX_REACTION_MINUTES))
    && rxSourceTitle.trim().length >= 2
  );

  // Simulated file pick
  const pickFakeFile = () => {
    const samples = rxUploadKind === 'video'
      ? ['sunday-sermon-apr-12.mp4', 'easter-message-2026.mov', 'sermon-recording.mp4']
      : rxUploadKind === 'audio'
      ? ['sermon-audio.mp3', 'podcast-episode-44.m4a']
      : ['sermon-manuscript.pdf', 'teaching-notes.docx'];
    setRxUploadName(samples[Math.floor(Math.random()*samples.length)]);
    if (rxUploadKind === 'text') setRxInputChars(Math.floor(Math.random()*20000)+4500);
    else setRxInputMinutes(Math.floor(Math.random()*55)+12);
  };

  const submitReaction = () => {
    w.requestSpend({
      credits: rxCost,
      label: 'Amos reaction \u2014 ' + (rxSourceTitle.trim() || 'sermon'),
      description: 'Amos watches the sermon and produces a finished reaction video. Usually under an hour; longer inputs can take up to two.',
      onConfirm: () => {
        const id = 'c-' + Date.now();
        const entry = {
          id,
          createdAt: Date.now(),
          kind: 'reaction',
          status: 'generating',
          title: 'Reaction to \u201c' + rxSourceTitle.trim() + '\u201d',
          sourceTitle: rxSourceTitle.trim(),
          sourcePreacher: rxSourcePreacher.trim(),
          uploadKind: rxUploadKind,
          uploadName: rxUploadName || ('sermon.' + (rxUploadKind === 'text' ? 'txt' : rxUploadKind === 'audio' ? 'mp3' : 'mp4')),
          inputMinutes: rxUploadKind === 'text' ? null : rxInputMinutes,
          inputChars:   rxUploadKind === 'text' ? rxInputChars : null,
          responseKind: rxResponseKind,
          posture: rxPosture,
          note: rxNote.trim(),
          allowPromotion,
          credits: rxCost,
          submittedBy: 'You',
          submittedByRole: 'Reader'
        };
        C.store.add(entry);
        // Simulated render: flip to 'yours' after a few seconds (in production: up to 1h)
        setTimeout(() => {
          C.store.update(id, { status: allowPromotion ? 'yours' : 'yours-private' });
        }, 11000);
        setPhase('submitted-reaction');
        if (onSubmitted) onSubmitted(entry);
      }
    });
  };

  // ── Submitted success screen ────────────────────────
  if (phase === 'submitted' || phase === 'submitted-offtopic' || phase === 'submitted-reaction') {
    return React.createElement('div', { className:'amos-cm-backdrop', onClick:onClose },
      React.createElement('div', { className:'amos-cm', onClick: e=>e.stopPropagation() },
        React.createElement('div', { className:'amos-cm-success' },
          React.createElement('div', { className:'seal' }, 'C'),
          phase === 'submitted-reaction' ? React.createElement(React.Fragment, null,
            React.createElement('h2', null, 'Amos is sitting down to watch.'),
            React.createElement('p', null,
              'He\u2019ll view the full sermon, mark the places to pause, and record his commentary as a pastoral reaction video. The finished video \u2014 original sermon + Amos\u2019 interruptions \u2014 will land in ',
              React.createElement('b', null, 'Your commissions'),
              ' on the Teachings page. ',
              allowPromotion
                ? 'You\u2019ve allowed our editors to consider it for promotion to the platform feed \u2014 they\u2019ll only reach out if they want to feature it.'
                : 'You\u2019ve asked that this reaction stay private to you.'
            ),
            React.createElement('p', { className:'hint' },
              'Turnaround is usually under an hour; longer sermons can take up to two. We\u2019ll notify you when the video is ready \u2014 you can close this window.'
            )
          ) : phase === 'submitted' ? React.createElement(React.Fragment, null,
            React.createElement('h2', null, 'Amos is reading your brief.'),
            React.createElement('p', null,
              'He is opening the scrolls you asked him to consult. When the draft is ready it will appear in ',
              React.createElement('b', null, 'Your commissions'),
              ' on the Teachings page \u2014 it\u2019s ',
              React.createElement('b', null, 'yours to keep'),
              '. ',
              allowPromotion
                ? 'You\u2019ve allowed our editors to consider it for promotion to the full platform feed. They\u2019ll only reach out if they want to feature it.'
                : 'You\u2019ve asked that this article not be considered for promotion \u2014 it stays private to you.'
            ),
            React.createElement('p', { className:'hint' }, 'Generation usually takes 30\u201390 seconds. You can close this window.')
          ) : React.createElement(React.Fragment, null,
            React.createElement('h2', null, 'Amos set the scroll down.'),
            React.createElement('p', null,
              'Your brief touches material outside the Library. Amos will not draft it — and you were not charged. Rephrase toward the texts on the shelves (fathers, preterocanonical, Zadokite, scripture) and try again.'
            ),
            React.createElement('div', { className:'offtopic-reply' },
              React.createElement('div', { className:'mark' }, 'C'),
              React.createElement('p', null, 'Friend, this is outside the library I was given. I read only what is shelved on The Amos Project. If you rephrase your question so it touches these texts, I will gladly answer.')
            )
          ),
          React.createElement('button', { className:'amos-cm-close-btn', onClick: onClose }, 'Close')
        )
      )
    );
  }

  // ── Compose ─────────────────────────────────────────
  return React.createElement('div', { className:'amos-cm-backdrop', onClick:onClose },
    React.createElement('div', { className:'amos-cm', onClick: e=>e.stopPropagation() },

      React.createElement('div', { className:'amos-cm-head' },
        React.createElement('div', { className:'amos-cm-mark' }, 'C'),
        React.createElement('div', { style:{ flex:1, minWidth:0 } },
          React.createElement('div', { className:'kick' },
            kind === 'reaction' ? 'Commission a reaction video' : 'Commission a reading'
          ),
          React.createElement('h2', null,
            kind === 'reaction'
              ? 'Ask Amos to watch a sermon'
              : 'Ask Amos to write something for you'
          ),
          React.createElement('p', { className:'sub' },
            kind === 'reaction'
              ? 'Upload a sermon \u2014 video, audio, or manuscript. Amos will watch the whole thing, pause to speak where the Library has something to say, and deliver a finished reaction video. Pastoral in tone. Clear on the differences.'
              : 'Tell him what you want to understand. He will answer from the Library \u2014 and only from the Library. The article is yours to keep; our editors may later ask to feature it on the platform.'
          )
        ),
        React.createElement('button', { className:'amos-cm-x', onClick: onClose, 'aria-label':'Close' }, '×')
      ),

      // Format tabs
      React.createElement('div', { className:'amos-cm-tabs' },
        React.createElement('button', {
          className:'amos-cm-tab' + (kind === 'reading' ? ' on' : ''),
          onClick: () => setKind('reading')
        },
          React.createElement('span', { className:'tab-k' }, 'Reading'),
          React.createElement('span', { className:'tab-meta' }, 'text article · from ', C.ARTICLE_COST, ' cr')
        ),
        React.createElement('button', {
          className:'amos-cm-tab' + (kind === 'reaction' ? ' on' : ''),
          onClick: () => setKind('reaction')
        },
          React.createElement('span', { className:'tab-k' }, 'Reaction video'),
          React.createElement('span', { className:'tab-meta' }, 'finished video · from ', C.REACTION_BASE + C.REACTION_PER_MIN * 10, ' cr')
        )
      ),

      // The guard card (dismissable) — reading kind only
      kind === 'reading' && guardShown && React.createElement('div', { className:'amos-cm-guard' },
        React.createElement('div', { className:'amos-cm-guard-icon' }, '!'),
        React.createElement('div', null,
          React.createElement('div', { className:'amos-cm-guard-title' }, 'Amos reads from this Library \u2014 and nothing else.'),
          React.createElement('div', { className:'amos-cm-guard-body' },
            'Ask about the pre-Nicene fathers, the Second Temple world, the Zadokite community, the preterocanonical books, or early Christian liturgy. He will ',
            React.createElement('b', null, 'not'),
            ' draft you a dissertation on ',
            React.createElement('i', null, 'reverse-osmosis membrane fouling in municipal desalination plants'),
            ' \u2014 however catechetical you make it sound. Off-topic briefs are caught before your credits are charged.'
          )
        ),
        React.createElement('button', { className:'amos-cm-guard-x', onClick:()=>setGuardShown(false), 'aria-label':'Dismiss' }, '×')
      ),

      // Form body — reading
      kind === 'reading' && React.createElement('div', { className:'amos-cm-body' },

        React.createElement('label', { className:'amos-cm-label' }, 'One-line topic ',
          React.createElement('span', { className:'hint' }, 'optional \u2014 helps Amos title the piece')
        ),
        React.createElement('input', {
          className:'amos-cm-input',
          placeholder:'e.g. Did the early fathers treat 1 Enoch as scripture?',
          value: topic,
          maxLength: 140,
          onChange: e => setTopic(e.target.value)
        }),

        React.createElement('label', { className:'amos-cm-label' }, 'Your brief',
          React.createElement('span', { className:'hint' }, 'What do you want Amos to work through? Questions, confusions, passages you keep circling.')
        ),
        React.createElement('textarea', {
          className: 'amos-cm-text' + (overLimit ? ' over' : ''),
          rows: 7,
          value: brief,
          onChange: e => setBrief(e.target.value),
          placeholder: 'I preach most weeks and a line from an older preacher keeps coming back to me. He said the church rejected 1 Enoch \u2014 but then I see it in Jude. Tertullian seems to have treated it as scripture. Could you walk me through what the fathers actually said, and what the Library shows about when the reception changed?'
        }),

        // Word counter
        React.createElement('div', { className: 'amos-cm-count' + (overLimit ? ' over' : '') },
          React.createElement('span', null, words, ' / ', C.MAX_WORDS, ' words'),
          overLimit
            ? React.createElement('span', { className:'err' }, 'Over the limit \u2014 trim ', words - C.MAX_WORDS, ' words to continue')
            : React.createElement('span', { className:'ok' }, C.MAX_WORDS - words, ' words remaining')
        ),

        // Optional: preacher / opinion to react to
        React.createElement('div', { className:'amos-cm-accordion' },
          React.createElement('button', {
            className:'amos-cm-acc-trigger',
            onClick: () => setOpinionOpen(o => !o)
          },
            React.createElement('span', null, opinionOpen ? '\u2212' : '+'),
            'Paste a quote, sermon clip, or a preacher\u2019s claim for Amos to react to ',
            React.createElement('span', { className:'hint' }, 'optional')
          ),
          opinionOpen && React.createElement('textarea', {
            className:'amos-cm-text opinion',
            rows: 4,
            value: opinion,
            onChange: e => setOpinion(e.target.value),
            placeholder: 'Paste the quote or the claim here. Amos will weigh it against the sources on the shelf \u2014 he won\u2019t pretend to know its full context, only what the Library can say about it.'
          })
        ),

        // Source focus
        React.createElement('label', { className:'amos-cm-label' }, 'Source focus ',
          React.createElement('span', { className:'hint' }, 'which shelves Amos should prioritise \u2014 he can still cross over when needed')
        ),
        React.createElement('div', { className:'amos-cm-sources' },
          ...sourceOptions.map(opt => React.createElement('button', {
            key: opt.key,
            className: 'amos-cm-src' + (sources.includes(opt.key) ? ' on' : ''),
            onClick: () => toggleSource(opt.key)
          },
            React.createElement('div', { className:'src-label' }, opt.label),
            React.createElement('div', { className:'src-hint' }, opt.hint)
          ))
        ),

        // Promotion preference
        React.createElement('div', { className:'amos-cm-promo' },
          React.createElement('button', {
            className: 'amos-cm-promo-toggle' + (allowPromotion ? ' on' : ''),
            role: 'switch',
            'aria-checked': allowPromotion,
            onClick: () => setAllowPromotion(v => !v)
          },
            React.createElement('span', { className:'track' },
              React.createElement('span', { className:'thumb' })
            )
          ),
          React.createElement('div', { className:'amos-cm-promo-copy' },
            React.createElement('div', { className:'amos-cm-promo-title' },
              'Allow editors to consider this for promotion'
            ),
            React.createElement('div', { className:'amos-cm-promo-body' },
              allowPromotion
                ? 'The article is yours either way. Our editors may reach out if they think your reading deserves to be featured on the platform\u2019s Teachings feed \u2014 nothing happens without your say-so.'
                : 'Your article stays private to you. Editors will not see it and will not consider it for the platform feed.'
            )
          )
        )
      ),

      // Form body — reaction
      kind === 'reaction' && React.createElement('div', { className:'amos-cm-body rx' },

        // What this is
        React.createElement('div', { className:'amos-cm-rx-explainer' },
          React.createElement('div', { className:'rx-ex-title' },
            React.createElement('span', { className:'seal' }, 'C'),
            'What you get'
          ),
          React.createElement('ul', { className:'rx-ex-list' },
            React.createElement('li', null,
              React.createElement('b', null, 'A finished response.'), ' The original sermon plays through (or is transcribed). Amos pauses it — a dozen or more times — to speak. Pastoral in tone. Clear on the differences. Every pause cites the Library.'),
            React.createElement('li', null,
              React.createElement('b', null, 'Delivered asynchronously.'), ' Usually under an hour. Longer sermons can take up to two. We notify you when it\u2019s ready.'),
            React.createElement('li', null,
              React.createElement('b', null, 'Yours to keep.'), ' You can allow editors to consider it for promotion on the platform feed, or keep it private — your choice.')
          )
        ),

        // Response format picker — Amos' OUTPUT
        React.createElement('label', { className:'amos-cm-label' }, 'How should Amos respond? ',
          React.createElement('span', { className:'hint' }, 'video is fullest; audio and paper are lighter')
        ),
        React.createElement('div', { className:'amos-cm-rx-kind' },
          ...[
            { key:'video', label:'Video reaction', hint: 'from ' + C.REACTION_PRICING.video.minimum + ' cr · +' + C.REACTION_PRICING.video.perMin + ' cr/min over 5' },
            { key:'audio', label:'Audio reaction', hint: 'from ' + C.REACTION_PRICING.audio.minimum + ' cr · +' + C.REACTION_PRICING.audio.perMin + ' cr/min over 5' },
            { key:'paper', label:'Written reaction', hint: 'from ' + C.REACTION_PRICING.paper.minimum + ' cr · +' + C.REACTION_PRICING.paper.perMin + ' cr/min over 5' }
          ].map(opt => React.createElement('button', {
            key: opt.key,
            className: 'amos-cm-rx-kind-btn' + (rxResponseKind === opt.key ? ' on' : ''),
            onClick: () => setRxResponseKind(opt.key)
          },
            React.createElement('div', { className:'rxk-label' }, opt.label),
            React.createElement('div', { className:'rxk-hint' }, opt.hint)
          ))
        ),

        // Upload source
        React.createElement('label', { className:'amos-cm-label' }, 'Upload a sermon ',
          React.createElement('span', { className:'hint' }, 'video, audio, or written manuscript')
        ),
        React.createElement('div', { className:'amos-cm-rx-kind' },
          ...[
            { key:'video', label:'Video', hint:'.mp4 · .mov · up to 2 GB' },
            { key:'audio', label:'Audio', hint:'.mp3 · .wav · .m4a' },
            { key:'text',  label:'Written', hint:'.pdf · .docx · paste' }
          ].map(opt => React.createElement('button', {
            key: opt.key,
            className: 'amos-cm-rx-kind-btn' + (rxUploadKind === opt.key ? ' on' : ''),
            onClick: () => { setRxUploadKind(opt.key); setRxUploadName(''); }
          },
            React.createElement('div', { className:'rxk-label' }, opt.label),
            React.createElement('div', { className:'rxk-hint' }, opt.hint)
          ))
        ),

        // File drop zone (simulated)
        rxUploadKind !== 'text' && React.createElement('div', {
          className: 'amos-cm-rx-drop' + (rxUploadName ? ' has-file' : ''),
          onClick: pickFakeFile
        },
          rxUploadName
            ? React.createElement(React.Fragment, null,
                React.createElement('div', { className:'rxd-file' },
                  React.createElement('span', { className:'rxd-icon' }, rxUploadKind === 'video' ? '▶' : '♪'),
                  React.createElement('div', { className:'rxd-meta' },
                    React.createElement('div', { className:'rxd-name' }, rxUploadName),
                    React.createElement('div', { className:'rxd-sub' }, rxInputMinutes, ' min · detected runtime')
                  )
                ),
                React.createElement('button', {
                  className:'rxd-replace',
                  onClick: (e) => { e.stopPropagation(); setRxUploadName(''); }
                }, 'Replace')
              )
            : React.createElement(React.Fragment, null,
                React.createElement('div', { className:'rxd-cloud' }, '↑'),
                React.createElement('div', { className:'rxd-main' }, 'Drop a ', rxUploadKind, ' file here, or click to browse'),
                React.createElement('div', { className:'rxd-hint' }, 'Demo — any click attaches a placeholder file so you can see the flow.')
              )
        ),

        // Text kind — paste / length input
        rxUploadKind === 'text' && React.createElement(React.Fragment, null,
          React.createElement('textarea', {
            className:'amos-cm-text',
            rows: 7,
            value: rxTextBody,
            onChange: e => {
              setRxTextBody(e.target.value);
              setRxInputChars(e.target.value.length);
            },
            placeholder: 'Paste the sermon manuscript here, or attach a file above. Amos reads it like a transcript and produces his reaction keyed to the places where he would speak.'
          }),
          React.createElement('div', { className:'amos-cm-count' },
            React.createElement('span', null, rxInputChars.toLocaleString(), ' characters'),
            React.createElement('span', { className:'ok' },
              '≈ ', rxEstimatedMinutes || 0, ' min of sermon')
          ),
          React.createElement('div', { className:'amos-cm-rx-orfile' },
            React.createElement('span', null, 'or attach a document instead'),
            React.createElement('button', { className:'rxd-browse', onClick: pickFakeFile },
              rxUploadName || 'Browse files'
            )
          )
        ),

        // Length slider (for video/audio)
        rxUploadKind !== 'text' && rxUploadName && React.createElement('div', { className:'amos-cm-rx-length' },
          React.createElement('div', { className:'rxl-head' },
            React.createElement('span', null, 'Sermon length'),
            React.createElement('b', null, rxInputMinutes, ' min')
          ),
          React.createElement('input', {
            type:'range', min: 2, max: C.MAX_REACTION_MINUTES, step: 1,
            value: rxInputMinutes,
            onChange: e => setRxInputMinutes(parseInt(e.target.value, 10)),
            className:'amos-cm-rx-slider'
          }),
          React.createElement('div', { className:'rxl-ticks' },
            React.createElement('span', null, '2 min'),
            React.createElement('span', null, '30 min'),
            React.createElement('span', null, '60 min'),
            React.createElement('span', null, '2 hr')
          )
        ),

        // Source identification
        React.createElement('label', { className:'amos-cm-label' }, 'What is this sermon?'),
        React.createElement('input', {
          className:'amos-cm-input',
          placeholder:'Sermon title — e.g. “The Wrath-Drinking Son”',
          value: rxSourceTitle,
          maxLength: 140,
          onChange: e => setRxSourceTitle(e.target.value)
        }),
        React.createElement('input', {
          className:'amos-cm-input',
          style:{ marginTop: 8 },
          placeholder:'Preacher and congregation (optional) — e.g. Pastor Daniel Reeve, Grace Covenant',
          value: rxSourcePreacher,
          maxLength: 140,
          onChange: e => setRxSourcePreacher(e.target.value)
        }),

        // Posture dial
        React.createElement('label', { className:'amos-cm-label' }, 'Amos\u2019 posture ',
          React.createElement('span', { className:'hint' }, 'how direct should he be with the preacher?')
        ),
        React.createElement('div', { className:'amos-cm-rx-posture' },
          ...[
            { key:'pastoral', label:'Pastoral', hint:'Charitable first. Names differences gently, honors the ministry.' },
            { key:'balanced', label:'Balanced', hint:'Straight down the middle. Commends and corrects in equal measure.' },
            { key:'direct',   label:'Direct',   hint:'Still pastoral, but willing to stop the tape and say "no, the record says otherwise."' }
          ].map(opt => React.createElement('button', {
            key: opt.key,
            className: 'amos-cm-rx-post' + (rxPosture === opt.key ? ' on' : ''),
            onClick: () => setRxPosture(opt.key)
          },
            React.createElement('div', { className:'post-k' }, opt.label),
            React.createElement('div', { className:'post-hint' }, opt.hint)
          ))
        ),

        // Optional note
        React.createElement('label', { className:'amos-cm-label' }, 'A note for Amos ',
          React.createElement('span', { className:'hint' }, 'optional — anything you want him to pay attention to')
        ),
        React.createElement('textarea', {
          className:'amos-cm-text',
          rows: 3,
          value: rxNote,
          onChange: e => setRxNote(e.target.value),
          placeholder: 'e.g. He spends a lot of time on Matthew 13 — I\u2019d love to hear what the Library says about the parables of the kingdom.'
        }),

        // Promotion preference (shared)
        React.createElement('div', { className:'amos-cm-promo' },
          React.createElement('button', {
            className: 'amos-cm-promo-toggle' + (allowPromotion ? ' on' : ''),
            role: 'switch',
            'aria-checked': allowPromotion,
            onClick: () => setAllowPromotion(v => !v)
          },
            React.createElement('span', { className:'track' },
              React.createElement('span', { className:'thumb' })
            )
          ),
          React.createElement('div', { className:'amos-cm-promo-copy' },
            React.createElement('div', { className:'amos-cm-promo-title' },
              'Allow editors to consider this for promotion'
            ),
            React.createElement('div', { className:'amos-cm-promo-body' },
              allowPromotion
                ? 'The reaction is yours either way. Editors may ask to feature it on the platform feed if they find it useful for other pastors — nothing happens without your say-so.'
                : 'Your reaction stays private to you. Editors will not see it and will not consider it for the platform feed.'
            )
          )
        )
      ),

      // Footer — cost + submit (branches by kind)
      React.createElement('div', { className:'amos-cm-foot' },
        React.createElement('div', { className:'amos-cm-cost' },
          React.createElement('div', { className:'c-row' },
            React.createElement('span', { className:'c-label' },
              kind === 'reaction' ? 'Reaction cost' : 'Commission cost'
            ),
            React.createElement('span', { className:'c-val' },
              React.createElement('b', null, kind === 'reaction' ? rxCost : C.ARTICLE_COST),
              ' cr'
            )
          ),
          kind === 'reaction' && React.createElement('div', { className:'c-row muted' },
            React.createElement('span', null,
              (rxResponseKind === 'video' ? 'Video' : rxResponseKind === 'audio' ? 'Audio' : 'Written'),
              ' — ', C.REACTION_PRICING[rxResponseKind].minimum, ' cr up to 5 min, then +',
              C.REACTION_PRICING[rxResponseKind].perMin, ' cr/min'
            ),
            React.createElement('span', null,
              rxUploadKind === 'text'
                ? (rxInputChars.toLocaleString() + ' chars ≈ ' + (rxEstimatedMinutes || 0) + ' min')
                : (rxInputMinutes + ' min input')
            )
          ),
          React.createElement('div', { className:'c-row muted' },
            React.createElement('span', null, 'Your balance'),
            React.createElement('span', null, (w ? w.balance : 0), ' cr')
          )
        ),
        React.createElement('div', { className:'amos-cm-foot-actions' },
          React.createElement('button', { className:'amos-cm-cancel', onClick: onClose }, 'Cancel'),
          kind === 'reaction'
            ? React.createElement('button', {
                className: 'amos-cm-submit' + (!rxCanSubmit ? ' disabled' : ''),
                disabled: !rxCanSubmit,
                onClick: submitReaction
              },
                'Send to Amos',
                React.createElement('span', { className:'meta' }, rxCost, ' cr')
              )
            : React.createElement('button', {
                className: 'amos-cm-submit' + (!canSubmit ? ' disabled' : ''),
                disabled: !canSubmit,
                onClick: submit
              },
                'Commission the article',
                React.createElement('span', { className:'meta' }, C.ARTICLE_COST, ' cr')
              )
        )
      )
    )
  );
}
Object.assign(window, { AmosCommissionModal });
