const { useState: useContactState } = React;

const contactStyles = {
  section: {
    position: 'relative',
    padding: '160px 48px 120px',
    background: '#0a0a0a',
  },
  inner: {
    maxWidth: 1040,
    margin: '0 auto',
  },
  header: {
    textAlign: 'center',
    marginBottom: 96,
  },
  sectionLabel: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 11,
    letterSpacing: '0.4em',
    textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.4)',
    marginBottom: 24,
  },
  sectionTitle: {
    fontFamily: "'Oswald', sans-serif",
    fontSize: 'clamp(56px, 8vw, 112px)',
    fontWeight: 600,
    letterSpacing: '0.04em',
    textTransform: 'uppercase',
    lineHeight: 0.95,
  },
  sub: {
    marginTop: 24,
    fontFamily: "'Inter', sans-serif",
    fontSize: 14,
    color: 'rgba(255,255,255,0.5)',
    letterSpacing: '0.02em',
  },
  form: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '48px 56px',
  },
  field: {
    position: 'relative',
    display: 'flex',
    flexDirection: 'column',
  },
  fieldFull: {
    gridColumn: '1 / -1',
  },
  label: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 10,
    letterSpacing: '0.4em',
    textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.45)',
    marginBottom: 14,
    transition: 'color 200ms ease',
  },
  input: {
    width: '100%',
    background: 'transparent',
    border: 'none',
    outline: 'none',
    borderBottom: '1px solid #242424',
    padding: '10px 0 16px',
    fontFamily: "'Inter', sans-serif",
    fontSize: 18,
    color: '#fff',
    letterSpacing: '0.01em',
    transition: 'border-color 250ms ease',
  },
  textarea: {
    resize: 'vertical',
    minHeight: 140,
    fontFamily: "'Inter', sans-serif",
    lineHeight: 1.6,
  },
  error: {
    marginTop: 8,
    fontFamily: "'Inter', sans-serif",
    fontSize: 11,
    letterSpacing: '0.2em',
    textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.85)',
  },
  actions: {
    gridColumn: '1 / -1',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 24,
    flexWrap: 'wrap',
    gap: 24,
  },
  submitBtn: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 18,
    padding: '22px 40px',
    background: 'transparent',
    border: '1px solid rgba(255,255,255,0.6)',
    color: '#fff',
    cursor: 'pointer',
    fontFamily: "'Oswald', sans-serif",
    fontSize: 15,
    fontWeight: 500,
    letterSpacing: '0.35em',
    textTransform: 'uppercase',
    transition: 'all 280ms ease',
  },
  hint: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 11,
    letterSpacing: '0.3em',
    textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.35)',
  },
  footer: {
    marginTop: 160,
    paddingTop: 48,
    borderTop: '1px solid #161616',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 28,
  },
  socials: {
    display: 'flex',
    alignItems: 'center',
    gap: 6,
    flexWrap: 'wrap',
    justifyContent: 'center',
  },
  iconBtn: {
    width: 40,
    height: 40,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    color: 'rgba(255,255,255,0.55)',
    transition: 'color 200ms ease, transform 200ms ease',
    cursor: 'pointer',
  },
  copy: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 11,
    letterSpacing: '0.35em',
    textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.3)',
  },
  brand: {
    display: 'inline-flex',
    alignItems: 'center',
    height: 28,
    opacity: 0.9,
  },
  brandImg: {
    height: '100%',
    width: 'auto',
    display: 'block',
    objectFit: 'contain',
  },
  success: {
    textAlign: 'center',
    padding: '80px 32px',
    border: '1px solid #1e1e1e',
    background: '#0c0c0c',
  },
  successTitle: {
    fontFamily: "'Oswald', sans-serif",
    fontSize: 48,
    fontWeight: 500,
    letterSpacing: '0.05em',
    textTransform: 'uppercase',
    marginBottom: 20,
  },
  successBody: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 15,
    color: 'rgba(255,255,255,0.55)',
    letterSpacing: '0.05em',
    maxWidth: 480,
    margin: '0 auto',
    lineHeight: 1.7,
  },
};

