/* global React, Icons */
// ============================================================
//  Contact — support page with a working contact form
//  Operated by Nestaa · get-resume
// ============================================================
const { useState } = React;

const CONTACT_EMAIL = "care@get-resume.com";
const TOPICS = ["General question", "Billing & Pro", "Bug report", "Feature request", "Partnership", "Other"];

const CHANNELS = [
  { ic: Icons.mail, label: "Email us", value: CONTACT_EMAIL, sub: "We read every message", href: `mailto:${CONTACT_EMAIL}` },
  { ic: Icons.bolt, label: "Response time", value: "Within 2 business days", sub: "Usually much faster" },
  { ic: Icons.globe, label: "Operated by", value: "Nestaa", sub: "Mon–Fri · 9am–6pm IST" },
];

const isEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);

function ContactPage({ onHome, onBack }) {
  React.useEffect(() => { window.scrollTo(0, 0); }, []);
  const [form, setForm] = useState({ name: "", email: "", topic: TOPICS[0], message: "" });
  const [touched, setTouched] = useState({});
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [stored, setStored] = useState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const blur = (k) => setTouched((t) => ({ ...t, [k]: true }));

  const errs = {
    name: form.name.trim() ? "" : "Please tell us your name",
    email: isEmail(form.email.trim()) ? "" : "Enter a valid email address",
    message: form.message.trim().length >= 10 ? "" : "Add a little more detail (10+ characters)",
  };
  const valid = !errs.name && !errs.email && !errs.message;

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name: true, email: true, message: true });
    if (!valid || busy) return;
    // Persist to the contact_messages table when the backend is connected.
    if (window.sb) {
      setBusy(true);
      try {
        const uid = (window.RBAuth && window.RBAuth.user()) ? window.RBAuth.user().id : null;
        const { error } = await window.sb.from("contact_messages").insert({
          name: form.name.trim(),
          email: form.email.trim(),
          topic: form.topic,
          message: form.message.trim(),
          user_id: uid,
        });
        if (error) throw error;
        setStored(true);
      } catch (e2) {
        console.warn("contact insert failed, falling back to mailto:", e2);
        setStored(false);
      }
      setBusy(false);
    }
    setSent(true);
  };

  const mailtoHref = `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent("[" + form.topic + "] from " + (form.name || "a visitor"))}&body=${encodeURIComponent(form.message + "\n\n— " + form.name + " (" + form.email + ")")}`;

  return (
    <div className="contact wrap">
      <button className="legal-back" onClick={onBack}><Icons.arrowL size={15} /> Back</button>

      <div className="contact-grid">
        {/* left — intro + channels */}
        <aside className="contact-aside">
          <div className="eyebrow">Contact</div>
          <h1 className="contact-h1">Talk to a real human.</h1>
          <p className="contact-lead">Questions about your résumé, billing, or a feature you wish existed? Send us a note and we'll get back to you personally.</p>
          <div className="contact-channels">
            {CHANNELS.map((c, i) => {
              const Inner = (
                <React.Fragment>
                  <span className="cc-ic"><c.ic size={18} /></span>
                  <span className="cc-text">
                    <span className="cc-label">{c.label}</span>
                    <span className="cc-value">{c.value}</span>
                    <span className="cc-sub">{c.sub}</span>
                  </span>
                </React.Fragment>
              );
              return c.href
                ? <a className="contact-channel" key={i} href={c.href}>{Inner}</a>
                : <div className="contact-channel" key={i}>{Inner}</div>;
            })}
          </div>
        </aside>

        {/* right — form card */}
        <div className="contact-card">
          {sent ? (
            <div className="contact-sent">
              <span className="contact-sent-ic"><Icons.check size={30} /></span>
              {stored ? (
                <>
                  <h2>Message received</h2>
                  <p>Thanks, {form.name.split(" ")[0] || "there"}! We've logged your message and will reply to <b>{form.email}</b> within 2 business days.</p>
                </>
              ) : (
                <>
                  <h2>Message ready to send</h2>
                  <p>Thanks, {form.name.split(" ")[0] || "there"}! Tap below to send it from your mail app — we'll reply to <b>{form.email}</b> within 2 business days.</p>
                  <a className="btn btn-primary" href={mailtoHref}>Open in mail app <Icons.arrow size={16} /></a>
                </>
              )}
              <button className="contact-reset" onClick={() => { setSent(false); setStored(false); setForm({ name: "", email: "", topic: TOPICS[0], message: "" }); setTouched({}); }}>Send another message</button>
            </div>
          ) : (
            <form className="contact-form" onSubmit={submit} noValidate>
              <div className="cf-row">
                <label className="cf-field">
                  <span className="cf-label">Your name</span>
                  <input className={`cf-input ${touched.name && errs.name ? "err" : ""}`} type="text" value={form.name}
                    onChange={(e) => set("name", e.target.value)} onBlur={() => blur("name")} placeholder="Jordan Rivera" />
                  {touched.name && errs.name && <span className="cf-err">{errs.name}</span>}
                </label>
                <label className="cf-field">
                  <span className="cf-label">Email</span>
                  <input className={`cf-input ${touched.email && errs.email ? "err" : ""}`} type="email" value={form.email}
                    onChange={(e) => set("email", e.target.value)} onBlur={() => blur("email")} placeholder="you@email.com" />
                  {touched.email && errs.email && <span className="cf-err">{errs.email}</span>}
                </label>
              </div>

              <div className="cf-field">
                <span className="cf-label">What's this about?</span>
                <div className="cf-topics">
                  {TOPICS.map((tp) => (
                    <button type="button" key={tp} className={`cf-topic ${form.topic === tp ? "on" : ""}`} onClick={() => set("topic", tp)}>{tp}</button>
                  ))}
                </div>
              </div>

              <label className="cf-field">
                <span className="cf-label">Message</span>
                <textarea className={`cf-input cf-textarea ${touched.message && errs.message ? "err" : ""}`} value={form.message}
                  onChange={(e) => set("message", e.target.value)} onBlur={() => blur("message")} rows={6}
                  placeholder="Tell us what's on your mind…" />
                {touched.message && errs.message && <span className="cf-err">{errs.message}</span>}
              </label>

              <div className="cf-foot">
                <span className="cf-note"><Icons.lock size={13} /> We'll only use your email to reply.</span>
                <button className="btn btn-primary cf-submit" type="submit" disabled={!valid || busy}>{busy ? "Sending…" : "Send message"} <Icons.arrow size={16} /></button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

window.ContactPage = ContactPage;
