// Contact.jsx — Maison Gifts
// Contact channels · 3-step quotation form (validation + success) · Footer.

const Field = ({ label, error, children }) =>
<div>
    <label style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500, color: 'var(--navy-ink)', marginBottom: 7 }}>{label}</label>
    {children}
    {error && <span style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--burgundy)', marginTop: 5 }}>{error}</span>}
  </div>;


const inputBase = (invalid) => ({
  fontFamily: 'var(--font-sans)', fontSize: 15, color: 'var(--navy-ink)', width: '100%',
  background: 'var(--cream)', border: `1px solid ${invalid ? 'var(--burgundy)' : 'var(--grey-line)'}`,
  borderRadius: 'var(--radius-md)', padding: '12px 14px', outline: 'none',
  transition: 'border-color 150ms ease, box-shadow 150ms ease', boxSizing: 'border-box'
});

const QuoteForm = () => {
  const c = useContent();
  const f = c.contact;
  const [step, setStep] = React.useState(0);
  const [sent, setSent] = React.useState(false);
  const [touched, setTouched] = React.useState(false);
  const [form, setForm] = React.useState({
    name: '', company: '', email: '', phone: '',
    productType: '', quantity: '', budget: '', timeline: '', message: ''
  });

  const set = (k, v) => setForm((prev) => ({ ...prev, [k]: v }));
  const emailOk = /.+@.+\..+/.test(form.email);

  // WhatsApp business number (digits only, country code, no +/spaces)
  const WHATSAPP_NUMBER = '6281282880550';

  const buildMessage = () => {
    const F = f.fields;
    const lines = [
      '*' + f.title + ' — Maison Gifts*',
      '',
      F.name + ': ' + form.name,
      F.company + ': ' + form.company,
      F.email + ': ' + form.email,
      F.phone + ': ' + form.phone,
      '',
      F.productType + ': ' + form.productType,
      F.quantity + ': ' + form.quantity,
      F.budget + ': ' + form.budget,
      F.timeline + ': ' + form.timeline,
    ];
    if (form.message.trim()) {
      lines.push('', F.message + ': ' + form.message.trim());
    }
    return lines.join('\n');
  };

  const waUrl = () => 'https://wa.me/' + WHATSAPP_NUMBER + '?text=' + encodeURIComponent(buildMessage());

  const stepValid = (s) => {
    if (s === 0) return form.name.trim() && form.company.trim() && emailOk && form.phone.trim();
    if (s === 1) return form.productType && form.quantity && form.budget && form.timeline;
    return true;
  };

  const next = () => {
    if (!stepValid(step)) {setTouched(true);return;}
    setTouched(false);
    setStep((s) => Math.min(s + 1, 2));
  };
  const back = () => {setTouched(false);setStep((s) => Math.max(s - 1, 0));};
  const submit = () => {
    // Open WhatsApp with the brief pre-filled, then show confirmation
    window.open(waUrl(), '_blank', 'noopener');
    setSent(true);
  };
  const reset = () => {setSent(false);setStep(0);setTouched(false);setForm({ name: '', company: '', email: '', phone: '', productType: '', quantity: '', budget: '', timeline: '', message: '' });};

  const focusRing = (e) => {e.target.style.borderColor = 'var(--burgundy)';e.target.style.boxShadow = '0 0 0 3px rgba(122,42,56,0.12)';};
  const blurRing = (e, invalid) => {e.target.style.borderColor = invalid ? 'var(--burgundy)' : 'var(--grey-line)';e.target.style.boxShadow = 'none';};

  const selectEl = (key) =>
  <select value={form[key]} onChange={(e) => set(key, e.target.value)}
  onFocus={focusRing} onBlur={(e) => blurRing(e, touched && !form[key])}
  style={{ ...inputBase(touched && !form[key]), appearance: 'none', cursor: 'pointer',
    backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%237A2A38' stroke-width='2'><path d='M6 9l6 6 6-6'/></svg>\")",
    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center', paddingRight: 38,
    color: form[key] ? 'var(--navy-ink)' : 'var(--grey)' }}>
      <option value="" disabled>—</option>
      {f.options[key].map((o) => <option key={o} value={o} style={{ color: 'var(--navy-ink)' }}>{o}</option>)}
    </select>;


  if (sent) {
    return (
      <div style={{ background: 'var(--ivory)', border: '1px solid var(--grey-line)', borderRadius: 'var(--radius-xl)', padding: 'var(--space-12) var(--space-8)', textAlign: 'center', boxShadow: 'var(--shadow-whisper)' }}>
        <span style={{ width: 64, height: 64, borderRadius: 'var(--radius-full)', background: 'rgba(122,42,56,0.1)', color: 'var(--burgundy)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
          <i data-lucide="check" style={{ width: 30, height: 30, strokeWidth: 2 }}></i>
        </span>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 30, color: 'var(--navy-ink)', margin: 0 }}>{f.success.title}</h3>
        <p style={{ fontFamily: 'var(--font-sans)', fontWeight: 300, fontSize: 16, lineHeight: 1.65, color: 'var(--text-2)', margin: '14px auto 0', maxWidth: 420 }}>{f.success.body}</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'center', marginTop: 28 }}>
          <a href={waUrl()} target="_blank" rel="noopener noreferrer" style={{ fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500, background: 'var(--burgundy)', color: '#F6F1E6', textDecoration: 'none', padding: '12px 24px', borderRadius: 'var(--radius-full)', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <i data-lucide="message-circle" style={{ width: 16, height: 16, strokeWidth: 2 }}></i>
            {f.success.open}
          </a>
          <button onClick={reset} style={{ fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500, background: 'transparent', color: 'var(--burgundy)', border: '1px solid var(--burgundy)', cursor: 'pointer', padding: '12px 24px', borderRadius: 'var(--radius-full)' }}>{f.success.again}</button>
        </div>
      </div>);

  }

  return (
    <div style={{ background: 'var(--ivory)', border: '1px solid var(--grey-line)', borderRadius: 'var(--radius-xl)', padding: 'var(--space-8)', boxShadow: 'var(--shadow-whisper)' }}>
      {/* Stepper */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 'var(--space-8)' }}>
        {f.steps.map((label, i) =>
        <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
              <span style={{
              width: 30, height: 30, borderRadius: 'var(--radius-full)', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
              background: i <= step ? 'var(--burgundy)' : 'var(--cream-deep)',
              color: i <= step ? '#F6F1E6' : 'var(--grey)',
              border: i <= step ? 'none' : '1px solid var(--grey-line)', transition: 'all 200ms ease'
            }}>{i < step ? '✓' : i + 1}</span>
              <span className="mg-step-label" style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: i === step ? 600 : 400, color: i <= step ? 'var(--navy-ink)' : 'var(--grey)' }}>{label}</span>
            </div>
            {i < f.steps.length - 1 && <span style={{ flex: 1, height: 1, background: 'var(--grey-line)', margin: '0 14px', minWidth: 16 }}></span>}
          </React.Fragment>
        )}
      </div>

      <p style={{ fontFamily: 'var(--font-sans)', fontWeight: 300, fontSize: 15, color: 'var(--text-2)', margin: '0 0 22px' }}>{f.stepHint[step]}</p>

      {/* Step 0 */}
      {step === 0 &&
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Field label={f.fields.name} error={touched && !form.name.trim() ? f.required : ''}>
            <input style={inputBase(touched && !form.name.trim())} placeholder={f.placeholders.name} value={form.name} onChange={(e) => set('name', e.target.value)} onFocus={focusRing} onBlur={(e) => blurRing(e, touched && !form.name.trim())} />
          </Field>
          <Field label={f.fields.company} error={touched && !form.company.trim() ? f.required : ''}>
            <input style={inputBase(touched && !form.company.trim())} placeholder={f.placeholders.company} value={form.company} onChange={(e) => set('company', e.target.value)} onFocus={focusRing} onBlur={(e) => blurRing(e, touched && !form.company.trim())} />
          </Field>
          <Field label={f.fields.email} error={touched && !emailOk ? f.required : ''}>
            <input type="email" style={inputBase(touched && !emailOk)} placeholder={f.placeholders.email} value={form.email} onChange={(e) => set('email', e.target.value)} onFocus={focusRing} onBlur={(e) => blurRing(e, touched && !emailOk)} />
          </Field>
          <Field label={f.fields.phone} error={touched && !form.phone.trim() ? f.required : ''}>
            <input style={inputBase(touched && !form.phone.trim())} placeholder={f.placeholders.phone} value={form.phone} onChange={(e) => set('phone', e.target.value)} onFocus={focusRing} onBlur={(e) => blurRing(e, touched && !form.phone.trim())} />
          </Field>
        </div>
      }

      {/* Step 1 */}
      {step === 1 &&
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Field label={f.fields.productType} error={touched && !form.productType ? f.required : ''}>{selectEl('productType')}</Field>
          <Field label={f.fields.quantity} error={touched && !form.quantity ? f.required : ''}>{selectEl('quantity')}</Field>
          <Field label={f.fields.budget} error={touched && !form.budget ? f.required : ''}>{selectEl('budget')}</Field>
          <Field label={f.fields.timeline} error={touched && !form.timeline ? f.required : ''}>{selectEl('timeline')}</Field>
        </div>
      }

      {/* Step 2 */}
      {step === 2 &&
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <Field label={f.fields.message}>
            <textarea rows={4} style={{ ...inputBase(false), resize: 'vertical', lineHeight: 1.6 }} placeholder={f.placeholders.message} value={form.message} onChange={(e) => set('message', e.target.value)} onFocus={focusRing} onBlur={(e) => blurRing(e, false)} />
          </Field>
          {/* Review summary */}
          <div style={{ background: 'var(--cream)', border: '1px solid var(--grey-line)', borderRadius: 'var(--radius-md)', padding: 'var(--space-5)' }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--burgundy)', marginBottom: 14 }}>{f.review}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 24px' }}>
              {[
            [f.fields.name, form.name], [f.fields.company, form.company],
            [f.fields.email, form.email], [f.fields.phone, form.phone],
            [f.fields.productType, form.productType], [f.fields.quantity, form.quantity],
            [f.fields.budget, form.budget], [f.fields.timeline, form.timeline]].
            map(([k, v], i) =>
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, borderBottom: '1px solid var(--grey-line)', paddingBottom: 8 }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--grey)' }}>{k}</span>
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500, color: 'var(--navy-ink)', textAlign: 'right' }}>{v || '—'}</span>
                </div>
            )}
            </div>
          </div>
        </div>
      }

      {/* Controls */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'var(--space-8)', gap: 12 }}>
        <button onClick={back} disabled={step === 0} style={{
          fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
          background: 'transparent', color: step === 0 ? 'var(--grey-line)' : 'var(--text-2)',
          border: 'none', cursor: step === 0 ? 'default' : 'pointer', padding: '12px 8px',
          display: 'inline-flex', alignItems: 'center', gap: 7
        }}>
          <i data-lucide="arrow-left" style={{ width: 15, height: 15, strokeWidth: 2 }}></i>{f.back}
        </button>

        {step < 2 ?
        <button onClick={next} style={{
          fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 500,
          background: 'var(--navy)', color: '#F6F1E6', border: 'none', cursor: 'pointer',
          padding: '13px 26px', borderRadius: 'var(--radius-full)', display: 'inline-flex', alignItems: 'center', gap: 8,
          transition: 'background 160ms ease'
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = 'var(--navy-900)'}
        onMouseLeave={(e) => e.currentTarget.style.background = 'var(--navy)'}>
            {f.next}<i data-lucide="arrow-right" style={{ width: 15, height: 15, strokeWidth: 2 }}></i>
          </button> :

        <button onClick={submit} style={{
          fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 500,
          background: 'var(--burgundy)', color: '#F6F1E6', border: 'none', cursor: 'pointer',
          padding: '13px 28px', borderRadius: 'var(--radius-full)', display: 'inline-flex', alignItems: 'center', gap: 8,
          transition: 'background 160ms ease'
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = 'var(--burgundy-deep)'}
        onMouseLeave={(e) => e.currentTarget.style.background = 'var(--burgundy)'}>
            {f.submit}<i data-lucide="send" style={{ width: 15, height: 15, strokeWidth: 2 }}></i>
          </button>
        }
      </div>
    </div>);

};

