/* global React, Reveal, Icon, MLN */
const { useState: useStateCta } = React;

const PHONE_RE_CTA = /^0[2-9]\d{7,8}$|^05\d[-\s]?\d{7}$/;
const EMAIL_RE_CTA = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const errStyle = { color: '#FFAAAA', fontSize: 12.5, display: 'block', marginTop: 4 };

const CtaField = ({ label, children }) => (
  <label style={{ display: 'block', textAlign: 'right' }}>
    <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13.5, color: 'var(--text-on-red-soft)', marginBottom: 7 }}>{label}</span>
    {children}
  </label>
);

const ctaInput = (focused) => ({
  width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-body)', fontSize: 15.5,
  padding: '13px 16px', borderRadius: 'var(--radius-md)', color: '#FFF6F2',
  background: 'rgba(255,246,242,0.08)',
  border: `1.5px solid ${focused ? 'var(--red-300)' : 'rgba(255,246,242,0.24)'}`,
  boxShadow: focused ? '0 0 0 4px rgba(236,160,172,0.18)' : 'none', outline: 'none',
  transition: 'all 200ms',
});

const ContactSection = ({ onSubmit }) => {
  const [form, setForm] = useStateCta({ name: '', phone: '', email: '', message: '' });
  const [topic, setTopic] = useStateCta('general');
  const [focus, setFocus] = useStateCta('');
  const [sent, setSent] = useStateCta(false);
  const [errors, setErrors] = useStateCta({});
  const [sending, setSending] = useStateCta(false);

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim() || form.name.trim().length < 2) errs.name = 'נא להזין שם מלא';
    if (!PHONE_RE_CTA.test(form.phone.trim().replace(/[\s-]/g, ''))) errs.phone = 'מספר טלפון לא תקין (לדוגמה: 054-1234567)';
    if (form.email && !EMAIL_RE_CTA.test(form.email.trim())) errs.email = 'כתובת מייל לא תקינה';
    if (!form.message.trim()) errs.message = 'נא לכתוב הודעה';
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }
    setErrors({});
    setSending(true);
    const rec = { id: MLN.id(), topic, product: null, ...form, date: new Date().toISOString(), read: false };
    try {
      if (typeof saveContactMessage === 'function') {
        await saveContactMessage({
          name: form.name, email: form.email, phone: form.phone,
          subject: MLN.TOPICS[topic].label,
          message: form.message,
        });
      }
    } catch (err) {
      setSending(false);
      setErrors({ form: err.message || 'אירעה שגיאה, נסה שוב' });
      return;
    }
    onSubmit(rec);
    setSent(true);
  };

  return (
    <section id="contact" style={{ background: 'var(--paper)', padding: 'var(--section-y) 28px' }}>
      <Reveal as="div" style={{
        maxWidth: 1060, margin: '0 auto',
        background: 'radial-gradient(120% 130% at 80% 0%, #7A1626, #4A0E18 72%)',
        borderRadius: 'var(--radius-xl)', boxShadow: '0 30px 70px rgba(74,14,24,0.30)',
        color: '#FFF6F2', padding: 'clamp(34px,5vw,60px)', overflow: 'hidden', position: 'relative',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0, opacity: 0.06, pointerEvents: 'none',
          backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22120%22 height=%22120%22%3E%3Cfilter id=%22n%22%3E%3CfeTurbulence type=%22fractalNoise%22 baseFrequency=%220.9%22 numOctaves=%222%22/%3E%3C/filter%3E%3Crect width=%22100%25%22 height=%22100%25%22 filter=%22url(%23n)%22/%3E%3C/svg%3E")',
        }} />
        <div className="mln-contact-grid" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'start' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, letterSpacing: '0.24em', color: 'var(--red-300)', marginBottom: 18 }}>יצירת קשר</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(1.9rem,3.2vw,2.7rem)', lineHeight: 1.2, margin: '0 0 18px' }}>נתחיל את המסע<br/>שלך — יחד</h2>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 16.5, lineHeight: 1.75, color: 'var(--text-on-red-soft)', margin: '0 0 30px', maxWidth: '40ch' }}>
              להזמנת הרצאה, לרכישת הספר, או לכל שאלה — בחר/י נושא, השאר/י פרטים, וכל פנייה תגיע אליי מסודרת ומקוטלגת.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <a href={MLN.gmailTo(MLN.EMAIL)} target="_blank" rel="noopener noreferrer" style={contactLink}><span style={contactIcon}><Icon name="mail" size={18} /></span> {MLN.EMAIL}</a>
              <a href="tel:0544618647" style={contactLink}><span style={contactIcon}><Icon name="phone" size={18} /></span> 054-461-8647</a>
              <div style={{ display: 'flex', gap: 12, marginTop: 6 }}>
                <a href="https://www.instagram.com/_milim_mehalev" target="_blank" rel="noopener noreferrer" title="אינסטגרם" style={socialBtn}><Icon name="instagram" size={20} /></a>
                <a href="https://www.facebook.com/wdlyhmyr.2025?locale=he_IL" target="_blank" rel="noopener noreferrer" title="פייסבוק — אודליה מאיר" style={socialBtn}><Icon name="facebook" size={20} /></a>
              </div>
            </div>
          </div>

          <div>
            {sent ? (
              <div style={{ background: 'rgba(255,246,242,0.08)', border: '1.5px solid rgba(255,246,242,0.24)', borderRadius: 'var(--radius-lg)', padding: '44px 32px', textAlign: 'center' }}>
                <div style={{ color: 'var(--red-300)', display: 'flex', justifyContent: 'center', marginBottom: 16 }}><Icon name="heart" size={40} /></div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, margin: '0 0 10px' }}>תודה מכל הלב</h3>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 15.5, color: 'var(--text-on-red-soft)', margin: 0 }}>קיבלתי את הפנייה תחת "{MLN.TOPICS[topic].label}" — אחזור אליך בהקדם.</p>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <CtaField label="נושא הפנייה">
                  <select value={topic} onChange={e => setTopic(e.target.value)} onFocus={() => setFocus('topic')} onBlur={() => setFocus('')} style={ctaInput(focus === 'topic')}>
                    {Object.values(MLN.TOPICS).map(tp => <option key={tp.id} value={tp.id} style={{ color: '#1C1413' }}>{tp.label}</option>)}
                  </select>
                </CtaField>
                <CtaField label="שם מלא">
                  <input placeholder="איך לפנות אליך?" value={form.name} onChange={e => { setForm(f => ({ ...f, name: e.target.value })); setErrors(ev => ({ ...ev, name: '' })); }} onFocus={() => setFocus('name')} onBlur={() => setFocus('')} style={ctaInput(focus === 'name')} />
                  {errors.name && <span style={errStyle}>{errors.name}</span>}
                </CtaField>
                <div className="mln-contact-phoneemail" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <CtaField label="טלפון">
                    <input type="tel" placeholder="050-000-0000" value={form.phone} onChange={e => { setForm(f => ({ ...f, phone: e.target.value })); setErrors(ev => ({ ...ev, phone: '' })); }} onFocus={() => setFocus('phone')} onBlur={() => setFocus('')} style={ctaInput(focus === 'phone')} />
                    {errors.phone && <span style={errStyle}>{errors.phone}</span>}
                  </CtaField>
                  <CtaField label="מייל">
                    <input type="email" placeholder="name@email.com" value={form.email} onChange={e => { setForm(f => ({ ...f, email: e.target.value })); setErrors(ev => ({ ...ev, email: '' })); }} onFocus={() => setFocus('email')} onBlur={() => setFocus('')} style={ctaInput(focus === 'email')} />
                    {errors.email && <span style={errStyle}>{errors.email}</span>}
                  </CtaField>
                </div>
                <CtaField label="ההודעה שלך">
                  <textarea rows={3} placeholder="כתבי/כתוב לי כמה מילים…" value={form.message} onChange={e => { setForm(f => ({ ...f, message: e.target.value })); setErrors(ev => ({ ...ev, message: '' })); }} onFocus={() => setFocus('msg')} onBlur={() => setFocus('')} style={{ ...ctaInput(focus === 'msg'), resize: 'vertical', minHeight: 84 }} />
                  {errors.message && <span style={errStyle}>{errors.message}</span>}
                </CtaField>
                {errors.form && <span style={{ ...errStyle, fontSize: 14, textAlign: 'center' }}>{errors.form}</span>}
                <button type="submit" disabled={sending} style={{ marginTop: 6, background: '#FFF6F2', color: 'var(--red-800)', border: 'none', cursor: sending ? 'wait' : 'pointer', opacity: sending ? 0.7 : 1, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 17, padding: '15px', borderRadius: 'var(--radius-pill)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 9, boxShadow: '0 14px 30px rgba(0,0,0,0.25)' }}>{sending ? 'שולח…' : 'שליחה'} {!sending && <Icon name="arrow" size={18} />}</button>
              </form>
            )}
          </div>
        </div>
      </Reveal>
    </section>
  );
};

const contactLink = { display: 'flex', alignItems: 'center', gap: 12, color: 'var(--text-on-red-soft)', textDecoration: 'none', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16 };
const contactIcon = { width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,246,242,0.1)', border: '1px solid rgba(255,246,242,0.2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 };
const socialBtn = { width: 46, height: 46, borderRadius: '50%', background: 'rgba(255,246,242,0.1)', border: '1px solid rgba(255,246,242,0.22)', color: '#FFF6F2', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none', transition: 'all 220ms var(--ease-soft)' };
window.ContactSection = ContactSection;
