// Contact modal. Opens from every CTA and the footer "Inquiry" link.
// Submits silently to FormSubmit.co/ajax which relays the fields to
// orxnge.com@gmail.com as a formatted email. The visitor never sees this.
const ORX_FORMSUBMIT = 'https://formsubmit.co/ajax/orxnge.com@gmail.com';

const Field = ({ label, value, setter, multi, placeholder, type = 'text' }) => {
  const [focused, setFocused] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  const lit = focused || hovered;
  const base = {
    background: lit ? 'rgba(245,238,228,0.07)' : 'rgba(245,238,228,0.04)',
    border: `1px solid ${focused ? '#FFA566' : (hovered ? 'rgba(255,250,245,0.45)' : 'rgba(245,238,228,0.1)')}`,
    boxShadow: focused ? '0 0 0 3px rgba(255,106,10,0.14)' : 'none',
    borderRadius: 10, padding: '12px 14px',
    fontSize: 14, color: '#FFFAF5',
    fontFamily: "'Inter Tight', sans-serif", outline: 'none',
    // Force the input to fill its grid cell — browsers default to a
    // fixed character count via the input `size` attribute, which made
    // the Email field in the two-column row spill past its column.
    width: '100%', boxSizing: 'border-box',
    transition: 'border-color 180ms, background 180ms, box-shadow 180ms',
  };
  const shared = {
    value, placeholder,
    onChange: (e) => setter(e.target.value),
    onFocus: () => setFocused(true),
    onBlur:  () => setFocused(false),
    onMouseEnter: () => setHovered(true),
    onMouseLeave: () => setHovered(false),
  };
  return (
    <div style={{display:'flex', flexDirection:'column', gap: 6}}>
      <span style={{
        fontFamily: "'Inter Tight', sans-serif",
        fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
        color: lit ? '#FFA566' : '#8A7F70',
        transition: 'color 180ms',
      }}>{label}</span>
      {multi ? (
        <textarea rows={3} {...shared} style={{...base, resize: 'vertical', minHeight: 86}}/>
      ) : (
        <input type={type} {...shared} style={base}/>
      )}
    </div>
  );
};

