/* ============================================================
   Devonew — member screen · Mural de Testemunhos
   Aba "Mural" (feed de testemunhos aprovados) + "Conte sua Benção"
   (formulário de envio com moderação prévia e opção de anonimato).
   ============================================================ */
const { useState: useStateMT } = React;

/* ---------- one mural card ---------- */
function TestiCard({ t, reacted, onReact }) {
  const d = window.TESTI.displayName(t);
  const c = window.TESTI.catOf(t.cat);
  return (
    <article className="testi-card">
      <div className="testi-head">
        <div className={`avatar ${d.anon ? 'anon' : ''}`}>{d.initials}</div>
        <div className="testi-id">
          <div className="testi-name">{d.name}</div>
          <div className="testi-when">{window.TESTI.relTime(t.ts)}</div>
        </div>
        <span className="tcat"><Icon name={c.icon} size={13}/>{c.label}</span>
      </div>
      <h3 className="testi-title">{t.title}</h3>
      <p className="testi-body">{t.body}</p>
      <div className="testi-foot">
        <button className={`glory-btn ${reacted ? 'on' : ''}`} onClick={() => onReact(t.id)}>
          <Icon name="hands" size={17}/>Glória a Deus!
        </button>
        <span className="glory-count">{t.reactions.toLocaleString('pt-BR')} {t.reactions === 1 ? 'irmão celebrou' : 'celebraram'}</span>
      </div>
    </article>
  );
}

/* ---------- my pending card (status only, no reactions) ---------- */
function PendingCard({ t }) {
  const c = window.TESTI.catOf(t.cat);
  return (
    <article className="testi-card is-pending">
      <div className="testi-head">
        <div className="avatar">{t.anon ? '✦' : t.initials}</div>
        <div className="testi-id">
          <div className="testi-name">{t.anon ? 'Você · anônimo' : 'Você'}</div>
          <div className="testi-when">Enviado {window.TESTI.relTime(t.ts)}</div>
        </div>
        <span className="tcat"><Icon name={c.icon} size={13}/>{c.label}</span>
      </div>
      <h3 className="testi-title">{t.title}</h3>
      <p className="testi-body">{t.body}</p>
      <div className="testi-foot">
        <span className="pending-flag"><Icon name="clock" size={14}/>Em análise pela liderança</span>
      </div>
    </article>
  );
}

/* ---------- "Conte sua Benção" form ---------- */
function TestiForm({ onSubmit, toast }) {
  const [title, setTitle] = useStateMT('');
  const [cat, setCat] = useStateMT('');
  const [body, setBody] = useStateMT('');
  const [anon, setAnon] = useStateMT(false);
  const [sent, setSent] = useStateMT(false);

  const submit = (e) => {
    e.preventDefault();
    if (!title.trim()) { toast('Dê um título ao seu testemunho'); return; }
    if (!cat) { toast('Escolha uma área'); return; }
    if (body.trim().length < 20) { toast('Conte um pouco mais do que Deus fez'); return; }
    onSubmit({ title: title.trim(), cat, body: body.trim(), anon });
    setSent(true);
  };

  if (sent) {
    return (
      <div className="card pad">
        <div className="tf-sent">
          <div className="tf-sent-ico"><Icon name="check" size={32}/></div>
          <h3>Recebido com gratidão!</h3>
          <p>Seu testemunho foi enviado para a liderança. Assim que for aprovado, ele aparece no mural para abençoar toda a igreja.</p>
          <span className="xp-note"><Icon name="sparkle" size={15}/>+20 XP quando for aprovado</span>
          <button className="btn btn-primary" onClick={() => { setSent(false); setTitle(''); setCat(''); setBody(''); setAnon(false); }}>
            Compartilhar outro testemunho
          </button>
        </div>
      </div>
    );
  }

  return (
    <form className="card pad testi-form" onSubmit={submit}>
      <label className="tf-lab" htmlFor="tf-title">Título do testemunho <span className="req">*</span></label>
      <input id="tf-title" className="tf-input" maxLength={70} value={title} onChange={(e) => setTitle(e.target.value)}
        placeholder="Ex.: A cura do meu filho · Porta de emprego aberta" />

      <span className="tf-lab">Área / categoria <span className="req">*</span></span>
      <div className="tf-cats">
        {window.TESTI.CATS.map((c) => (
          <button type="button" key={c.id} className={`tf-cat ${cat === c.id ? 'on' : ''}`} onClick={() => setCat(c.id)}>
            <Icon name={c.icon} size={15}/>{c.label}
          </button>
        ))}
      </div>

      <label className="tf-lab" htmlFor="tf-body">O relato <span className="req">*</span></label>
      <textarea id="tf-body" className="tf-input tf-textarea" maxLength={900} value={body} onChange={(e) => setBody(e.target.value)}
        placeholder="Escreva, com as suas palavras, o que Deus fez na sua vida…" />
      <div className="tf-count">{body.length}/900</div>

      <button type="button" className={`tf-anon ${anon ? 'on' : ''}`} onClick={() => setAnon((v) => !v)} aria-pressed={anon}>
        <span className="tf-check"><Icon name="check" size={15}/></span>
        <span className="tf-anon-body">
          <span className="tf-anon-t">Publicar de forma anônima</span>
          <span className="tf-anon-s">Seu nome e foto ficam ocultos no mural — aparece apenas “Irmão(ã) em Cristo”.</span>
        </span>
      </button>

      <button className="btn btn-primary tf-submit" type="submit"><Icon name="share" size={17}/>Enviar testemunho</button>
      <p className="tf-fine"><Icon name="shield" size={14}/>Passa por moderação da liderança antes de ir ao ar.</p>
    </form>
  );
}

