/* The Upper Room — Compose modal: real post creation from the feed. */
const { useState: useCmpState, useRef: useCmpRef } = React;

function ComposeModal({ onClose, onPost }) {
  const bodyRef = useCmpRef(null);
  const verseRef = useCmpRef(null);
  const refRef = useCmpRef(null);
  const [showVerse, setShowVerse] = useCmpState(false);

  const post = () => {
    const body = (bodyRef.current ? bodyRef.current.value : '').trim();
    if (!body) { if (bodyRef.current) bodyRef.current.focus(); return; }
    const vText = showVerse && verseRef.current ? verseRef.current.value.trim() : '';
    const vRef = showVerse && refRef.current ? refRef.current.value.trim() : '';
    onPost({
      id: 'new' + Date.now(),
      author: CURRENT_USER.name, from: CURRENT_USER.from, church: CURRENT_USER.church,
      time: 'now', verified: true,
      body: body,
      verse: (vText ? { text: vText, ref: vRef || 'Scripture' } : null),
      amens: 0, comments: 0,
    });
    onClose();
  };

  return (
    <div className="ur-modal-scrim" onClick={onClose}>
      <div className="card ur-modal" onClick={(e) => e.stopPropagation()}>
        <div className="ur-modal-head">
          <div className="ur-modal-author">
            <Avatar name={CURRENT_USER.name} />
            <div>
              <div className="name">{CURRENT_USER.name}</div>
              <div className="meta">Sharing to the room</div>
            </div>
          </div>
          <button className="ur-modal-x" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>
        </div>

        <textarea ref={bodyRef} className="ur-modal-body" autoFocus
          placeholder="What is the Lord putting on your heart? Share it — and weigh it against the Word."></textarea>

        {showVerse && (
          <div className="ur-modal-verse">
            <textarea ref={verseRef} placeholder="Paste the Scripture you're standing on…"></textarea>
            <input ref={refRef} placeholder="Reference — e.g. Joel 2:28" />
          </div>
        )}

        <div className="ur-modal-foot">
          <button className={'ur-modal-tool' + (showVerse ? ' active' : '')} onClick={() => setShowVerse(!showVerse)}>
            <Icon name="book-open" size={18} />Add a verse
          </button>
          <button className="ur-primary ur-modal-post" onClick={post}>Share the word</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ComposeModal });
