// Modals.jsx — form modals for each help card + donation
const Modal = ({ open, onClose, children }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Fechar">
          <Icon.Close />
        </button>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
};

const FormSubmit = ({ label = 'Enviar' }) => (
  <button type="submit" className="btn btn-primary"
    style={{ marginTop: 8, alignSelf: 'flex-start' }}>
    {label} <Icon.ArrowRight size={16} />
  </button>
);

// Field building blocks (used by FormDoar)
const Field = ({ label, type = 'text', placeholder, required = true, name }) => (
  <div className="form-row">
    <label htmlFor={name}>{label}</label>
    <input id={name} name={name} type={type} placeholder={placeholder} required={required} />
  </div>
);
const Textarea = ({ label, placeholder, name }) => (
  <div className="form-row">
    <label htmlFor={name}>{label}</label>
    <textarea id={name} name={name} placeholder={placeholder} rows="3"></textarea>
  </div>
);

// --- Card 1: Indicar aluno ---
const FormAluno = () => (
  <JotFormEmbed id="261215717055049" title="Indique alguém que deveria estar na Belavista!" />
);

// --- Card 2: Indicar escola ---
const FormEscola = () => (
  <JotFormEmbed id="261216675555058" title="Indicação de Escolas para a Faculdade Belavista" />
);

// --- Card 3: Indicar pessoa para o projeto ---
const FormProjeto = () => (
  <JotFormEmbed id="261216115238045" title="Indicação de Parceiros Estratégicos para a Faculdade Belavista" />
);

// --- Reusable JotForm embed ---
const JOTFORM_SCRIPT = 'https://cdn.jotfor.ms/s/umd/latest/for-form-embed-handler.js';
const JotFormEmbed = ({ id, title, height = 539 }) => {
  React.useEffect(() => {
    const apply = () => {
      if (window.jotformEmbedHandler) {
        window.jotformEmbedHandler(`iframe[id='JotFormIFrame-${id}']`, 'https://form.jotform.com/');
      }
    };
    if (window.jotformEmbedHandler) { apply(); return; }
    const existing = document.querySelector(`script[src="${JOTFORM_SCRIPT}"]`);
    if (existing) { existing.addEventListener('load', apply, { once: true }); return; }
    const s = document.createElement('script');
    s.src = JOTFORM_SCRIPT;
    s.async = true;
    s.addEventListener('load', apply, { once: true });
    document.body.appendChild(s);
  }, [id]);
  return (
    <iframe
      id={`JotFormIFrame-${id}`}
      title={title}
      allowTransparency="true"
      allow="geolocation; microphone; camera; fullscreen; payment"
      src={`https://form.jotform.com/${id}`}
      frameBorder="0"
      style={{ minWidth: '100%', maxWidth: '100%', height, border: 'none', display: 'block' }}
      scrolling="no"
    />
  );
};

// --- Card 4: Visitar ---
const FormVisita = () => (
  <JotFormEmbed id="260543092124045" title="Agendamento de Visitas" />
);

