/* ============================================================
   Rainbow Group — contact.jsx
   Contact.html — hero, body (4 info blocks + map / form),
   footer strip for suppliers + press.
   Per DESIGN-SYSTEM.md §9.
   ============================================================ */

const { useState: useStateCt, useEffect: useEffectCt } = React;

function useCtKuwaitTime() {
  const [t, setT] = useStateCt('');
  useEffectCt(() => {
    const tick = () => {
      try { setT(new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Kuwait' })); }
      catch (e) { setT(new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })); }
    };
    tick();
    const id = setInterval(tick, 60000);
    return () => clearInterval(id);
  }, []);
  return t;
}

function ContactHero() {
  const ref = useReveal();
  const time = useCtKuwaitTime();
  return (
    <header ref={ref} className="reveal" style={{ background: 'var(--paper)', paddingTop: 160, paddingBottom: 64 }}>
      <div className="wrap">
        <div className="eyebrow" style={{ marginBottom: 32 }}>Contact · تواصل</div>
        <h1 className="display" style={{ fontSize: 'clamp(56px, 10vw, 180px)', maxWidth: '11ch', lineHeight: 0.92 }}>
          Write to us. <em style={{ color: 'var(--gold)', fontStyle: 'italic' }}>We read</em> each one.
        </h1>
        <div className="ar" style={{ fontSize: 'clamp(28px, 3.4vw, 52px)', color: 'var(--muted)', marginTop: 20 }}>اكتبوا لنا. نقرأُ كلَّ رسالة.</div>
        <div style={{ display: 'flex', gap: 40, marginTop: 56, fontSize: 13, color: 'var(--muted)', flexWrap: 'wrap' }}>
          <span>— Kuwait City, {time || '—'}</span>
          <span>N 29.3759° · E 47.9774°</span>
          <span>Replies within 48 hours</span>
        </div>
      </div>
    </header>
  );
}

function Block({ label, children }) {
  return (
    <div style={{ borderTop: '1px solid var(--ink)', padding: '24px 0 32px' }}>
      <div className="mono" style={{ color: 'var(--muted)', letterSpacing: '0.16em', marginBottom: 14 }}>{label}</div>
      {children}
    </div>
  );
}