const FOOTER_SOCIALS = [
  { name: 'Instagram',    Icon: window.IconInstagram,   href: 'https://www.instagram.com/eshwarhq/' },
  { name: 'YouTube',      Icon: window.IconYouTube,     href: 'https://www.youtube.com/channel/UCp4n6jt4JE0_Y-1VVKkgZbQ' },
  { name: 'Spotify',      Icon: window.IconSpotify,     href: 'https://open.spotify.com/artist/1hNm0KMAwufnraxLBhDBEh?si=Q9h-fqRQSyadw1oAD48xsg' },
  { name: 'Apple Music',  Icon: window.IconAppleMusic,  href: 'https://music.apple.com/us/artist/eshwar/1886541880' },
  { name: 'SoundCloud',   Icon: window.IconSoundCloud,  href: 'https://on.soundcloud.com/zbFXNnHxWNTatSJHjx' },
  { name: 'TikTok',       Icon: window.IconTikTok,      href: 'https://www.tiktok.com/@eshwarhq' },
  { name: 'Amazon Music', Icon: window.IconAmazonMusic, href: 'https://music.amazon.com/tracks/B0GT6Z5LXN' },
];

function Field({ id, label, type = 'text', value, onChange, onFocus, onBlur, focused, error, required, textarea, placeholder }) {
  const activeBorder =
    error ? '#fff'
    : focused ? 'rgba(255,255,255,0.75)'
    : value ? 'rgba(255,255,255,0.35)'
    : '#242424';

  const Comp = textarea ? 'textarea' : 'input';

  return (
    <div style={contactStyles.field}>
      <label htmlFor={id} style={{
        ...contactStyles.label,
        color: focused ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.45)',
      }}>
        {label}{required && <span style={{ marginLeft: 6, opacity: 0.4 }}>*</span>}
      </label>
      <Comp
        id={id}
        name={id}
        type={textarea ? undefined : type}
        value={value}
        placeholder={placeholder}
        rows={textarea ? 5 : undefined}
        onChange={(e) => onChange(e.target.value)}
        onFocus={onFocus}
        onBlur={onBlur}
        style={{
          ...contactStyles.input,
          ...(textarea ? contactStyles.textarea : {}),
          borderBottomColor: activeBorder,
        }}
      />
      {error && <div style={contactStyles.error}>— {error}</div>}
    </div>
  );
}

