
const CONTACT_WEBHOOK = "https://n8n-bgdp.srv1516287.hstgr.cloud/webhook/portfolio-contact";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const RATE_KEY  = "fj_contact_submissions";
const EMAIL_KEY = "fj_contact_emails";

function sanitize(str) {
  return str.replace(/<[^>]*>/g, "").trim();
}

function checkContactRateLimit(email) {
  const now = Date.now();
  let times = JSON.parse(localStorage.getItem(RATE_KEY) || "[]");
  times = times.filter(t => now - t < 3_600_000);
  if (times.length >= 3)
    return "You've sent too many messages. Please wait a while before trying again.";
  const emails = JSON.parse(localStorage.getItem(EMAIL_KEY) || "{}");
  if (emails[email] && now - emails[email] < 86_400_000)
    return "A message from this email was already sent recently. Please try again tomorrow.";
  return null;
}

function recordContactSubmission(email) {
  const now = Date.now();
  let times = JSON.parse(localStorage.getItem(RATE_KEY) || "[]");
  times = times.filter(t => now - t < 3_600_000);
  times.push(now);
  localStorage.setItem(RATE_KEY, JSON.stringify(times));
  const emails = JSON.parse(localStorage.getItem(EMAIL_KEY) || "{}");
  emails[email] = now;
  localStorage.setItem(EMAIL_KEY, JSON.stringify(emails));
}

