// ============================================================
// DEMIURGE — CONTACT / STRATEGY CALL SECTION
// Fully operational: real validation, loading/success/failure states,
// package context from the URL, honeypot spam protection, and a real
// server submission to /api/contact. NO mailto fallback.
// ============================================================

const PACKAGE_NAMES = {
  starter: 'Starter', growth: 'Growth', autonomous: 'Autonomous', enterprise: 'Enterprise'
};

// Read context passed via /full?package=<slug>&intent=<key>&source=<page>#contact
const readContext = () => {
  if (typeof window === 'undefined') return {};
  const q = new URLSearchParams(window.location.search);
  const pkg = (q.get('package') || q.get('plan') || '').toLowerCase();
  return {
    package: PACKAGE_NAMES[pkg] ? pkg : '',
    intent: q.get('intent') || (PACKAGE_NAMES[pkg] ? 'strategy-call' : ''),
    source: q.get('source') || q.get('ref') || '',
    service: q.get('service') || ''
  };
};

const ContactSection = () => {
  const ctx = readContext();
  const [form, setForm] = React.useState({
    name: '', email: '', company: '', role: '', phone: '',
    industry: '', package: ctx.package || '',
    intent: ctx.intent || 'strategy-call',
    preferredContact: 'email', preferredDate: '',
    message: '', consent: false,
    website: '' // honeypot — must stay empty
  });
  const [errors, setErrors] = React.useState({});
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | success | error
  const [serverError, setServerError] = React.useState(null);
  const firstErrorRef = React.useRef(null);

  const source = ctx.source || (typeof document !== 'undefined' ? (document.title || 'full') : 'full');

  const update = (k) => (e) => {
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(er => { const n = { ...er }; delete n[k]; return n; });
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Please tell us your name.';
    if (!form.email.trim()) e.email = 'A work email is required.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'That doesn’t look like a valid email.';
    if (!form.message.trim()) e.message = 'A short summary helps us prepare.';
    if (!form.consent) e.consent = 'Please acknowledge the privacy notice to continue.';
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    if (phase === 'submitting') return; // prevent duplicate submissions
    setServerError(null);
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) {
      // Move focus to the first invalid control for accessibility.
      const first = ['name', 'email', 'message', 'consent'].find(k => e[k]);
      const el = document.getElementById(`c-${first}`);
      if (el) el.focus();
      return;
    }
    setPhase('submitting');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, source })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        setServerError(data.error || `Submission failed (HTTP ${res.status}). Your details are preserved — please try again.`);
        setPhase('error');
        return;
      }
      setPhase('success');
    } catch (err) {
      setServerError('Network error — your details are preserved. Please try again.');
      setPhase('error');
    }
  };

  const selectedPackageLabel = form.package ? PACKAGE_NAMES[form.package] : '';

  return (
    <section className="lp-section" id="contact" style={{scrollMarginTop: 96}}>
      <div className="lp">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 48, flexWrap: 'wrap'}}>
          <div style={{maxWidth: 720}}>
            <div className="lp-eyebrow">/ 12 · Strategy call</div>
            <h2 className="lp-h2" style={{marginTop: 18}}>
              Talk to a deployment lead.<br/>
              <em className="lp-brass">Get a custom plan</em> in 30 minutes.
            </h2>
          </div>
          <p className="lp-lede" style={{maxWidth: 380, fontSize: 15.5}}>
            Tell us where you are, where you want to be, and which lane hurts most. A senior operator
            will reach out within one business day with a calibrated deployment plan.
          </p>
        </div>

        {selectedPackageLabel && phase !== 'success' && (
          <div className="lp-ctx-banner" role="status">
            <span className="dot"></span>
            <span>Enquiring about the <strong>{selectedPackageLabel}</strong> package. Change it in the form below if needed.</span>
          </div>
        )}

        <div style={{
          display: 'grid', gridTemplateColumns: 'minmax(0, 1.05fr) minmax(0, 0.95fr)',
          gap: 32, marginTop: 32, alignItems: 'stretch'
        }} className="lp-contact-grid">
          {/* Form panel */}
          <div className="lp-ind-panel" style={{padding: '36px 32px'}}>
            <div className="corner tl"></div><div className="corner tr"></div>
            <div className="corner bl"></div><div className="corner br"></div>
            <div className="lp-ind-tag" style={{position: 'absolute', top: 16, left: 16}}>SECURE INTAKE · DMG/FORM-014</div>

            {phase === 'success' ? (
              <div style={{padding: '64px 16px', textAlign: 'center'}} role="status" aria-live="polite">
                <div style={{
                  width: 64, height: 64, margin: '0 auto 20px', borderRadius: '50%',
                  background: 'radial-gradient(circle at 35% 35%, #fff, #5dffb0 50%, #1a5c3a 100%)',
                  boxShadow: '0 0 32px rgba(93,255,176,0.4)'
                }}/>
                <h3 style={{fontFamily: 'Instrument Serif', fontSize: 28, color: '#f5f1e6', margin: '0 0 12px', fontStyle: 'italic', fontWeight: 400}}>
                  Enquiry received.
                </h3>
                <p style={{color: '#8388a8', fontSize: 14, maxWidth: 380, margin: '0 auto', lineHeight: 1.6}}>
                  Thank you{form.name ? `, ${form.name.split(/\s+/)[0]}` : ''}. Your enquiry is in — a confirmation is on its way to{' '}
                  <strong style={{color: '#f5f1e6'}}>{form.email}</strong>, and a deployment lead will reply within one business day.
                </p>
              </div>
            ) : (
              <form onSubmit={onSubmit} noValidate style={{display: 'flex', flexDirection: 'column', gap: 14, marginTop: 32}}>
                {/* Honeypot — visually hidden, off keyboard/AT */}
                <div aria-hidden="true" style={{position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden'}}>
                  <label>Company URL<input tabIndex={-1} autoComplete="off" value={form.website} onChange={update('website')}/></label>
                </div>

                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row">
                  <CField id="c-name" label="Name" required error={errors.name}>
                    <input id="c-name" required type="text" value={form.name} onChange={update('name')} autoComplete="name"
                      aria-invalid={!!errors.name} aria-describedby={errors.name ? 'e-name' : undefined}/>
                  </CField>
                  <CField id="c-email" label="Work email" required error={errors.email}>
                    <input id="c-email" required type="email" value={form.email} onChange={update('email')} autoComplete="email"
                      aria-invalid={!!errors.email} aria-describedby={errors.email ? 'e-email' : undefined}/>
                  </CField>
                </div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row">
                  <CField id="c-company" label="Company / organisation">
                    <input id="c-company" type="text" value={form.company} onChange={update('company')} autoComplete="organization"/>
                  </CField>
                  <CField id="c-role" label="Role">
                    <input id="c-role" type="text" value={form.role} onChange={update('role')} placeholder="Owner / CEO / Head of Ops"/>
                  </CField>
                </div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row">
                  <CField id="c-phone" label="Phone (optional)">
                    <input id="c-phone" type="tel" value={form.phone} onChange={update('phone')} autoComplete="tel"/>
                  </CField>
                  <CField id="c-package" label="Package / service">
                    <select id="c-package" value={form.package} onChange={update('package')}>
                      <option value="">General enquiry</option>
                      <option value="starter">Starter package</option>
                      <option value="growth">Growth package</option>
                      <option value="autonomous">Autonomous package</option>
                      <option value="enterprise">Enterprise package</option>
                    </select>
                  </CField>
                </div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row">
                  <CField id="c-intent" label="What do you want to talk about?">
                    <select id="c-intent" value={form.intent} onChange={update('intent')}>
                      <option value="strategy-call">Strategy call · scope a deployment</option>
                      <option value="enterprise">Enterprise · custom deployment</option>
                      <option value="pricing">Pricing question</option>
                      <option value="demo">Live console demo</option>
                      <option value="other">Other</option>
                    </select>
                  </CField>
                  <CField id="c-industry" label="Industry">
                    <select id="c-industry" value={form.industry} onChange={update('industry')}>
                      <option value="">Select</option>
                      <option>HVAC &amp; Trades</option><option>Dental &amp; Medical</option>
                      <option>Law firm</option><option>Real estate</option>
                      <option>E-commerce</option><option>Agency</option><option>Other</option>
                    </select>
                  </CField>
                </div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row">
                  <CField id="c-preferredContact" label="Preferred contact method">
                    <select id="c-preferredContact" value={form.preferredContact} onChange={update('preferredContact')}>
                      <option value="email">Email</option>
                      <option value="phone">Phone</option>
                      <option value="either">Either</option>
                    </select>
                  </CField>
                  <CField id="c-preferredDate" label="Preferred date / availability">
                    <input id="c-preferredDate" type="text" value={form.preferredDate} onChange={update('preferredDate')} placeholder="e.g. weekday mornings, next week"/>
                  </CField>
                </div>
                <CField id="c-message" label="Project summary — what’s the biggest bottleneck?" required error={errors.message}>
                  <textarea id="c-message" rows={4} value={form.message} onChange={update('message')}
                    aria-invalid={!!errors.message} aria-describedby={errors.message ? 'e-message' : undefined}
                    placeholder="Where you're losing leads, calls, hours, or margin — the more specific, the better the call."/>
                </CField>

                <label htmlFor="c-consent" style={{display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 12.5, color: '#8388a8', lineHeight: 1.5}}>
                  <input id="c-consent" type="checkbox" checked={form.consent} onChange={update('consent')}
                    aria-invalid={!!errors.consent} aria-describedby={errors.consent ? 'e-consent' : undefined}
                    style={{marginTop: 3, accentColor: '#8b6bff'}}/>
                  <span>
                    I agree that Demiurge Systems may use these details to respond to my enquiry, as described in the{' '}
                    <a href="/legal/privacy" style={{color: '#4be8ff'}}>Privacy Policy</a>.
                  </span>
                </label>
                {errors.consent && <div id="e-consent" className="cf-err">{errors.consent}</div>}

                {phase === 'error' && serverError && (
                  <div className="cf-servererr" role="alert">{serverError}</div>
                )}

                <button type="submit" className="lp-btn primary lg" disabled={phase === 'submitting'}
                  style={{justifyContent: 'center', marginTop: 8, opacity: phase === 'submitting' ? 0.6 : 1}}>
                  {phase === 'submitting' ? 'Sending…' : 'Send enquiry'}
                  {phase !== 'submitting' && (
                    <svg className="arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
                  )}
                </button>
                <p style={{fontFamily: 'Geist Mono', fontSize: 10, color: '#4a4f6b', letterSpacing: '0.06em', textAlign: 'center', marginTop: 4}}>
                  No spam · One human reply · We never sell your data
                </p>
              </form>
            )}
          </div>

          {/* Sidebar — what to expect */}
          <div className="lp-ind-panel" style={{padding: '36px 32px'}}>
            <div className="corner tl"></div><div className="corner tr"></div>
            <div className="corner bl"></div><div className="corner br"></div>
            <div className="lp-ind-tag" style={{position: 'absolute', top: 16, left: 16}}>WHAT HAPPENS NEXT</div>
            <div style={{marginTop: 40, display: 'flex', flexDirection: 'column', gap: 22}}>
              {[
                { ix: '01', t: 'Within one business day', d: 'A senior deployment lead reviews your enquiry and replies with two or three calibrated paths forward — no boilerplate.' },
                { ix: '02', t: 'A 30-minute scoping call', d: 'You bring the constraints. We bring the operator stack tuned to your industry. Out of the call: a deployment plan with line items and ROI projections.' },
                { ix: '03', t: 'Seven-day deploy or walk', d: 'If we mutually decide to proceed, your operators are live within seven business days. Cancel inside thirty for any reason.' }
              ].map(step => (
                <div key={step.ix} style={{display: 'flex', gap: 16}}>
                  <div style={{fontFamily: 'Geist Mono', fontSize: 18, color: '#c9a674', letterSpacing: '0.16em', minWidth: 36, paddingTop: 2}}>{step.ix}</div>
                  <div>
                    <div style={{fontFamily: 'Instrument Serif', fontSize: 20, color: '#f5f1e6', fontStyle: 'italic', marginBottom: 6}}>{step.t}</div>
                    <div style={{color: '#8388a8', fontSize: 14, lineHeight: 1.55}}>{step.d}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{marginTop: 32, paddingTop: 20, borderTop: '1px solid rgba(255,255,255,0.08)', display: 'flex', flexDirection: 'column', gap: 10}}>
              <div style={{fontFamily: 'Geist Mono', fontSize: 10, color: '#4a4f6b', letterSpacing: '0.16em', textTransform: 'uppercase'}}>Prefer email?</div>
              <a href="mailto:ops@demiurge.systems" style={{color: '#4be8ff', fontFamily: 'Geist Mono', fontSize: 13, textDecoration: 'none', letterSpacing: '0.04em'}}>ops@demiurge.systems</a>
              <div style={{fontFamily: 'Geist Mono', fontSize: 10.5, color: '#4a4f6b', lineHeight: 1.6}}>
                For privacy or data requests see the <a href="/legal/privacy" style={{color: '#8388a8'}}>Privacy Policy</a>.
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const CField = ({ id, label, required, error, children }) => (
  <label htmlFor={id} style={{display: 'flex', flexDirection: 'column', gap: 6}}>
    <span style={{fontFamily: 'Geist Mono', fontSize: 10, color: '#8388a8', letterSpacing: '0.14em', textTransform: 'uppercase'}}>
      {label}{required ? <span style={{color: '#e8c98a', marginLeft: 4}} aria-hidden="true">*</span> : null}
    </span>
    {React.cloneElement(children, {
      style: {
        background: 'rgba(3,4,12,0.6)',
        border: `1px solid ${error ? 'rgba(255,95,95,0.55)' : 'rgba(255,255,255,0.1)'}`,
        borderRadius: 3, color: '#f5f1e6', fontFamily: 'Geist, system-ui, sans-serif',
        fontSize: 14, padding: '11px 14px', outline: 'none', width: '100%', boxSizing: 'border-box',
        resize: children.type === 'textarea' ? 'vertical' : undefined
      }
    })}
    {error ? <span id={`e-${id.replace('c-', '')}`} className="cf-err" role="alert">{error}</span> : null}
  </label>
);

// Styles (Babel-in-browser can't use CSS modules)
if (typeof document !== 'undefined' && !document.getElementById('lp-contact-styles')) {
  const s = document.createElement('style');
  s.id = 'lp-contact-styles';
  s.textContent = `
    #contact input:focus, #contact select:focus, #contact textarea:focus {
      border-color: rgba(75, 232, 255, 0.5) !important;
      box-shadow: 0 0 0 3px rgba(75, 232, 255, 0.08) !important;
    }
    #contact input::placeholder, #contact textarea::placeholder { color: #4a4f6b; }
    #contact select option { background: #03040c; color: #f5f1e6; }
    #contact .cf-err { color: #ff8b8b; font-size: 11.5px; font-family: 'Geist Mono', monospace; letter-spacing: 0.02em; }
    #contact .cf-servererr {
      padding: 12px 14px; background: rgba(255,95,95,0.08); border: 1px solid rgba(255,95,95,0.3);
      border-radius: 3px; color: #ff8b8b; font-size: 13px; font-family: 'Geist Mono', monospace;
    }
    .lp-ctx-banner {
      display: flex; align-items: center; gap: 10px; margin-top: 24px;
      padding: 12px 16px; border: 1px solid rgba(139,107,255,0.3); background: rgba(139,107,255,0.06);
      border-radius: 4px; color: #c8a8ff; font-size: 13.5px;
    }
    .lp-ctx-banner .dot { width: 7px; height: 7px; border-radius: 50%; background: #8b6bff; box-shadow: 0 0 8px #8b6bff; }
    .lp-ctx-banner strong { color: #f5f1e6; }
    @media (max-width: 880px) {
      .lp-contact-grid { grid-template-columns: 1fr !important; }
      #contact .cf-row { grid-template-columns: 1fr !important; }
    }
  `;
  document.head.appendChild(s);
}

// Smooth-scroll to the section when arriving at /full#contact. Because the
// page renders via in-browser Babel/React AFTER load, the #contact element
// may not exist yet — so we retry until it appears (up to ~5s).
if (typeof window !== 'undefined') {
  const focusContact = () => {
    if (window.location.hash !== '#contact') return;
    let tries = 0;
    const attempt = () => {
      const el = document.getElementById('contact');
      if (el) {
        const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        el.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'start' });
        return;
      }
      if (tries++ < 50) setTimeout(attempt, 100);
    };
    attempt();
  };
  window.addEventListener('load', focusContact);
  window.addEventListener('hashchange', focusContact);
  focusContact(); // in case load already fired before this script ran
}

window.ContactSection = ContactSection;
