/* GayCard — Contact page.
   A public channel where visitors send a complaint, suggestion, doubt or
   anything else. Submits through GayCardAPI.createContactMessage(), which
   calls the SECURITY DEFINER create_contact_message() RPC (anon-safe; the
   table itself is locked by RLS). Admins read these in admin.html. */
const { useState } = React;

const KINDS = [
  { id: "reclamacao", label: "Reclamação", desc: "Algo não saiu como esperado", color: "var(--red)", icon: "M12 9v4m0 4h.01M10.3 3.86l-8.1 14a1.5 1.5 0 0 0 1.3 2.24h16.2a1.5 1.5 0 0 0 1.3-2.24l-8.1-14a1.5 1.5 0 0 0-2.6 0z" },
  { id: "sugestao",   label: "Sugestão",   desc: "Uma ideia pra melhorar",      color: "var(--blue)", icon: "M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.3 1 2.5h6c0-1.2.3-1.8 1-2.5A6 6 0 0 0 12 3z" },
  { id: "duvida",     label: "Dúvida",     desc: "Quero entender melhor",        color: "var(--purple)", icon: "M9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3M12 17h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z" },
  { id: "outro",      label: "Outro",      desc: "Qualquer outro assunto",       color: "var(--green)", icon: "M8 10h8M8 14h5M21 12a9 9 0 0 1-9 9 9 9 0 0 1-4-1l-5 1 1-5a9 9 0 1 1 17-4z" },
];

function TopBar() {
  return (
    <nav style={{ position: "sticky", top: 0, zIndex: 40, background: "rgba(255,255,255,0.86)", backdropFilter: "blur(14px)", borderBottom: "1px solid rgba(18,18,18,0.08)" }}>
      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 70 }}>
        <a href="GayCard.html" className="brand" style={{ display: "flex", alignItems: "center", gap: 9, textDecoration: "none" }}>
          <PrideFlag width={30} />
          <span className="display" style={{ fontSize: "1.4rem", color: "var(--ink)" }}>Gay<span className="rainbow-text brand-accent">Card</span></span>
        </a>
        <a className="btn btn-ghost" href="GayCard.html" style={{ padding: "0.6rem 1.1rem", fontSize: "0.88rem" }}>← Voltar ao site</a>
      </div>
    </nav>
  );
}

function KindCard({ k, active, onClick }) {
  return (
    <button type="button" onClick={onClick}
      style={{ textAlign: "left", cursor: "pointer", padding: "16px 16px", borderRadius: 16,
        border: "2px solid " + (active ? k.color : "#e7e2d7"),
        background: active ? "#fff" : "#fffdf8", transition: "border-color .15s, box-shadow .15s",
        boxShadow: active ? "0 0 0 4px " + k.color + "22" : "none" }}>
      <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 34, height: 34, borderRadius: 10, background: k.color + "1a", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke={k.color} strokeWidth="2.2"><path d={k.icon} strokeLinecap="round" strokeLinejoin="round" /></svg>
        </span>
        <span>
          <span style={{ display: "block", fontWeight: 800, fontSize: "0.98rem", color: "var(--ink)" }}>{k.label}</span>
          <span style={{ display: "block", fontSize: "0.78rem", color: "var(--ink-45)", fontWeight: 500 }}>{k.desc}</span>
        </span>
      </span>
    </button>
  );
}