const ContactChannels = () => {
  const c = useContent();
  const ch = c.contact.channels;
  const rows = [
  { icon: 'message-circle', label: ch.whatsappLabel, value: ch.whatsapp, href: 'https://wa.me/6281282880550' },
  { icon: 'mail', label: ch.emailLabel, value: ch.email, href: 'mailto:' + ch.email },
  { icon: 'instagram', label: ch.instagramLabel, value: ch.instagram, href: 'https://instagram.com/maisongifts.id' },
  { icon: 'map-pin', label: ch.locationLabel, value: ch.location, href: null }];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {rows.map((r, i) => {
        const inner =
        <div style={{ display: 'flex', alignItems: 'center', gap: 15 }}>
            <span style={{ width: 46, height: 46, borderRadius: 'var(--radius-md)', flexShrink: 0, background: 'var(--navy)', color: '#F6F1E6', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <i data-lucide={r.icon} style={{ width: 20, height: 20, strokeWidth: 1.5 }}></i>
            </span>
            <div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11.5, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--grey)' }}>{r.label}</div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 16, fontWeight: 500, color: 'var(--navy-ink)', marginTop: 3 }}>{r.value}</div>
            </div>
          </div>;

        const cardStyle = {
          background: 'var(--ivory)', border: '1px solid var(--grey-line)', borderRadius: 'var(--radius-lg)',
          padding: 'var(--space-4) var(--space-5)', textDecoration: 'none', display: 'block',
          transition: 'border-color 180ms ease, transform 180ms ease'
        };
        return r.href ?
        <a key={i} href={r.href} target="_blank" rel="noopener noreferrer" style={cardStyle}
        onMouseEnter={(e) => {e.currentTarget.style.borderColor = 'var(--burgundy)';e.currentTarget.style.transform = 'translateX(3px)';}}
        onMouseLeave={(e) => {e.currentTarget.style.borderColor = 'var(--grey-line)';e.currentTarget.style.transform = 'none';}}>{inner}</a> :

        <div key={i} style={cardStyle}>{inner}</div>;

      })}
    </div>);

};