// --- Card 5: Doar (segmented) ---
const FormDoar = ({ onClose }) => {
  const [tab, setTab] = React.useState('unica');     // 'unica' | 'bolsas'
  const [pay, setPay] = React.useState('pix');       // 'pix' | 'cartao'
  const [copied, setCopied] = React.useState(false);
  const [bolsasSent, setBolsasSent] = React.useState(false);
  const PIX = '00020126880014BR.GOV.BCB.PIX0136a1a81d1a-02bc-4575-96d8-58084e9af71f0226Doacao Faculdade Belavista5204000053039865802BR5919FACULDADE BELAVISTA6009SAO PAULO622605221m7W5GoYTnSmL9sLywV3HJ6304013B';
  const copyPix = () => {
    navigator.clipboard.writeText(PIX).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    });
  };
  return (
    <div>
      <h3>Quero contribuir financeiramente</h3>
      <p className="lede">
        A Belavista cresce com alunos — e também com doadores que acreditam no
        projeto antes dele ser grande.
      </p>

      <div className="donate-segment">
        <button className={tab === 'unica' ? 'active' : ''} onClick={() => setTab('unica')}>
          Doação única
        </button>
        <button className={tab === 'bolsas' ? 'active' : ''} onClick={() => setTab('bolsas')}>
          Fundo de bolsas
        </button>
      </div>

      {tab === 'unica' && (
        <div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 20 }}>
            <div className="form-grid-2">
              <Field name="d_nome" label="Nome" />
              <Field name="d_telefone" label="Telefone" />
            </div>
            <Field name="d_email" label="E-mail" type="email" />
          </div>

          <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
            <button className={`btn ${pay === 'pix' ? 'btn-primary' : 'btn-ghost'} btn-sm`} onClick={() => setPay('pix')} style={{ flex: 1, justifyContent: 'center' }}>
              <Icon.Pix size={18} /> Doar via Pix
            </button>
            <button className={`btn ${pay === 'cartao' ? 'btn-primary' : 'btn-ghost'} btn-sm`} onClick={() => setPay('cartao')} style={{ flex: 1, justifyContent: 'center' }}>
              <Icon.CreditCard size={18} /> Cartão / PayPal
            </button>
          </div>

          {pay === 'pix' && (
            <div className="pix-box">
              <div className="pix-qr">
                {/* simple stylized QR placeholder */}
                <svg width="100" height="100" viewBox="0 0 100 100" aria-label="QR Code Pix">
                  <rect width="100" height="100" fill="#fff"/>
                  {Array.from({length: 13}).map((_,r) => Array.from({length: 13}).map((_,c) => {
                    const seed = (r*7 + c*11 + r*c) % 5;
                    return seed < 2 ? <rect key={`${r}-${c}`} x={6 + c*7} y={6 + r*7} width="6" height="6" fill="#511865"/> : null;
                  }))}
                  {/* Position markers */}
                  {[[6,6],[80,6],[6,80]].map(([x,y]) => (
                    <g key={`${x}-${y}`}>
                      <rect x={x} y={y} width="14" height="14" fill="#511865"/>
                      <rect x={x+3} y={y+3} width="8" height="8" fill="#fff"/>
                      <rect x={x+5} y={y+5} width="4" height="4" fill="#511865"/>
                    </g>
                  ))}
                </svg>
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--bv-purple)', marginBottom: 6 }}>
                  Pix copia e cola
                </div>
                <div className="pix-code">{PIX}</div>
                <button className="btn btn-ghost btn-sm" onClick={copyPix} style={{ marginTop: 10 }}>
                  <Icon.Copy size={14} /> {copied ? 'Copiado!' : 'Copiar código'}
                </button>
              </div>
            </div>
          )}

          {pay === 'cartao' && (
            <div style={{
              background: 'var(--bv-bg-alt)', borderRadius: 14, padding: 24,
              textAlign: 'center',
            }}>
              <p style={{ margin: '0 0 16px', color: 'var(--bv-gray-dark)' }}>
                Você será redirecionado ao PayPal — aceita cartão de crédito,
                débito e saldo.
              </p>
              <a className="btn btn-primary" href="https://www.paypal.com/donate/?hosted_button_id=745BL7P5KM56E" target="_blank" rel="noopener">
                Continuar no PayPal <Icon.ArrowRight size={16} />
              </a>
            </div>
          )}
        </div>
      )}

      {tab === 'bolsas' && (
        bolsasSent ? (
          <div className="modal-success">
            <div className="check"><Icon.Check size={28} /></div>
            <h3>Pedido recebido</h3>
            <p>Nossa equipe vai entrar em contato para apresentar o fundo de bolsas com calma.</p>
            <button className="btn btn-primary" style={{ marginTop: 24 }} onClick={onClose}>Fechar</button>
          </div>
        ) : (
          <form onSubmit={(e) => { e.preventDefault(); setBolsasSent(true); }}
                style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ margin: 0, color: 'var(--bv-gray-dark)', fontSize: 15, lineHeight: 1.55 }}>
              Quer entender como funciona o fundo de bolsas e como uma contribuição
              recorrente sustenta alunos ao longo do curso? Deixe seu contato e
              nossa equipe faz questão de conversar.
            </p>
            <div className="form-grid-2">
              <Field name="b_nome" label="Nome" />
              <Field name="b_telefone" label="Telefone" />
            </div>
            <Field name="b_email" label="E-mail" type="email" />
            <Textarea name="b_obs" label="Algo que devemos saber antes da conversa? (opcional)" />
            <FormSubmit label="Quero conversar" />
          </form>
        )
      )}
    </div>
  );
};

const FORM_BY_ID = {
  aluno: FormAluno,
  escola: FormEscola,
  projeto: FormProjeto,
  visitar: FormVisita,
  doar: FormDoar,
};

const ContribModal = ({ openId, onClose }) => {
  const Form = openId ? FORM_BY_ID[openId] : null;
  return (
    <Modal open={!!openId} onClose={onClose}>
      {Form && <Form onClose={onClose} />}
    </Modal>
  );
};

window.ContribModal = ContribModal;