/* ---------- screen ---------- */
function TestemunhosScreen({ c, testimonies, myReactions, onReact, onSubmit, go, toast }) {
  const [tab, setTab] = useStateMT('mural');

  const approved = testimonies
    .filter((t) => t.status === 'aprovado')
    .sort((a, b) => b.ts - a.ts);
  const minePending = testimonies
    .filter((t) => t.mine && t.status === 'pendente')
    .sort((a, b) => b.ts - a.ts);

  const submitAndGo = (data) => { onSubmit(data); };

  return (
    <div className="col fade-up">
      <button className="btn btn-quiet show-mobile" style={{ marginLeft: -8, marginBottom: 4 }} onClick={() => go('hoje')}>
        <Icon name="chevronL" size={18}/>Hoje
      </button>
      <PageHead title="Mural de Testemunhos" sub="O que Deus tem feito na nossa comunidade." />
      <div className="show-mobile" style={{ marginBottom: 16 }}>
        <h2 className="greet" style={{ fontSize: 26 }}>Testemunhos</h2>
        <p className="greet-sub" style={{ marginBottom: 0 }}>O que Deus tem feito entre nós.</p>
      </div>

      <div className="lead-tabs" style={{ marginBottom: 20 }}>
        <button className={`lead-tab ${tab === 'mural' ? 'active' : ''}`} onClick={() => setTab('mural')}>Mural · {approved.length}</button>
        <button className={`lead-tab ${tab === 'enviar' ? 'active' : ''}`} onClick={() => setTab('enviar')}>Conte sua benção</button>
      </div>

      {tab === 'mural' ? (
        <div className="mural-feed">
          <div className="mural-intro">
            <div className="ico-wrap"><Icon name="hands" size={22}/></div>
            <div>
              <div className="mi-t">Cada testemunho fortalece a fé de alguém</div>
              <div className="mi-s">Leia, celebre com um “Glória a Deus!” e compartilhe a sua própria benção.</div>
            </div>
          </div>

          {minePending.map((t) => <PendingCard key={t.id} t={t} />)}

          {approved.map((t) => (
            <TestiCard key={t.id} t={t} reacted={myReactions.includes(t.id)} onReact={onReact} />
          ))}

          {approved.length === 0 && minePending.length === 0 && (
            <div className="card pad" style={{ textAlign: 'center', color: 'var(--muted)' }}>
              Ainda não há testemunhos no mural. Seja o primeiro a contar o que Deus fez!
            </div>
          )}

          <button className="btn btn-ghost btn-block" style={{ marginTop: 4 }} onClick={() => setTab('enviar')}>
            <Icon name="plus" size={17}/>Compartilhar meu testemunho
          </button>
        </div>
      ) : (
        <TestiForm onSubmit={submitAndGo} toast={toast} />
      )}
    </div>
  );
}

window.TestemunhosScreen = TestemunhosScreen;