function Contact() {
  const [form, setForm] = useContactState({ name: '', email: '', subject: '', message: '' });
  const [errors, setErrors] = useContactState({});
  const [focused, setFocused] = useContactState(null);
  const [hoverSubmit, setHoverSubmit] = useContactState(false);
  const [submitting, setSubmitting] = useContactState(false);
  const [sent, setSent] = useContactState(false);
  const [submitError, setSubmitError] = useContactState(null);
  const [hovered, setHovered] = useContactState(null);

  const setField = (k) => (v) => {
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((e) => ({ ...e, [k]: undefined }));
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = 'Invalid email';
    if (!form.subject.trim()) e.subject = 'Required';
    if (!form.message.trim()) e.message = 'Required';
    else if (form.message.trim().length < 10) e.message = 'Too short';
    return e;
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setSubmitting(true);
    setSubmitError(null);
    fetch('https://formspree.io/f/myklnpaq', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify({ name: form.name, email: form.email, subject: form.subject, message: form.message }),
    })
      .then((res) => {
        setSubmitting(false);
        if (res.ok) {
          setSent(true);
        } else {
          return res.json().then((data) => {
            setSubmitError(data.error || 'Submission failed. Please try again.');
          });
        }
      })
      .catch(() => {
        setSubmitting(false);
        setSubmitError('Network error. Please check your connection and try again.');
      });
  };

  return (
    <section id="contact" style={contactStyles.section}>
      <div style={contactStyles.inner}>
        <div style={contactStyles.header}>
          <div style={contactStyles.sectionLabel}>— 03</div>
          <h2 style={contactStyles.sectionTitle}>Get in Touch</h2>
        </div>

        {sent ? (
          <div style={contactStyles.success}>
            <div style={contactStyles.successTitle}>Message Sent</div>
            <div style={contactStyles.successBody}>
              Thanks for reaching out. I'll get back to you within a few days.
            </div>
          </div>
        ) : (
          <form className="contact-form" style={contactStyles.form} onSubmit={submit} noValidate>
            <Field
              id="name"
              label="Name"
              required
              value={form.name}
              onChange={setField('name')}
              onFocus={() => setFocused('name')}
              onBlur={() => setFocused(null)}
              focused={focused === 'name'}
              error={errors.name}
              placeholder="Your full name"
            />
            <Field
              id="email"
              label="Email"
              type="email"
              required
              value={form.email}
              onChange={setField('email')}
              onFocus={() => setFocused('email')}
              onBlur={() => setFocused(null)}
              focused={focused === 'email'}
              error={errors.email}
              placeholder="you@domain.com"
            />
            <div style={contactStyles.fieldFull}>
              <Field
                id="subject"
                label="Subject"
                required
                value={form.subject}
                onChange={setField('subject')}
                onFocus={() => setFocused('subject')}
                onBlur={() => setFocused(null)}
                focused={focused === 'subject'}
                error={errors.subject}
                placeholder="Subject"
              />
            </div>
            <div style={contactStyles.fieldFull}>
              <Field
                id="message"
                label="Message"
                required
                textarea
                value={form.message}
                onChange={setField('message')}
                onFocus={() => setFocused('message')}
                onBlur={() => setFocused(null)}
                focused={focused === 'message'}
                error={errors.message}
                placeholder="Your message"
              />
            </div>

            {submitError && (
              <div style={{ ...contactStyles.fieldFull, ...contactStyles.error, color: 'rgba(255,100,100,0.9)', marginBottom: 0 }}>
                — {submitError}
              </div>
            )}

            <div className="contact-actions" style={contactStyles.actions}>
              <div style={contactStyles.hint}>
                {submitting ? 'Sending…' : 'All fields required'}
              </div>
              <button
                type="submit"
                disabled={submitting}
                onMouseEnter={() => setHoverSubmit(true)}
                onMouseLeave={() => setHoverSubmit(false)}
                style={{
                  ...contactStyles.submitBtn,
                  background: hoverSubmit ? '#fff' : 'transparent',
                  color: hoverSubmit ? '#000' : '#fff',
                  borderColor: hoverSubmit ? '#fff' : 'rgba(255,255,255,0.6)',
                  opacity: submitting ? 0.5 : 1,
                  cursor: submitting ? 'wait' : 'pointer',
                }}
              >
                <span>{submitting ? 'Sending' : 'Send Message'}</span>
                <window.IconArrow size={16} />
              </button>
            </div>
          </form>
        )}

        <div className="contact-footer" style={contactStyles.footer}>
          <div style={contactStyles.brand}>
            <img src="assets/logo-white.png" alt="Eshwar" style={contactStyles.brandImg} />
          </div>
          <div style={contactStyles.socials}>
            {FOOTER_SOCIALS.map(({ name, Icon, href }) => (
              <a
                key={name}
                href={href}
                target="_blank"
                rel="noopener noreferrer"
                aria-label={name}
                title={name}
                style={{
                  ...contactStyles.iconBtn,
                  color: hovered === name ? '#fff' : 'rgba(255,255,255,0.5)',
                  transform: hovered === name ? 'translateY(-1px)' : 'translateY(0)',
                }}
                onMouseEnter={() => setHovered(name)}
                onMouseLeave={() => setHovered(null)}
              >
                <Icon size={18} />
              </a>
            ))}
          </div>
          <div style={contactStyles.copy}>© 2026 Eshwar · All Rights Reserved</div>
        </div>
      </div>
    </section>
  );
}

window.Contact = Contact;