/* ---------- Elegant custom dropdown ---------- */
function ElegantSelect({ options, value, onChange, placeholder = 'Select —' }) {
  const [open, setOpen] = useStateCt(false);
  const wrapRef = React.useRef(null);

  useEffectCt(() => {
    if (!open) return;
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: '100%' }}>
      <button type="button"
              onClick={() => setOpen(o => !o)}
              data-cursor-label={open ? 'CLOSE' : 'OPEN'}
              style={{
                width: '100%',
                background: 'transparent',
                border: 0,
                textAlign: 'left',
                padding: 0,
                fontFamily: "'Fraunces', serif",
                fontSize: 22,
                color: value ? 'var(--ink)' : 'var(--muted)',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 16,
                outline: 'none',
              }}>
        <span>{value || placeholder}</span>
        <span aria-hidden="true" style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 24, height: 24,
          color: open ? 'var(--gold)' : 'var(--muted)',
          transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          transition: 'transform 0.35s cubic-bezier(.2,.6,.2,1), color 0.3s ease',
          fontSize: 14, lineHeight: 1,
        }}>↓</span>
      </button>

      {open ? (
        <div role="listbox" style={{
          position: 'absolute',
          left: 0, right: 0, top: 'calc(100% + 14px)',
          background: 'var(--paper)',
          border: '1px solid var(--ink)',
          zIndex: 40,
          boxShadow: '0 28px 60px rgba(21,20,18,0.12)',
          maxHeight: 320,
          overflowY: 'auto',
        }}>
          {options.filter(o => o !== '').map((opt, i, arr) => {
            const selected = opt === value;
            return (
              <button key={opt} type="button"
                      role="option"
                      aria-selected={selected}
                      onClick={() => { onChange(opt); setOpen(false); }}
                      data-cursor-label="SELECT"
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        gap: 16,
                        width: '100%',
                        padding: '16px 20px',
                        background: 'transparent',
                        border: 0,
                        borderBottom: i < arr.length - 1 ? '1px solid var(--rule)' : 'none',
                        textAlign: 'left',
                        cursor: 'pointer',
                        fontFamily: "'Fraunces', serif",
                        fontSize: 18,
                        color: selected ? 'var(--gold)' : 'var(--ink)',
                        transition: 'background 0.2s ease, color 0.2s ease, padding-left 0.2s ease',
                      }}
                      onMouseEnter={(e) => {
                        if (!selected) { e.currentTarget.style.background = 'var(--paper-2)'; e.currentTarget.style.color = 'var(--gold)'; e.currentTarget.style.paddingLeft = '28px'; }
                      }}
                      onMouseLeave={(e) => {
                        if (!selected) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink)'; e.currentTarget.style.paddingLeft = '20px'; }
                      }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
                  <span style={{
                    width: 6, height: 6, borderRadius: '50%',
                    background: selected ? 'var(--gold)' : 'transparent',
                    border: selected ? 'none' : '1px solid var(--rule)',
                  }} />
                  {opt}
                </span>
                {selected ? <span className="mono" style={{ fontSize: 9, color: 'var(--gold)' }}>SELECTED</span> : null}
              </button>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

function ContactField({ label, ar, type = 'text', required = false, textarea = false, select = false, options, value, onChange, placeholder }) {
  const [focus, setFocus] = useStateCt(false);
  return (
    <label style={{
      display: 'block', padding: '22px 16px',
      borderBottom: '1px solid var(--rule)',
      background: focus ? 'rgba(168,132,59,0.04)' : 'transparent',
      transition: 'background 0.3s ease',
      cursor: select ? 'default' : 'text',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <span className="mono" style={{ color: focus ? 'var(--gold)' : 'var(--muted)', transition: 'color 0.3s ease' }}>
          {label}{required ? <span style={{ color: 'var(--gold)' }}> *</span> : null}
        </span>
        <span className="ar" style={{ fontSize: 12, color: 'var(--muted)' }}>{ar}</span>
      </div>
      {textarea ? (
        <textarea rows={4} value={value} onChange={(e) => onChange(e.target.value)} required={required}
                  onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
                  style={{ width: '100%', background: 'transparent', border: 0, fontFamily: "'Fraunces', serif", fontSize: 20, color: 'var(--ink)', outline: 'none', resize: 'vertical', lineHeight: 1.4 }} />
      ) : select ? (
        <div onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}>
          <ElegantSelect options={options} value={value} onChange={(v) => { onChange(v); }} placeholder={placeholder || 'Select —'} />
        </div>
      ) : (
        <input type={type} value={value} onChange={(e) => onChange(e.target.value)} required={required}
               onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
               style={{ width: '100%', background: 'transparent', border: 0, fontFamily: "'Fraunces', serif", fontSize: 22, color: 'var(--ink)', outline: 'none' }} />
      )}
    </label>
  );
}

function MapSVG() {
  const mono = (props, text) => <text {...props} fontFamily="JetBrains Mono, monospace" fontSize="7" letterSpacing="0.18em" textTransform="uppercase">{text}</text>;
  return (
    <div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 3', background: 'var(--paper)', border: '1px solid var(--rule)' }}>
      <svg viewBox="0 0 400 300" style={{ width: '100%', height: '100%', display: 'block' }}>
        <defs>
          <pattern id="map-grid" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="var(--rule)" strokeWidth="0.5" />
          </pattern>
        </defs>
        <rect width="400" height="300" fill="url(#map-grid)" />
        <path d="M 0 220 Q 80 200 150 210 Q 220 220 320 200 L 400 180 L 400 300 L 0 300 Z" fill="rgba(91,196,232,0.05)" stroke="var(--rule)" strokeWidth="0.5" />
        <line x1="0" y1="120" x2="400" y2="140" stroke="var(--ink-2)" strokeWidth="1" />
        <line x1="130" y1="0" x2="150" y2="300" stroke="var(--ink-2)" strokeWidth="1" />
        <line x1="250" y1="0" x2="260" y2="300" stroke="var(--muted)" strokeWidth="0.5" />
        <line x1="0" y1="60" x2="400" y2="70" stroke="var(--muted)" strokeWidth="0.5" />
        <line x1="0" y1="180" x2="400" y2="195" stroke="var(--muted)" strokeWidth="0.5" />
        <rect x="143" y="110" width="20" height="26" fill="var(--gold)" stroke="var(--ink)" strokeWidth="1" />
        <line x1="153" y1="136" x2="153" y2="260" stroke="var(--gold)" strokeWidth="0.5" strokeDasharray="2,2" />
        {mono({ x: 170, y: 120, fill: 'var(--ink)' }, '◉ RGCC · B1 SUAD COMPLEX')}
        {mono({ x: 170, y: 134, fill: 'var(--muted)' }, '29.3759°N · 47.9774°E')}
        {mono({ x: 10, y: 116, fill: 'var(--muted)' }, 'FAHD AL SALAM ST')}
        {mono({ x: 110, y: 25, fill: 'var(--muted)', transform: 'rotate(90 110 25)' }, 'MUBARAK AL KABEER ST')}
        {mono({ x: 10, y: 245, fill: 'var(--muted)' }, 'ARABIAN GULF')}
        <g transform="translate(360,40)">
          <circle r="14" fill="none" stroke="var(--ink-2)" strokeWidth="0.5" />
          <path d="M 0 -12 L 3 0 L 0 12 L -3 0 Z" fill="var(--ink-2)" />
          <text x="0" y="-18" fontFamily="JetBrains Mono, monospace" fontSize="8" textAnchor="middle" fill="var(--muted)">N</text>
        </g>
      </svg>
      <span className="mono" style={{ position: 'absolute', top: 8, left: 10, color: 'var(--muted)', fontSize: 9 }}>PLATE 01 — FAHD AL SALAM ST</span>
      <span className="mono" style={{ position: 'absolute', bottom: 8, right: 10, color: 'var(--muted)', fontSize: 9 }}>1 : 4000</span>
    </div>
  );
}

function ContactBody() {
  const ref = useReveal();
  const [name, setName] = useStateCt('');
  const [email, setEmail] = useStateCt('');
  const [phone, setPhone] = useStateCt('');
  const [company, setCompany] = useStateCt('');
  const [scope, setScope] = useStateCt('');
  const [budget, setBudget] = useStateCt('');
  const [brief, setBrief] = useStateCt('');
  const [sent, setSent] = useStateCt(false);
  const [sending, setSending] = useStateCt(false);
  const [errMsg, setErrMsg] = useStateCt('');

  const onSubmit = async (e) => {
    e.preventDefault();
    if (sending || sent) return;
    setErrMsg('');
    setSending(true);

    const payload = { name, email, phone, company, scope, budget, brief, website: '' };
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await r.json().catch(() => ({}));
      if (r.ok) {
        if (window.gtag) { try { window.gtag('event', 'contact_submit', { method: 'form' }); } catch (_) {} }
        setSent(true);
      } else {
        setErrMsg(data.error || 'Could not send. Please email info@rainbowgroup-kwt.com directly.');
      }
    } catch (err) {
      // No endpoint (local file-server, etc). Still flip to thank-you so user gets a clear state,
      // but nudge them to the direct email address.
      setSent(true);
      setErrMsg('Enquiry queued locally. For immediate reply, email info@rainbowgroup-kwt.com.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section ref={ref} className="reveal" style={{ background: 'var(--paper-2)', padding: '80px 0 120px' }}>
      <div className="wrap" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80 }} data-mobile-stack>
        {/* Left */}
        <div>
          <Block label="Office · المقر">
            <div style={{ fontFamily: "'Fraunces', serif", fontSize: 16, lineHeight: 1.5 }}>
              B1 Suad Complex,<br/>
              Fahad Al Salam Street,<br/>
              Kuwait City, Kuwait
            </div>
            <div className="ar" style={{ fontSize: 15, color: 'var(--muted)', marginTop: 10 }}>مجمع سعاد بي ١، شارع فهد السالم، مدينة الكويت</div>
          </Block>
          <Block label="Direct · مباشر">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 15 }}>
              <a href="mailto:info@rainbowgroup-kwt.com" style={{ borderBottom: '1px solid var(--rule)' }}>info@rainbowgroup-kwt.com</a>
              <a href="mailto:projects@rainbowgroup-kwt.com" style={{ borderBottom: '1px solid var(--rule)' }}>projects@rainbowgroup-kwt.com</a>
              <span>+965 · 2241 0045</span>
              <span style={{ color: 'var(--muted)' }}>+965 · 2241 0046 (fax)</span>
            </div>
            <div style={{ marginTop: 20, color: 'var(--ink)' }}>
              <SocialIcons variant="light" />
            </div>
          </Block>
          <Block label="Hours · ساعات">
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--rule)' }}><span>Sun — Thu</span><span className="mono">08:30 — 17:30</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--rule)' }}><span>Friday</span><span className="mono">Closed</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0' }}><span>Saturday</span><span className="mono">By appointment</span></div>
            </div>
          </Block>
          <Block label="Approach · الوصول">
            <MapSVG />
          </Block>
        </div>

        {/* Right — Form */}
        <form onSubmit={onSubmit} style={{ borderTop: '1px solid var(--ink)' }}>
          <div className="mono" style={{ color: 'var(--muted)', padding: '18px 0 6px' }}>Project enquiry form · استمارة</div>

          <ContactField label="Full name" ar="الاسم الكامل" value={name} onChange={setName} required />
          <div className="form-two-col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }} data-mobile-stack>
            <ContactField label="Email"  ar="البريد" type="email" value={email} onChange={setEmail} required />
            <ContactField label="Phone"  ar="هاتف"   type="tel"   value={phone} onChange={setPhone} />
          </div>
          <ContactField label="Company / capacity" ar="الجهة" value={company} onChange={setCompany} />
          <ContactField label="Project scope" ar="نطاق" select options={['', 'Turnkey fit-out', 'Interior finishing', 'GRG / GRC / gypsum', 'Joinery only', 'Flooring only', 'Specialty paint / gold leaf', 'Other']} value={scope} onChange={setScope} />
          <ContactField label="Indicative budget" ar="الميزانية" select options={['', 'Under KWD 50,000', 'KWD 50,000 — 250,000', 'KWD 250,000 — 1M', 'KWD 1M — 5M', 'Over KWD 5M', 'Prefer not to say']} value={budget} onChange={setBudget} />
          <ContactField label="Tell us about the project" ar="تفاصيل المشروع" textarea value={brief} onChange={setBrief} required />

          {/* Honeypot — hidden from humans + screen readers, visible to bots */}
          <input
            type="text"
            name="website"
            autoComplete="off"
            tabIndex={-1}
            aria-hidden="true"
            style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
            onChange={() => {}}
          />

          <button type="submit" disabled={sent || sending} style={{
            marginTop: 32, padding: '22px 28px', width: '100%',
            background: sent ? 'var(--ink-2)' : (sending ? 'var(--muted)' : 'var(--gold)'),
            color: 'var(--paper)', border: 0,
            fontFamily: "'Inter Tight', sans-serif", fontSize: 13, letterSpacing: '0.12em', textTransform: 'uppercase',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            cursor: (sent || sending) ? 'default' : 'pointer',
            transition: 'background 0.4s ease',
          }}>
            <span>{sent ? 'Received — we will reply within 48 hours' : (sending ? 'Sending…' : 'Send enquiry')}</span>
            <span>{sent ? '✓' : (sending ? '…' : '→')}</span>
          </button>
          {errMsg ? (
            <p className="mono" style={{ color: 'var(--gold)', marginTop: 14, fontSize: 11 }}>{errMsg}</p>
          ) : (
            <p className="mono" style={{ color: 'var(--muted)', marginTop: 14 }}>Your enquiry will reach Rizwan Bhati (General Manager) directly.</p>
          )}
        </form>
      </div>
    </section>
  );
}

