// pages-contact.jsx — Contact page for ruuapi.com

function ContactPage({ accent }) {
  const { t } = useT();
  const isMobile = useMobile(960);
  const [status, setStatus] = React.useState('idle'); // idle | sending | success | ratelimit | error
  const [ticketId, setTicketId] = React.useState('');
  const [form, setForm] = React.useState({
    name: '',
    email: '',
    company: '',
    intent: 'sales',
    message: ''
  });
  const [validationError, setValidationError] = React.useState(false);

  const _accent = accent || 'var(--accent)';

  const inputStyle = {
    width: '100%',
    padding: '14px 16px',
    border: '2px solid var(--ink)',
    background: 'var(--paper)',
    fontFamily: 'var(--sans)',
    fontSize: '15px',
    outline: 'none',
    borderRadius: '0',
    marginBottom: '16px',
    color: 'var(--ink)',
    transition: 'border-color 0.15s ease',
    display: 'block',
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    if (validationError) setValidationError(false);
  };

  const validate = () => {
    const ok = form.name.trim() !== '' &&
               form.email.includes('@') &&
               form.message.trim().length >= 10;
    if (!ok) setValidationError(true);
    return ok;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setStatus('sending');
    try {
      const resp = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.company || undefined,
          intent: form.intent,
          message: form.message,
        }),
      });
      if (resp.status === 200) {
        const data = await resp.json();
        setTicketId(data.ticket_id || '');
        setStatus('success');
      } else if (resp.status === 429) {
        setStatus('ratelimit');
      } else {
        setStatus('error');
      }
    } catch (_) {
      setStatus('error');
    }
  };

  const channelBox = (emoji, label, value, href) => (
    React.createElement('a', {
      href,
      target: href.startsWith('http') ? '_blank' : undefined,
      rel: href.startsWith('http') ? 'noreferrer noopener' : undefined,
      style: { textDecoration: 'none', color: 'inherit', display: 'block' },
    },
      React.createElement('div', {
        style: {
          background: 'var(--paper)',
          border: '2px solid var(--ink)',
          padding: '16px 20px',
          boxShadow: '4px 4px 0 var(--ink)',
          cursor: 'pointer',
          transition: 'transform 0.15s ease, box-shadow 0.15s ease',
        },
        onMouseEnter: e => { e.currentTarget.style.transform = 'translate(-2px,-2px)'; e.currentTarget.style.boxShadow = '6px 6px 0 var(--ink)'; },
        onMouseLeave: e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '4px 4px 0 var(--ink)'; },
      },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 } },
          React.createElement('span', null, emoji),
          React.createElement('span', { className: 'mono', style: { fontSize: 11, letterSpacing: '0.08em', opacity: 0.6, textTransform: 'uppercase' } }, label),
        ),
        React.createElement('div', { style: { fontWeight: 700, fontSize: 15, fontFamily: 'var(--mono)' } }, value),
      )
    )
  );

  return (
    <div className="ruu" style={{ background: 'var(--paper)', color: 'var(--ink)', minHeight: '100vh' }}>

      {/* Trust strip */}
      <div style={{ background: _accent, borderBottom: '2px solid var(--ink)', padding: '8px 24px', textAlign: 'center' }}>
        <span className="mono" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          {t('contact.trust')}
        </span>
      </div>

      {/* Hero */}
      <section style={{ padding: isMobile ? '56px 24px 48px' : '80px 56px 64px', borderBottom: '4px solid var(--ink)' }}>
        <div style={{ maxWidth: 820 }}>
          <span className="stamp" style={{ background: _accent, borderColor: 'var(--ink)', marginBottom: 20, display: 'inline-block' }}>
            {t('contact.stamp')}
          </span>
          <h1 className="serif" style={{ fontSize: 'clamp(48px, 7vw, 96px)', lineHeight: 0.91, margin: '0 0 20px', letterSpacing: '-0.03em' }}>
            {t('contact.hero.title')}
          </h1>
          <p style={{ fontSize: 18, color: 'var(--ink-2)', margin: 0, maxWidth: 560, lineHeight: 1.6 }}>
            {t('contact.hero.sub')}
          </p>
        </div>
      </section>

      {/* Main 2-col grid */}
      <section style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.3fr 1fr',
        borderBottom: '4px solid var(--ink)',
      }}>

        {/* LEFT — form */}
        <div style={{ padding: isMobile ? '40px 24px' : '56px', borderRight: isMobile ? 'none' : '4px solid var(--ink)', borderBottom: isMobile ? '4px solid var(--ink)' : 'none' }}>

          {status === 'success' ? (
            <div style={{ background: _accent, border: '2px solid var(--ink)', padding: '40px', boxShadow: '4px 4px 0 var(--ink)' }}>
              <h2 className="serif" style={{ fontSize: 36, margin: '0 0 12px', lineHeight: 1 }}>
                {t('contact.success.title')}
              </h2>
              <p className="mono" style={{ fontSize: 13, letterSpacing: '0.08em', marginBottom: 16, opacity: 0.8 }}>
                TICKET {ticketId}
              </p>
              <p style={{ fontFamily: 'var(--sans)', fontSize: 16, margin: '0 0 24px', lineHeight: 1.6 }}>
                {t('contact.success.body')}
              </p>
              <button className="btn btn-ghost" onClick={() => { setStatus('idle'); setForm({ name:'', email:'', company:'', intent:'sales', message:'' }); }}>
                Send another
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate>
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: '0 16px' }}>
                <input
                  type="text" name="name" placeholder={t('contact.form.name')}
                  style={inputStyle} value={form.name} onChange={handleChange} autoComplete="name"
                />
                <input
                  type="email" name="email" placeholder={t('contact.form.email')}
                  style={inputStyle} value={form.email} onChange={handleChange} autoComplete="email"
                />
              </div>
              <input
                type="text" name="company" placeholder={t('contact.form.company')}
                style={inputStyle} value={form.company} onChange={handleChange} autoComplete="organization"
              />
              <select
                name="intent"
                style={{ ...inputStyle, cursor: 'pointer', appearance: 'none', backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\'%3E%3Cpath d=\'M0 0l6 8 6-8z\' fill=\'%230e1116\'/%3E%3C/svg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 16px center', paddingRight: 36 }}
                value={form.intent} onChange={handleChange}
              >
                <option value="sales">{t('contact.intent.sales')}</option>
                <option value="support">{t('contact.intent.support')}</option>
                <option value="partnership">{t('contact.intent.partnership')}</option>
                <option value="press">{t('contact.intent.press')}</option>
                <option value="other">{t('contact.intent.other')}</option>
              </select>
              <textarea
                name="message" rows={6} placeholder={t('contact.form.message')}
                style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }}
                value={form.message} onChange={handleChange}
              />

              {validationError && (
                <p className="mono" style={{ color: '#d32f2f', fontSize: 12, marginBottom: 12, letterSpacing: '0.04em' }}>
                  {t('contact.form.error.required')}
                </p>
              )}
              {status === 'ratelimit' && (
                <p className="mono" style={{ color: '#d32f2f', fontSize: 12, marginBottom: 12, letterSpacing: '0.04em' }}>
                  {t('contact.error.ratelimit')}
                </p>
              )}
              {status === 'error' && (
                <p className="mono" style={{ color: '#d32f2f', fontSize: 12, marginBottom: 12, letterSpacing: '0.04em' }}>
                  {t('contact.error.generic')}{' '}
                  <a href="mailto:info@ndr.ist" style={{ color: 'inherit' }}>info@ndr.ist</a>
                </p>
              )}

              <button
                type="submit"
                className="btn btn-accent"
                disabled={status === 'sending'}
                style={{ width: '100%', justifyContent: 'center', fontSize: 15, opacity: status === 'sending' ? 0.7 : 1 }}
              >
                {status === 'sending' ? (
                  <>
                    {t('contact.form.sending')}
                    <span style={{ display: 'inline-block', width: 60, height: 2, background: 'var(--ink)', marginLeft: 8, animation: 'ruu-cursor-sweep 1.4s linear infinite', verticalAlign: 'middle' }} />
                  </>
                ) : t('contact.form.submit')}
              </button>
            </form>
          )}
        </div>

        {/* RIGHT — direct channels */}
        <aside style={{ padding: isMobile ? '40px 24px' : '48px 40px', background: 'var(--paper-2)' }}>
          <h3 className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 24, opacity: 0.7 }}>
            {t('contact.sidebar.title')}
          </h3>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {channelBox('✉', 'Email', 'info@ndr.ist', 'mailto:info@ndr.ist')}
            {channelBox('𝕏', 'Twitter / X', '@ruuapi', 'https://twitter.com/ruuapi')}
            {channelBox('⚙', 'GitHub Issues', 'Open an issue', 'https://github.com/mehmetnadir/blog-writer-for-seo-and-geo/issues')}
          </div>

          <p className="mono" style={{ fontSize: 11, marginTop: 32, color: 'var(--ink-3)', lineHeight: 1.7, letterSpacing: '0.03em' }}>
            {t('contact.sidebar.response')}
          </p>
        </aside>
      </section>

      {/* FAQ accordion */}
      <section style={{ padding: isMobile ? '48px 24px' : '64px 56px', borderBottom: '4px solid var(--ink)' }}>
        <h2 className="serif" style={{ fontSize: 'clamp(36px, 5vw, 64px)', margin: '0 0 40px', lineHeight: 0.95 }}>
          {t('contact.faq.title')}
        </h2>
        <div style={{ maxWidth: 760 }}>
          {[1, 2, 3, 4].map(idx => (
            React.createElement('details', {
              key: idx,
              style: { borderBottom: '2px solid var(--ink)' },
            },
              React.createElement('summary', {
                style: {
                  padding: '20px 0',
                  cursor: 'pointer',
                  fontWeight: 600,
                  fontFamily: 'var(--sans)',
                  fontSize: 16,
                  listStyle: 'none',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  userSelect: 'none',
                },
              },
                React.createElement('span', null, t(`contact.faq.q${idx}`)),
                React.createElement('span', { style: { fontSize: 22, fontWeight: 300, flexShrink: 0, marginLeft: 16 } }, '+'),
              ),
              React.createElement('div', {
                style: { padding: '0 0 24px', color: 'var(--ink-2)', lineHeight: 1.65, fontFamily: 'var(--sans)', fontSize: 16 },
              }, t(`contact.faq.a${idx}`)),
            )
          ))}
        </div>
      </section>

      <style>{`
        .ruu details[open] > summary span:last-child { content: '−'; transform: none; }
        .ruu summary::-webkit-details-marker { display: none; }
        .ruu input:focus, .ruu select:focus, .ruu textarea:focus { border-color: var(--accent) !important; box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 30%, transparent); }
      `}</style>
    </div>
  );
}

Object.assign(window, { ContactPage });