const ContactModal = ({ open, onClose }) => {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [note, setNote] = React.useState('');
  const [state, setState] = React.useState('idle'); // idle | sending | sent | error
  const [closeHover, setCloseHover] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  React.useEffect(() => {
    if (open) return;
    const t = setTimeout(() => {
      setName(''); setEmail(''); setCompany(''); setNote(''); setState('idle');
    }, 400);
    return () => clearTimeout(t);
  }, [open]);

  const submit = async () => {
    if (!name.trim() || !email.trim() || !note.trim()) return;
    setState('sending');
    try {
      const res = await fetch(ORX_FORMSUBMIT, {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
        body: JSON.stringify({
          _subject: `ORXNGE inquiry — ${name}${company ? ' · ' + company : ''}`,
          _template: 'table',
          _captcha: 'false',
          Name: name,
          Email: email,
          Company: company || '—',
          Note: note,
        }),
      });
      if (!res.ok) throw new Error('bad status');
      setState('sent');
    } catch {
      setState('error');
    }
  };

  if (!open) return null;

  // All four fields are required. No asterisks or "required" copy —
  // the Submit button simply stays disabled until everything is filled.
  const disabled = state === 'sending'
    || !name.trim() || !email.trim() || !company.trim() || !note.trim();

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(10, 7, 5, 0.72)',
        backdropFilter: 'blur(18px)',
        WebkitBackdropFilter: 'blur(18px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        animation: 'orx-modal-fade 220ms cubic-bezier(0.22,1,0.36,1) both',
      }}
    >
      <style>{`
        @keyframes orx-modal-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes orx-modal-rise {
          from { opacity: 0; transform: translateY(10px) scale(0.98); }
          to   { opacity: 1; transform: translateY(0)    scale(1); }
        }

        /* Placeholder text in the modal should read as a hint, not as
           already-typed content. Dim the color so it's clearly ghost
           text — especially the longer note prompt. */
        .orx-modal-card input::placeholder,
        .orx-modal-card textarea::placeholder {
          color: rgba(245, 238, 228, 0.32);
          opacity: 1; /* override Firefox's default .54 fade */
        }

        /* Modal-specific: instead of a full dual-arc ring tracing the
           whole border, there is ONE bright highlight (the top "line"
           you already see in the resting design). On open, that single
           highlight rotates clockwise once around the modal's perimeter
           and lands back at the top — where it holds as the permanent
           resting state. No fade-in, no fade-out: the line is visible
           the entire time, it just travels the perimeter once before
           settling. The conic gradient uses a symmetric single peak at
           the start (0°) which wraps to 360°, so bright stays at top at
           both ends of the rotation. The gradient stops mirror the old
           horizontal top line's orange-to-transparent fade. */
        .orx-modal-card { isolation: isolate; }
        .orx-modal-card::after {
          content: '';
          position: absolute;
          inset: 0;
          border-radius: inherit;
          padding: 1.5px;
          pointer-events: none;
          z-index: -1;
          background: conic-gradient(
            from var(--orx-card-load-angle),
            rgba(255,106, 10, 0.85)    0deg,
            rgba(255,140, 60, 0.55)   14deg,
            rgba(255,165,102, 0.18)   30deg,
            rgba(255,106, 10, 0)      52deg,
            rgba(255,106, 10, 0)     308deg,
            rgba(255,165,102, 0.18)  330deg,
            rgba(255,140, 60, 0.55)  346deg,
            rgba(255,106, 10, 0.85)  360deg
          );
          -webkit-mask:
            linear-gradient(#000 0 0) content-box,
            linear-gradient(#000 0 0);
          -webkit-mask-composite: xor;
                  mask:
            linear-gradient(#000 0 0) content-box,
            linear-gradient(#000 0 0);
                  mask-composite: exclude;
          animation: orx-modal-line 1500ms cubic-bezier(0.22,1,0.36,1) forwards;
        }
        @keyframes orx-modal-line {
          from { --orx-card-load-angle: 0deg; }
          to   { --orx-card-load-angle: 360deg; }
        }
      `}</style>
      <div
        // Remount the card when the submission transitions to "sent" so
        // both the rise-in AND the conic ring spin replay for the
        // Received confirmation — otherwise the ring's one-shot animation
        // from the initial open would never run again, and the success
        // state would appear without the signature edge sweep.
        key={state === 'sent' ? 'received' : 'form'}
        className="orx-modal-card"
        onClick={(e) => e.stopPropagation()}
        style={{
          maxWidth: 520, width: '100%',
          background: 'linear-gradient(180deg, rgba(18,13,8,0.96), rgba(10,7,5,0.96))',
          border: '1px solid rgba(245,238,228,0.12)',
          borderRadius: 18,
          padding: '36px 32px 28px',
          boxShadow:
            '0 40px 120px rgba(0,0,0,0.6),' +
            '0 0 0 1px rgba(255,165,102,0.10) inset,' +
            '0 -18px 48px rgba(255,106,10,0.06) inset',
          position: 'relative',
          overflow: 'hidden',
          animation: 'orx-modal-rise 280ms cubic-bezier(0.22,1,0.36,1) both',
        }}
      >
        {/* Orange top line is now the resting state of the conic ring
            above, so the static div has been removed — the ring itself
            settles at the top after its one-pass rotation. */}

        <button
          onClick={onClose}
          aria-label="Close"
          onMouseEnter={() => setCloseHover(true)}
          onMouseLeave={() => setCloseHover(false)}
          style={{
            position: 'absolute', top: 16, right: 16,
            background: 'transparent',
            color: closeHover ? '#FFA566' : '#8A7F70',
            border: 'none', padding: 0, margin: 0,
            width: 24, height: 24,
            cursor: 'pointer',
            fontSize: 22, lineHeight: 1,
            fontFamily: "'Inter Tight', sans-serif", fontWeight: 300,
            display: 'grid', placeItems: 'center',
            transition: 'color 180ms, transform 180ms',
            transform: closeHover ? 'scale(1.1)' : 'scale(1)',
          }}
        >×</button>

        {state === 'sent' ? (
          <div style={{textAlign: 'center', padding: '16px 0 8px'}}>
            <div style={{
              fontFamily: "'Instrument Serif', serif", fontStyle: 'italic',
              fontSize: 34, color: '#FFFAF5', marginBottom: 10,
            }}>Received.</div>
            <div style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: 14, color: '#BFB3A2', marginBottom: 24,
            }}>Your note's in. We'll be in touch.</div>
            <button
              onClick={onClose}
              style={{
                background: 'linear-gradient(180deg, #FFFFFF 0%, #F5EEE4 100%)',
                color: '#0A0705', border: 'none',
                padding: '10px 22px', borderRadius: 10,
                fontFamily: "'Inter Tight', sans-serif",
                fontSize: 13, fontWeight: 500, cursor: 'pointer',
                boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.85), 0 1px 0 rgba(255,255,255,0.35) inset, 0 8px 20px rgba(0,0,0,0.4)',
              }}
            >Close</button>
          </div>
        ) : (
          <>
            <div style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase',
              color: '#FFA566', marginBottom: 10,
            }}>Inquiry</div>
            <h3 style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: 28, fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.02em',
              color: '#FFFAF5', margin: '0 0 6px',
            }}>
              Leave us a <span style={{fontFamily: "'Instrument Serif', serif", fontStyle: 'italic'}}>note</span>.
            </h3>
            <p style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: 14, lineHeight: 1.5, color: '#8A7F70',
              margin: '0 0 22px',
            }}>
              A line or two is enough. The right things rise to the top.
            </p>

            <div style={{display:'flex', flexDirection:'column', gap: 14}}>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12}}>
                <Field label="Name"  value={name}  setter={setName}/>
                <Field label="Email" value={email} setter={setEmail} type="email"/>
              </div>
              <Field label="Company" value={company} setter={setCompany}/>
              <Field label="Note" value={note} setter={setNote} multi
                     placeholder="What you want off your plate, or the venture you want a partner in."/>

              {state === 'error' && (
                <div style={{
                  fontFamily: "'Inter Tight', sans-serif",
                  fontSize: 12, color: '#FFA566',
                  background: 'rgba(255,106,10,0.08)',
                  border: '1px solid rgba(255,106,10,0.25)',
                  borderRadius: 8, padding: '8px 12px',
                }}>Something got in the way. Give it another try.</div>
              )}

              <div style={{display: 'flex', justifyContent: 'center', marginTop: 18}}>
                <button
                  onClick={submit}
                  disabled={disabled}
                  className="orx-btn-aura orx-btn-aura--primary"
                  style={{
                    background: 'linear-gradient(180deg, #FFFFFF 0%, #F5EEE4 100%)',
                    color: '#0A0705', border: 'none',
                    padding: '12px 34px', borderRadius: 10,
                    fontFamily: "'Inter Tight', sans-serif",
                    fontSize: 14, fontWeight: 500, letterSpacing: '-0.005em',
                    cursor: disabled ? 'not-allowed' : 'pointer',
                    opacity: disabled ? 0.55 : 1,
                    minWidth: 144,
                    boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.85), 0 1px 0 rgba(255,255,255,0.35) inset, 0 8px 20px rgba(0,0,0,0.4)',
                    transition: 'opacity 180ms',
                  }}
                >{state === 'sending' ? 'Sending…' : 'Submit'}</button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

window.ContactModal = ContactModal;
window.ContactField = Field;