const ContactSection = ({ navigateTo }) => {
  const [form, setForm]               = React.useState({ name: "", email: "", message: "", _hp: "" });
  const [emailError, setEmailError]   = React.useState("");
  const [formError, setFormError]     = React.useState("");
  const [sent, setSent]               = React.useState(false);
  const [sending, setSending]         = React.useState(false);

  const validateEmail = (value) => {
    if (!value) return "Email is required.";
    if (!EMAIL_RE.test(value)) return "Please enter a valid email address.";
    return "";
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (form._hp) return;
    const emailErr = validateEmail(form.email);
    if (emailErr) { setEmailError(emailErr); return; }
    const msg = sanitize(form.message);
    if (msg.length < 10)  { setFormError("Message is too short (min 10 characters)."); return; }
    if (msg.length > 2000) { setFormError("Message is too long (max 2000 characters)."); return; }
    const limitErr = checkContactRateLimit(form.email.toLowerCase());
    if (limitErr) { setFormError(limitErr); return; }
    setFormError("");
    setSending(true);
    try {
      await fetch(CONTACT_WEBHOOK, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name:    sanitize(form.name).slice(0, 100),
          email:   form.email.toLowerCase().trim().slice(0, 254),
          message: msg.slice(0, 2000),
        }),
      });
      recordContactSubmission(form.email.toLowerCase());
    } catch {}
    setSending(false);
    setSent(true);
  };

  const glassCard = {
    background: "rgba(5,12,13,0.86)",
    border: "1px solid rgba(20,184,166,0.16)",
    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
  };

  const inputStyle = {
    width: "100%", padding: "13px 16px",
    background: "rgba(255,255,255,0.025)",
    border: "1px solid rgba(20,184,166,0.12)",
    borderRadius: 10, color: "var(--fg)",
    fontFamily: "Montserrat, sans-serif", fontSize: 14,
    outline: "none", boxSizing: "border-box", transition: "border-color 0.2s",
    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03)",
  };

  return (
    <section data-screen-label="06 Contact" style={{
      minHeight: "100vh", padding: "100px 60px 60px",
      background: "var(--bg)", borderTop: "1px solid var(--border)",
      position: "relative", overflow: "hidden",
    }}>
      <video autoPlay muted loop playsInline src="uploads/background_teal_moving.mp4"
        onCanPlay={e => e.target.playbackRate = 0.4}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 0 }} />
      <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.72)", zIndex: 1 }} />

      <div style={{ maxWidth: 1100, margin: "0 auto", position: "relative", zIndex: 2 }}>

        {/* Editorial header */}
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 56, flexWrap: "wrap", gap: 16 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
              <div style={{ width: 32, height: 2, borderRadius: 2, background: "var(--teal)", boxShadow: "0 0 8px rgba(20,184,166,0.6)", flexShrink: 0 }} />
              <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 11, fontWeight: 500, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--teal)" }}>Let's Talk</p>
            </div>
            <h2 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: "clamp(2.2rem,5vw,3.5rem)", color: "var(--fg)", letterSpacing: "-0.02em", lineHeight: 1.05 }}>
              <span style={{ color: "var(--teal)", textShadow: "0 0 14px oklch(0.65 0.16 185 / 0.9), 0 0 32px oklch(0.65 0.16 185 / 0.5)", animation: "tealGlow 2.5s ease-in-out infinite" }}>Ready to automate</span><br />your business?
            </h2>
          </div>
          <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 15, color: "var(--muted)", maxWidth: 360, lineHeight: 1.7 }}>
            Whether you need a custom workflow, AI integration, or a full CRM buildout — let's make it happen.
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, alignItems: "start" }}>

          {/* LEFT — Booking glass card */}
          <div style={{ ...glassCard, borderRadius: 20, overflow: "hidden" }}>
            <div style={{ padding: "28px 32px 20px", borderBottom: "1px solid rgba(255,255,255,0.07)", background: "rgba(20,184,166,0.03)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
                <div style={{ width: 32, height: 2, borderRadius: 2, background: "var(--teal)", boxShadow: "0 0 8px rgba(20,184,166,0.6)" }} />
                <span style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.18em", textTransform: "uppercase" }}>Schedule</span>
              </div>
              <h3 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: 18, color: "var(--fg)", marginBottom: 6 }}>Book a Free Strategy Call</h3>
              <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 13, color: "var(--muted)", lineHeight: 1.6 }}>30 minutes. No fluff. Let's map out how automation can transform your workflow.</p>
            </div>
            <iframe
              src="https://calendly.com/francisdanao55/30min?embed_type=inline&hide_gdpr_banner=1&background_color=070e10&text_color=edeff2&primary_color=14b8a6"
              style={{ width: "100%", height: 620, border: "none", display: "block" }}
              title="Book a meeting"
            />
          </div>

          {/* RIGHT — Form + Resume + Social */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>

            {/* Form glass card */}
            <div style={{ ...glassCard, borderRadius: 20, padding: "28px 32px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24 }}>
                <div style={{ width: 32, height: 2, borderRadius: 2, background: "var(--teal)", boxShadow: "0 0 8px rgba(20,184,166,0.6)" }} />
                <span style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.18em", textTransform: "uppercase" }}>Send a Message</span>
              </div>

              {sent ? (
                <div style={{ textAlign: "center", padding: "32px 0" }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: "50%",
                    background: "rgba(20,184,166,0.1)",
                    border: "1px solid rgba(20,184,166,0.3)",
                    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.08), 0 10px 28px rgba(0,0,0,0.2)",
                    display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 20px",
                  }}>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--teal)" strokeWidth="2"><path d="M20 6L9 17l-5-5"/></svg>
                  </div>
                  <h3 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 800, fontSize: 20, color: "var(--fg)", marginBottom: 8 }}>Message Received!</h3>
                  <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 14, color: "var(--muted)" }}>I'll get back to you within 24 hours.</p>
                </div>
              ) : (
                <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
                  <div style={{ position: "absolute", left: "-9999px", opacity: 0, pointerEvents: "none" }} aria-hidden="true">
                    <input tabIndex="-1" autoComplete="off" value={form._hp}
                      onChange={e => setForm({...form, _hp: e.target.value})} />
                  </div>

                  {[
                    { key: "name",  label: "Name",  type: "text",  placeholder: "Your full name" },
                    { key: "email", label: "Email", type: "email", placeholder: "your@email.com" },
                  ].map(field => (
                    <div key={field.key}>
                      <label style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: field.key === "email" && emailError ? "#f87171" : "var(--teal)", letterSpacing: "0.15em", textTransform: "uppercase", display: "block", marginBottom: 8 }}>{field.label}</label>
                      <input
                        type={field.type} placeholder={field.placeholder} required
                        value={form[field.key]}
                        maxLength={field.key === "name" ? 100 : 254}
                        onChange={e => {
                          setForm({...form, [field.key]: e.target.value});
                          if (field.key === "email") setEmailError(validateEmail(e.target.value));
                        }}
                        style={{ ...inputStyle, border: `1px solid ${field.key === "email" && emailError ? "rgba(248,113,113,0.6)" : "rgba(255,255,255,0.1)"}` }}
                        onFocus={e => e.target.style.borderColor = field.key === "email" && emailError ? "rgba(248,113,113,0.8)" : "rgba(20,184,166,0.5)"}
                        onBlur={e  => e.target.style.borderColor = field.key === "email" && emailError ? "rgba(248,113,113,0.6)" : "rgba(255,255,255,0.1)"}
                      />
                      {field.key === "email" && emailError && (
                        <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 11, color: "#f87171", marginTop: 6 }}>{emailError}</p>
                      )}
                    </div>
                  ))}

                  <div>
                    <label style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.15em", textTransform: "uppercase", display: "block", marginBottom: 8 }}>
                      Message
                      <span style={{ color: "rgba(255,255,255,0.3)", marginLeft: 8, fontSize: 9 }}>({form.message.length}/2000)</span>
                    </label>
                    <textarea
                      rows={5} placeholder="Tell me about your project..." required
                      value={form.message} maxLength={2000}
                      onChange={e => { setForm({...form, message: e.target.value}); setFormError(""); }}
                      style={{ ...inputStyle, resize: "vertical" }}
                      onFocus={e => e.target.style.borderColor = "rgba(20,184,166,0.5)"}
                      onBlur={e  => e.target.style.borderColor = "rgba(255,255,255,0.1)"}
                    />
                  </div>

                  {formError && (
                    <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 12, color: "#f87171", background: "rgba(248,113,113,0.08)", border: "1px solid rgba(248,113,113,0.2)", borderRadius: 8, padding: "10px 14px", margin: 0 }}>
                      {formError}
                    </p>
                  )}

                  <button type="submit" disabled={sending} style={{
                    background: "var(--teal)", color: "#030d0e",
                    border: "none", cursor: sending ? "default" : "pointer", borderRadius: 999,
                    padding: "14px 32px", width: "fit-content",
                    fontFamily: "Montserrat, sans-serif", fontSize: 13, fontWeight: 700,
                    letterSpacing: "0.04em", transition: "opacity 0.15s",
                    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.3), 0 0 18px oklch(0.65 0.16 185 / 0.5), 0 0 40px oklch(0.65 0.16 185 / 0.25)",
                    animation: "buttonGlow 2.5s ease-in-out infinite",
                    opacity: sending ? 0.7 : 1,
                  }} onMouseEnter={e=>{ if (!sending) e.currentTarget.style.opacity="0.85"; }} onMouseLeave={e=>{ if (!sending) e.currentTarget.style.opacity="1"; }}>
                    {sending ? "Sending…" : "Send Message"}
                  </button>
                </form>
              )}
            </div>

            {/* Resume glass card */}
            <div style={{ ...glassCard, borderRadius: 16, padding: "22px 28px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
              <div>
                <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 6 }}>Resume</p>
                <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 14, color: "var(--muted)" }}>Full credentials & experience PDF</p>
              </div>
              <a href="Francis_Joseph_Danao_Resume.pdf" download="Francis_Joseph_Danao_Resume.pdf" style={{
                background: "rgba(5,12,13,0.86)",
                border: "1px solid rgba(20,184,166,0.3)",
                color: "rgba(255,255,255,0.82)", borderRadius: 999, padding: "10px 22px",
                fontFamily: "Montserrat, sans-serif", fontSize: 13, fontWeight: 700,
                textDecoration: "none", display: "flex", alignItems: "center", gap: 8,
                boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 0 14px oklch(0.65 0.16 185 / 0.28), 0 0 30px oklch(0.65 0.16 185 / 0.16), 0 10px 28px rgba(0,0,0,0.2)",
                transition: "all 0.2s", whiteSpace: "nowrap",
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background = "rgba(7,16,17,0.92)";
                e.currentTarget.style.borderColor = "rgba(20,184,166,0.5)";
                e.currentTarget.style.color = "var(--teal)";
                e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.03), 0 0 20px oklch(0.65 0.16 185 / 0.42), 0 0 42px oklch(0.65 0.16 185 / 0.22), 0 10px 28px rgba(0,0,0,0.22)";
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background = "rgba(5,12,13,0.86)";
                e.currentTarget.style.borderColor = "rgba(20,184,166,0.3)";
                e.currentTarget.style.color = "rgba(255,255,255,0.82)";
                e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.03), 0 0 14px oklch(0.65 0.16 185 / 0.28), 0 0 30px oklch(0.65 0.16 185 / 0.16), 0 10px 28px rgba(0,0,0,0.2)";
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
                Download PDF
              </a>
            </div>

            {/* Social glass links */}
            <div style={{ display: "flex", gap: 10 }}>
              {[
                { label: "LinkedIn", href: "https://linkedin.com", logo: (
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="#0A66C2">
                    <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
                  </svg>
                )},
                { label: "Upwork", href: "https://upwork.com", logo: (
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="#14A800">
                    <path d="M18.561 13.158c-1.102 0-2.135-.467-3.074-1.227l.228-1.076.008-.042c.207-1.143.849-3.06 2.839-3.06 1.492 0 2.703 1.212 2.703 2.703-.001 1.489-1.212 2.702-2.704 2.702zm0-8.14c-2.539 0-4.51 1.649-5.31 4.366-1.22-1.834-2.148-4.036-2.687-5.892H7.828v7.112c-.002 1.406-1.141 2.546-2.547 2.546-1.405 0-2.543-1.14-2.543-2.546V3.492H0v7.112c0 2.914 2.37 5.303 5.281 5.303 2.913 0 5.283-2.389 5.283-5.303v-1.19c.529 1.107 1.182 2.229 1.974 3.221l-1.673 7.873h2.797l1.213-5.71c1.063.679 2.285 1.109 3.686 1.109 3 0 5.439-2.452 5.439-5.45 0-3-2.439-5.439-5.439-5.439z"/>
                  </svg>
                )},
                { label: "Gmail", href: "mailto:francisdanao55@gmail.com", logo: (
                  <img src="https://cdn.simpleicons.org/gmail/EA4335" alt="Gmail" width="18" height="18" />
                )},
              ].map(s => (
                <a key={s.label} href={s.href} target="_blank" rel="noreferrer" style={{
                  flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
                  padding: "13px",
                  background: "rgba(5,12,13,0.86)",
                  border: "1px solid rgba(20,184,166,0.16)",
                  boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
                  borderRadius: 12, color: "rgba(255,255,255,0.5)", textDecoration: "none",
                  fontFamily: "Montserrat, sans-serif", fontSize: 12, fontWeight: 600,
                  letterSpacing: "0.01em", textTransform: "none", transition: "all 0.2s",
                }}
                onMouseEnter={e => {
                  e.currentTarget.style.borderColor = "rgba(20,184,166,0.3)";
                  e.currentTarget.style.color = "var(--teal)";
                  e.currentTarget.style.transform = "translateY(-2px)";
                  e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.22)";
                }}
                onMouseLeave={e => {
                  e.currentTarget.style.borderColor = "rgba(20,184,166,0.16)";
                  e.currentTarget.style.color = "rgba(255,255,255,0.5)";
                  e.currentTarget.style.transform = "translateY(0)";
                  e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)";
                }}>
                  {s.logo}
                  {s.label}
                </a>
              ))}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{ marginTop: 56, paddingTop: 28, borderTop: "1px solid rgba(255,255,255,0.07)", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <img src="assets/logo.png" alt="logo" style={{ width: 36, height: 36, objectFit: "contain" }} />
            <div>
              <p style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: 17, lineHeight: 1.1, margin: 0 }}>
                <span style={{ color: "var(--teal)", textShadow: "0 0 14px oklch(0.65 0.16 185 / 0.9), 0 0 32px oklch(0.65 0.16 185 / 0.5)", animation: "tealGlow 2.5s ease-in-out infinite" }}>Francis</span>
                <span style={{ color: "var(--fg)" }}> Joseph Danao</span>
              </p>
              <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "rgba(20,184,166,0.55)", letterSpacing: "0.12em", textTransform: "uppercase", margin: 0, marginTop: 3 }}>AI & Automation Specialist</p>
            </div>
          </div>
          <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "rgba(255,255,255,0.3)", letterSpacing: "0.1em" }}>© 2026 — All rights reserved</p>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { ContactSection });
