// About + Newsletter + Footer

function AboutSection() {
  const cfg = window.SO_CONFIG || {};
  const brand = cfg.brand || {};
  return (
    <section className="so-section so-about" id="about">
      <div className="so-about-grid">
        <div className="so-about-left">
          <span className="so-mono-label">SECTION · ABOUT {((brand.company || 'signalOPS').toUpperCase())}</span>
          <h2 className="so-section-title" style={{ marginTop: 12 }}>
            We came from <span className="muted">operations.</span><br/>
            We left to engineer it.
          </h2>
          <p className="so-about-body">
            Every founding engineer here ran ops before they wrote ops. We've held the bag during Black Friday postmortems, manually reconciled invoices, and lived inside Zendesk macros.
            We know what you're trying to automate because we've done it manually.
          </p>
          <p className="so-about-body">
            {brand.company || 'signalOPS'} {brand.lab || 'DIGITAL Lab'} exists to turn that institutional knowledge into systems your team can actually use: versioned, observable, and simple enough to maintain.
          </p>
          <p className="so-about-body">
            Project {brand.project || 'Amera256'} is the project line under the lab.
          </p>
          <div className="so-about-stats">
            <div><div className="num">9</div><div className="lab">years avg. operator experience</div></div>
            <div><div className="num">41</div><div className="lab">custom flows designed</div></div>
            <div><div className="num">100%</div><div className="lab">client-held artifacts</div></div>
          </div>
        </div>
        <div className="so-about-right">
          <div className="so-about-tile">
            <div className="head"><span className="so-mono-label">manifesto</span></div>
            <div className="body">
              <p>Operations is a compiler. Inputs in, outcomes out, errors caught at the boundary.</p>
              <p>Manual operations is the unoptimized build. It works, but it costs everything to maintain.</p>
              <p className="signal">Our job is to build the better one.</p>
            </div>
            <div className="foot so-mono-label">- signed, the operators</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ CONTACT SECTION ============
// Shows email, phone, hours + a contact form that posts to
// SO_CONFIG.webhooks.contactForm. Easy edit point: see config.js.
function ContactSection() {
  const cfg = window.SO_CONFIG || {};
  const c = cfg.contact || {};
  const privacy = cfg.privacy || {};
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', company: '', message: '' });
  const [stage, setStage] = React.useState('idle');
  const [consent, setConsent] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');

  async function submit(e) {
    e.preventDefault();
    if (stage === 'loading') return;
    if (!consent) {
      setErrorMsg('Please accept the privacy notice before sending.');
      setStage('error');
      return;
    }
    setErrorMsg('');
    setStage('loading');
    const res = await window.SoSubmit('contactForm', {
      ...form,
      consent: true,
      consentText: privacy.consentText,
      storageVendor: privacy.storageVendor,
      retentionDays: privacy.retentionDays,
    });
    if (!res.ok) {
      setErrorMsg('Webhook did not accept the request. Check `config.js` -> `webhooks.contactForm`.');
    }
    setStage(res.ok ? 'done' : 'error');
  }

  if (cfg.features && cfg.features.showContactSection === false) return null;

  return (
    <section className="so-section so-contact" id="contact">
      <div className="so-section-head">
        <span className="so-mono-label">SECTION · CONTACT</span>
        <h2 className="so-section-title">
          Wire a call. <span className="muted">Or send the brief.</span>
        </h2>
        <p className="so-section-lede">
          One route. Send the brief and we will pick it up directly.
        </p>
      </div>

      <div className="so-contact-grid">
        <form className="so-contact-form" onSubmit={submit}>
          <div className="so-contact-form-h">
            <span className="so-mono-label">async · form</span>
            <h3>Tell us what is broken.</h3>
            <div className="so-contact-sub" style={{ marginTop: 2 }}>
              <a href={'mailto:' + c.email}>{c.email}</a> · {c.hours}
            </div>
          </div>
          {stage !== 'done' && (
            <>
              <div className="so-form-row">
                <input className="so-input" placeholder="name" value={form.name} onChange={e => setForm({...form, name: e.target.value})}/>
                <input className="so-input" placeholder="company" value={form.company} onChange={e => setForm({...form, company: e.target.value})}/>
              </div>
              <div className="so-form-row">
                <input className="so-input" type="email" placeholder="email *" required value={form.email} onChange={e => setForm({...form, email: e.target.value})}/>
                <input className="so-input" placeholder="phone (optional)" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})}/>
              </div>
              <textarea
                className="so-input so-textarea"
                placeholder="The manual process eating your team's time..."
                rows={4}
                value={form.message}
                onChange={e => setForm({...form, message: e.target.value})}
              />
              <div className="so-privacy-box">
                <label className="so-consent-row">
                  <input
                    type="checkbox"
                    checked={consent}
                    onChange={e => setConsent(e.target.checked)}
                  />
                  <span>{privacy.consentText || 'I agree to be contacted about this request.'}</span>
                </label>
                <div className="so-privacy-note">
                  {privacy.storageSummary || 'Your details will be sent to n8n and stored only for the requested follow-up.'}
                </div>
              </div>
              <div className="so-form-foot">
                <span className="so-mono-label">encrypted · no sales sequence</span>
                <button className="so-cta so-cta--primary" type="submit" disabled={stage === 'loading'}>
                  {stage === 'loading' ? 'Sending...' : 'Send brief →'}
                </button>
              </div>
              {stage === 'error' && errorMsg && (
                <div className="so-form-error">{errorMsg}</div>
              )}
            </>
          )}
          {stage === 'done' && (
            <div className="so-form-success">
              <span className="so-pulse-dot"></span>
              <div>
                <div><strong>Received.</strong> An engineer will reach out within 24h.</div>
                <div className="so-mono-label" style={{ marginTop: 4 }}>routed to {c.email} · ref #{Math.random().toString(36).slice(2, 8).toUpperCase()}</div>
              </div>
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

function NewsletterSection() {
  const cfg = window.SO_CONFIG || {};
  const privacy = cfg.privacy || {};
  const [stage, setStage] = React.useState('idle');
  const [email, setEmail] = React.useState('');
  const [digestStage, setDigestStage] = React.useState('idle');
  const [digestEmail, setDigestEmail] = React.useState('');
  const [consent, setConsent] = React.useState(false);
  const [digestConsent, setDigestConsent] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [digestErrorMsg, setDigestErrorMsg] = React.useState('');

  async function submit(e) {
    e.preventDefault();
    if (!email) return;
    if (!consent) {
      setErrorMsg('Please accept the privacy notice before requesting analysis.');
      setStage('error');
      return;
    }
    setErrorMsg('');
    setStage('loading');
    const res = await window.SoSubmit('analysisRequest', {
      email,
      source: 'newsletter-block',
      consent: true,
      consentText: privacy.consentText,
      storageVendor: privacy.storageVendor,
      retentionDays: privacy.retentionDays,
    });
    if (!res.ok) {
      setErrorMsg('Webhook did not accept the request. Check `config.js` -> `webhooks.analysisRequest`.');
    }
    setStage(res.ok ? 'done' : 'error');
  }

  async function submitDigest(e) {
    e.preventDefault();
    if (!digestEmail) return;
    if (!digestConsent) {
      setDigestErrorMsg('Please accept the privacy notice before joining the digest.');
      setDigestStage('error');
      return;
    }
    setDigestErrorMsg('');
    setDigestStage('loading');
    const res = await window.SoSubmit('newsletter', {
      email: digestEmail,
      source: 'digest-form',
      consent: true,
      consentText: privacy.consentText,
      storageVendor: privacy.storageVendor,
      retentionDays: privacy.retentionDays,
    });
    if (!res.ok) {
      setDigestErrorMsg('Newsletter webhook did not accept the request. Check `config.js` -> `webhooks.newsletter`.');
    }
    setDigestStage(res.ok ? 'done' : 'error');
  }

  return (
    <section className="so-section so-news" id="analysis">
      <div className="so-news-card">
        <div className="so-news-bg" aria-hidden="true">
          <svg viewBox="0 0 600 200" width="100%" height="100%" preserveAspectRatio="none">
            <defs>
              <pattern id="news-grid" width="20" height="20" patternUnits="userSpaceOnUse">
                <path d="M 20 0 L 0 0 0 20" fill="none" stroke="var(--grid-line-strong)" strokeWidth="1"/>
              </pattern>
            </defs>
            <rect width="600" height="200" fill="url(#news-grid)"/>
            <g fill="none" stroke="var(--signal-line)" strokeWidth="1.2" strokeDasharray="2 6">
              <path d="M 0 100 Q 150 60 300 100 T 600 100"/>
              <path d="M 0 130 Q 150 90 300 130 T 600 130" opacity="0.5"/>
            </g>
          </svg>
        </div>
        <div className="so-news-content">
          <span className="so-mono-label">CTA · OPERATIONAL ANALYSIS</span>
          <h2 className="so-news-title">Get your operational analysis.</h2>
          <p className="so-news-desc">
            Tell us where your operation is breaking. We send back a written assessment - manual touchpoints, automation candidates, expected hours saved - within five business days. No deck.
          </p>
          <form className="so-news-form" onSubmit={submit}>
            {stage !== 'done' && (
              <>
                <input
                  className="so-input"
                  type="email"
                  placeholder="ops@yourcompany.com"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                />
                <div className="so-privacy-box so-privacy-box--inline">
                  <label className="so-consent-row">
                    <input
                      type="checkbox"
                      checked={consent}
                      onChange={e => setConsent(e.target.checked)}
                    />
                    <span>{privacy.consentText || 'I agree to be contacted about this request.'}</span>
                  </label>
                  <div className="so-privacy-note">
                    {privacy.storageSummary || 'Your details will be sent to n8n and retained only for follow-up.'}
                  </div>
                </div>
                <button className="so-cta so-cta--primary so-cta--lg" type="submit">
                  {stage === 'loading' ? 'Submitting...' : 'Get analysis →'}
                </button>
              </>
            )}
            {stage === 'done' && (
              <div className="so-news-success">
                <span className="so-pulse-dot"></span>
                <span>Received. We'll reach out within 24 hours from <code>{email}</code>.</span>
              </div>
            )}
          </form>
          {stage === 'error' && errorMsg && (
            <div className="so-form-error" style={{ marginTop: 12 }}>
              {errorMsg}
            </div>
          )}
          <div className="so-news-alt">
            <span>or</span>
            <form
              onSubmit={submitDigest}
              style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'stretch', width: '100%' }}
            >
              <input
                className="so-input"
                type="email"
                placeholder="ops digest email"
                value={digestEmail}
                onChange={e => setDigestEmail(e.target.value)}
              />
              <div className="so-privacy-box so-privacy-box--inline so-privacy-box--tight">
                <label className="so-consent-row">
                  <input
                    type="checkbox"
                    checked={digestConsent}
                    onChange={e => setDigestConsent(e.target.checked)}
                  />
                  <span>{privacy.consentText || 'I agree to be contacted about this request.'}</span>
                </label>
                <div className="so-privacy-note">
                  {privacy.storageSummary || 'Your details will be sent to n8n and retained only for follow-up.'}
                </div>
              </div>
              <button className="so-cta so-cta--ghost" type="submit" disabled={digestStage === 'loading'}>
                {digestStage === 'loading' ? 'Joining...' : 'Join digest →'}
              </button>
            </form>
          </div>
          {digestStage === 'done' && (
            <div className="so-news-success" style={{ marginTop: 12 }}>
              <span className="so-pulse-dot"></span>
              <span>Digest request received. We'll use <code>{digestEmail}</code> for the next send.</span>
            </div>
          )}
          {digestStage === 'error' && digestErrorMsg && (
            <div className="so-form-error" style={{ marginTop: 12 }}>
              {digestErrorMsg}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function MarketingFooter() {
  const cfg = window.SO_CONFIG || {};
  const c = cfg.contact || {};
  const s = cfg.social || {};
  const brand = cfg.brand || {};
  return (
    <footer className="so-footer">
      <div className="so-footer-grid">
        <div className="so-footer-brand">
          <Glyph size={32} />
          <span className="so-wm">{brand.project || 'Project AmeRA256'}</span>
          <p className="so-footer-tag">{brand.tagline || 'Automation and digital transformation engineering.'}</p>
          <div className="so-footer-meta so-mono-label">
            <span><span className="so-pulse-dot"></span>OPERATIONAL</span>
            <span>·</span>
            <span>v 2026.04</span>
          </div>
        </div>
        <div className="so-footer-col">
          <span className="so-mono-label">offer</span>
          <a>Automation Nano Flows</a>
          <a>Automation Systems</a>
          <a>AI &amp; Agentic Workflows</a>
        </div>
        <div className="so-footer-col">
          <span className="so-mono-label">analysis</span>
          <a>Operational Audit</a>
          <a>Process Mapping</a>
          <a>Efficiency Detection</a>
        </div>
        <div className="so-footer-col">
          <span className="so-mono-label">about</span>
          <a>Mission</a>
          <a>Background</a>
          <a>Behind the Scenes</a>
        </div>
        <div className="so-footer-col">
          <span className="so-mono-label">contact</span>
          <a href={'mailto:' + c.email}>{c.email}</a>
          {c.phone ? <a href={'tel:' + c.phoneHref}>{c.phone}</a> : <a href="#contact">Add phone in config.js</a>}
          <a href="#contact">Wire a call</a>
          {s.github   && <a href={s.github}   target="_blank" rel="noopener">GitHub ↗</a>}
          {s.linkedin && <a href={s.linkedin} target="_blank" rel="noopener">LinkedIn ↗</a>}
          {s.instagram && <a href={'https://instagram.com/' + s.instagram.replace(/^@/, '')} target="_blank" rel="noopener">Instagram ↗</a>}
          {s.twitter && <a href={s.twitter} target="_blank" rel="noopener">X / Twitter ↗</a>}
        </div>
      </div>
      <div className="so-footer-base">
        <span>© 2026 {brand.company || 'signalOPS'}</span>
        <span className="so-mono-label">compile · connect · observe</span>
      </div>
    </footer>
  );
}

Object.assign(window, { AboutSection, ContactSection, NewsletterSection, MarketingFooter });