function ContactFooterStrip() {
  const ref = useReveal();
  return (
    <section ref={ref} className="reveal" style={{ background: 'var(--ink)', color: '#f3ede2', padding: '80px 0' }}>
      <div className="wrap" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'end' }} data-mobile-stack>
        <div>
          <div className="mono" style={{ color: 'rgba(243,237,226,0.55)', marginBottom: 14 }}>For suppliers</div>
          <p style={{ fontFamily: "'Fraunces', serif", fontSize: 22, lineHeight: 1.35, marginBottom: 18 }}>
            Long-standing partnerships with Knauf, Mannington, Recer Cerâmica, Sitab, Strähle.
          </p>
          <a href="mailto:procurement@rainbowgroup-kwt.com" className="mono" style={{ color: 'var(--gold-hi)' }}>procurement@rainbowgroup-kwt.com <span style={{ marginLeft: 4 }}>→</span></a>
        </div>
        <div>
          <div className="mono" style={{ color: 'rgba(243,237,226,0.55)', marginBottom: 14 }}>For press</div>
          <p style={{ fontFamily: "'Fraunces', serif", fontSize: 22, lineHeight: 1.35, marginBottom: 18 }}>
            Project photography & interview requests.
          </p>
          <a href="mailto:press@rainbowgroup-kwt.com" className="mono" style={{ color: 'var(--gold-hi)' }}>press@rainbowgroup-kwt.com <span style={{ marginLeft: 4 }}>→</span></a>
        </div>
      </div>
    </section>
  );
}

function ContactApp() {
  useEffectCt(() => {
    const h = document.documentElement;
    h.setAttribute('data-palette', 'archival');
    h.setAttribute('data-motif', 'subtle');
    h.setAttribute('data-motion', 'combination');
    h.setAttribute('data-cursor', 'custom');
    h.setAttribute('data-signature', 'off');
  }, []);

  return (
    <React.Fragment>
      <SharedNav currentPath="Contact.html" />
      <ContactHero />
      <ContactBody />
      <ContactFooterStrip />
      <SharedFooter />
      <RGCursor />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ContactApp />);