const Contact = () => {
  const c = useContent();
  return (
    <section id="contact" style={{ background: 'var(--cream-deep)', padding: 'var(--space-32) var(--space-8)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div className="mg-contact-grid" style={{ display: 'grid', gridTemplateColumns: '0.82fr 1.18fr', gap: 'var(--space-16)', alignItems: 'start' }}>
          <Reveal>
            <Overline>{c.contact.overline}</Overline>
            <h2 style={{ fontWeight: 500, color: 'var(--navy-ink)', fontSize: 'clamp(34px,4vw,54px)', lineHeight: 1.08, letterSpacing: '-0.01em', margin: '20px 0 0', fontFamily: "serif" }}>{c.contact.title}</h2>
            <p style={{ fontFamily: 'var(--font-sans)', fontWeight: 300, fontSize: 17.5, lineHeight: 1.7, color: 'var(--text-2)', margin: '16px 0 var(--space-8)', maxWidth: 380 }}>{c.contact.sub}</p>
            <ContactChannels />
          </Reveal>
          <Reveal delay={120}>
            <QuoteForm />
          </Reveal>
        </div>
      </div>
    </section>);

};

// ── Footer ───────────────────────────────────────────────────
const Footer = () => {
  const c = useContent();
  const cats = c.categories.items.map((i) => i.name).slice(0, 6);
  return (
    <footer style={{ background: 'var(--navy-900)', color: '#F6F1E6', padding: 'var(--space-24) var(--space-8) var(--space-10)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div className="mg-foot-grid" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 'var(--space-12)' }}>
          <div>
            <button onClick={() => scrollToId('top')} aria-label="Maison Gifts home" style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>
              <img src={IMG.logo} alt="Maison Gifts" style={{ width: 196, height: 'auto', display: 'block', borderRadius: 'var(--radius-lg)' }} />
            </button>
            <p style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20, color: 'var(--burgundy-soft)', margin: '24px 0 0', lineHeight: 1.4, maxWidth: 320 }}>{c.footer.tagline}</p>
            <p style={{ fontFamily: 'var(--font-sans)', fontWeight: 300, fontSize: 14.5, lineHeight: 1.7, color: 'rgba(246,241,230,0.6)', margin: '16px 0 0', maxWidth: 340 }}>{c.footer.blurb}</p>
          </div>

          <div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(246,241,230,0.5)', marginBottom: 18 }}>{c.footer.colExplore}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              {c.nav.links.map((l) =>
              <button key={l.id} onClick={() => scrollToId(l.id)} style={{ fontFamily: 'var(--font-sans)', fontSize: 14.5, fontWeight: 300, color: 'rgba(246,241,230,0.78)', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: 0, transition: 'color 150ms ease' }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'var(--burgundy-soft)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(246,241,230,0.78)'}>{l.label}</button>
              )}
            </div>
          </div>

          <div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(246,241,230,0.5)', marginBottom: 18 }}>{c.footer.colCategories}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              {cats.map((name, i) =>
              <button key={i} onClick={() => scrollToId('products')} style={{ fontFamily: 'var(--font-sans)', fontSize: 14.5, fontWeight: 300, color: 'rgba(246,241,230,0.78)', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: 0, transition: 'color 150ms ease' }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'var(--burgundy-soft)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(246,241,230,0.78)'}>{name}</button>
              )}
            </div>
          </div>

          <div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(246,241,230,0.5)', marginBottom: 18 }}>{c.footer.colContact}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11, fontFamily: 'var(--font-sans)', fontSize: 14.5, fontWeight: 300, color: 'rgba(246,241,230,0.78)' }}>
              <span>{c.contact.channels.whatsapp}</span>
              <span>{c.contact.channels.email}</span>
              <span>{c.contact.channels.instagram}</span>
              <span>{c.contact.channels.location}</span>
            </div>
          </div>
        </div>

        <div style={{ borderTop: '1px solid rgba(246,241,230,0.12)', marginTop: 'var(--space-16)', paddingTop: 'var(--space-6)', display: 'flex', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'rgba(246,241,230,0.45)' }}>{c.footer.rights}</span>
          <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'rgba(246,241,230,0.32)', maxWidth: 620, textAlign: 'right' }}>{c.footer.keywords}</span>
        </div>
      </div>
    </footer>);

};

Object.assign(window, { Contact, QuoteForm, ContactChannels, Footer });