function ContactApp() {
  const [kind, setKind] = useState("reclamacao");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [done, setDone] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!window.GayCardAPI || !window.GayCardAPI.configured()) {
      setErr("Backend não configurado (config.js).");
      return;
    }
    if (!name.trim() || !email.trim() || !message.trim()) {
      setErr("Preencha nome, e-mail e mensagem.");
      return;
    }
    setBusy(true);
    try {
      await window.GayCardAPI.createContactMessage({ kind, name, email, subject, message });
      setDone(true);
    } catch (e2) {
      setErr(e2.message || "Não foi possível enviar sua mensagem. Tente de novo.");
    } finally {
      setBusy(false);
    }
  };

  if (done) {
    const k = KINDS.find((x) => x.id === kind);
    return (
      <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
        <TopBar />
        <div className="wrap" style={{ maxWidth: 620, padding: "80px 24px", textAlign: "center" }}>
          <div style={{ width: 72, height: 72, margin: "0 auto 22px", borderRadius: "50%", background: "var(--rainbow)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><path d="M5 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </div>
          <h1 className="display" style={{ fontSize: "clamp(1.9rem,4vw,2.8rem)", margin: 0 }}>Mensagem enviada!</h1>
          <p style={{ color: "var(--ink-70)", fontWeight: 500, lineHeight: 1.6, marginTop: 14, fontSize: "1.05rem" }}>
            Recebemos sua <strong>{(k ? k.label : "mensagem").toLowerCase()}</strong>. Nossa equipe vai dar uma olhada com carinho 🏳️‍🌈
          </p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap", marginTop: 30 }}>
            <a className="btn btn-rainbow" href="GayCard.html">Voltar ao início</a>
            <button className="btn btn-ghost" onClick={() => { setDone(false); setName(""); setEmail(""); setSubject(""); setMessage(""); setKind("reclamacao"); }}>
              Enviar outra
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
      <TopBar />
      <div className="wrap contact-grid" style={{ display: "grid", gridTemplateColumns: "1.15fr 0.85fr", gap: 44, padding: "54px 24px 90px", alignItems: "start" }}>
        {/* Form */}
        <form onSubmit={submit}>
          <div className="eyebrow" style={{ color: "var(--purple)", marginBottom: 10 }}>Fale com a gente</div>
          <h1 className="display" style={{ fontSize: "clamp(2rem,4.4vw,3.2rem)", margin: 0 }}>Contato</h1>
          <p style={{ color: "var(--ink-70)", fontWeight: 500, lineHeight: 1.6, marginTop: 12, maxWidth: 520 }}>
            Reclamação, sugestão, dúvida ou qualquer outro assunto — escreve aqui que a gente responde.
          </p>

          <label className="field-label" style={{ marginTop: 30 }}>Sobre o que é?</label>
          <div className="kind-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 22 }}>
            {KINDS.map((k) => <KindCard key={k.id} k={k} active={kind === k.id} onClick={() => setKind(k.id)} />)}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div>
              <label className="field-label">Seu nome</label>
              <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Como podemos te chamar?" required />
            </div>
            <div>
              <label className="field-label">Seu e-mail</label>
              <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="voce@email.com" required />
            </div>
          </div>

          <label className="field-label" style={{ marginTop: 16 }}>Assunto <span style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-45)" }}>(opcional)</span></label>
          <input className="input" value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Resumo em uma linha" maxLength={200} />

          <label className="field-label" style={{ marginTop: 16 }}>Mensagem</label>
          <textarea className="textarea" value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Conte com detalhes o que aconteceu ou o que você gostaria..." maxLength={4000} required />
          <div className="mono" style={{ textAlign: "right", fontSize: "0.72rem", color: "var(--ink-45)", marginTop: 4 }}>{message.length}/4000</div>

          {err && <p style={{ color: "var(--red)", fontWeight: 600, fontSize: "0.9rem", margin: "10px 0 0" }}>{err}</p>}

          <button className="btn btn-rainbow" type="submit" disabled={busy} style={{ marginTop: 18, opacity: busy ? 0.6 : 1 }}>
            {busy ? "Enviando…" : "Enviar mensagem"}
            {!busy && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" /></svg>}
          </button>
        </form>

        {/* Aside */}
        <aside className="contact-aside" style={{ position: "sticky", top: 90 }}>
          <div style={{ background: "linear-gradient(135deg,#fff,#faf6ec)", border: "2px solid #efe9dc", borderRadius: "var(--radius)", padding: 28, position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", top: -40, right: -40, width: 150, height: 150, background: "var(--rainbow)", filter: "blur(60px)", opacity: 0.2, borderRadius: "50%" }} />
            <PrideFlag width={40} />
            <h3 className="display" style={{ fontSize: "1.4rem", margin: "16px 0 8px" }}>A gente te escuta.</h3>
            <p style={{ color: "var(--ink-70)", lineHeight: 1.55, fontWeight: 500, margin: 0 }}>
              Toda mensagem é lida por uma pessoa de verdade. Sua opinião ajuda a deixar o GayCard cada vez melhor pra comunidade. 💛
            </p>
            <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid #efe9dc", display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                ["Resposta no seu e-mail", "Respondemos no e-mail que você informar."],
                ["Sem julgamentos", "Pode falar à vontade — esse espaço é seu."],
              ].map(([t, d]) => (
                <div key={t} style={{ display: "flex", gap: 10 }}>
                  <span style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--rainbow)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 2 }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><path d="M5 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                  </span>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: "0.92rem" }}>{t}</div>
                    <div style={{ color: "var(--ink-45)", fontSize: "0.82rem", fontWeight: 500 }}>{d}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ContactApp />);
