// cta-footer-modal.jsx — CtaBand, SiteFooter, LeadModal
window.DZ = window.DZ || {};

/* ╔══════════════════════════════════════════════════════════════════════╗
   ║  "BOOK A BUILD" LEAD DELIVERY — paste ONE of the following, then save:  ║
   ║   • LEAD_WEB3FORMS_KEY = your access key from https://web3forms.com     ║
   ║   • LEAD_ENDPOINT      = your n8n webhook / Formspree / Getform URL      ║
   ║  Leave BOTH "" to preview in demo mode (shows success, sends nothing).  ║
   ╚══════════════════════════════════════════════════════════════════════╝ */
const LEAD_WEB3FORMS_KEY = "";
const LEAD_ENDPOINT = "https://oswald.app.n8n.cloud/webhook/58ae576e-024b-473d-8bca-3f9c6ec3a6d4";

async function deliverLead(payload) {
  if (LEAD_WEB3FORMS_KEY) {
    const res = await fetch('https://api.web3forms.com/submit', {
      method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
      body: JSON.stringify({ access_key: LEAD_WEB3FORMS_KEY, ...payload }),
    });
    const d = await res.json().catch(() => ({}));
    if (!res.ok || d.success === false) throw new Error(d.message || 'send failed');
    return;
  }
  if (LEAD_ENDPOINT) {
    const res = await fetch(LEAD_ENDPOINT, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return;
  }
  await new Promise((r) => setTimeout(r, 500)); // demo mode — nothing configured yet
}

function CtaBand({ onCta }) {
  const { Button } = window.DelzAILabsDesignSystem_bfa572 || {};
  return (
    <section style={{ padding: 'clamp(20px, 5vw, 56px)' }}>
      <div style={{ position: 'relative', overflow: 'hidden', maxWidth: 'var(--container-xl)', margin: '0 auto', background: 'var(--navy-ink)', borderRadius: 'var(--radius-xl)', padding: 'clamp(40px, 7vw, 88px) clamp(28px, 6vw, 80px)' }}>
        <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'radial-gradient(80% 120% at 85% 0%, rgba(242,106,31,0.35), transparent 55%), radial-gradient(70% 110% at 0% 100%, rgba(27,63,196,0.45), transparent 60%)' }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap' }}>
          <div style={{ maxWidth: 560 }}>
            <h2 style={{ color: '#fff', fontSize: 'clamp(28px, 4vw, 46px)', margin: '0 0 16px' }}>Ship your first agent this week</h2>
            <p style={{ color: 'rgba(255,255,255,0.72)', fontSize: 18, margin: 0, lineHeight: 1.6 }}>Tell us one workflow that's eating your team's time. We'll build the agent, wire it to your channels and tools, and watch the first runs with you.</p>
          </div>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            {Button && <Button variant="accent" size="lg" onClick={onCta} iconRight={<i data-lucide="arrow-right" />}>Book a build</Button>}
          </div>
        </div>
      </div>
    </section>
  );
}
window.DZ.CtaBand = CtaBand;

function SiteFooter({ onCta }) {
  const linkFor = (i) => ({ Contact: 'contact-us.html', Agents: '#agents', Channels: '#channels' }[i] || '#');
  const cols = [
    ['Product', ['Agents', 'Channels', 'Integrations']],
    ['Company', ['About', 'Careers', 'Blog', 'Contact']],
    ['Resources', ['Docs', 'Guides', 'Changelog', 'Status']],
  ];
  return (
    <footer style={{ padding: 'clamp(48px, 6vw, 80px) clamp(20px, 5vw, 56px) 40px', background: 'var(--surface-card)', borderTop: '1px solid var(--border-subtle)' }}>
      <div style={{ maxWidth: 'var(--container-xl)', margin: '0 auto', display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 1fr)', gap: 40 }} className="footer-grid">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
            <img src="assets/logo-mark.png" alt="" style={{ height: 42 }} />
            <span className="notranslate" translate="no" style={{ fontFamily: 'var(--font-display)', fontSize: 21, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>Delz AI Labs</span>
          </div>
          <p style={{ fontSize: 14.5, color: 'var(--text-muted)', maxWidth: 290, margin: '0 0 18px', lineHeight: 1.6 }}>Agentic AI and automations for companies and individuals. We build the agents — you get your time back.</p>
          <div style={{ display: 'flex', gap: 10 }}>
            {[
              { label: 'GitHub', path: 'M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222 0 1.606-.014 2.898-.014 3.293 0 .322.216.694.825.576C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12' },
              { label: 'X', path: 'M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z' },
              { label: 'LinkedIn', path: 'M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.225 0z' },
            ].map((s) => (
              <a key={s.label} href="#" aria-label={s.label} style={{ width: 38, height: 38, borderRadius: 'var(--radius-md)', border: '1px solid var(--border-subtle)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)', transition: 'color var(--dur-fast) var(--ease-standard), border-color var(--dur-fast) var(--ease-standard)' }}
                 onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text-strong)'; e.currentTarget.style.borderColor = 'var(--border-default)'; }}
                 onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-muted)'; e.currentTarget.style.borderColor = 'var(--border-subtle)'; }}>
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true"><path d={s.path} /></svg>
              </a>
            ))}
          </div>
        </div>
        {cols.map(([h, items]) => (
          <div key={h}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', marginBottom: 16 }}>{h}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              {items.map((i) => <a key={i} href={linkFor(i)} style={{ fontSize: 14, color: 'var(--text-muted)', textDecoration: 'none' }}>{i}</a>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ maxWidth: 'var(--container-xl)', margin: '44px auto 0', paddingTop: 24, borderTop: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, fontSize: 13, color: 'var(--text-subtle)' }}>
        <span>© 2026 Delz AI Labs. All rights reserved.</span>
        <span style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}><a href="privacy-policy.html" style={{ color: 'var(--text-subtle)', textDecoration: 'none' }}>Privacy</a><a href="terms-of-service.html" style={{ color: 'var(--text-subtle)', textDecoration: 'none' }}>Terms</a><a href="data-deletion.html" style={{ color: 'var(--text-subtle)', textDecoration: 'none' }}>Data deletion</a></span>
      </div>
    </footer>
  );
}
window.DZ.SiteFooter = SiteFooter;

function LeadModal({ open, onClose }) {
  const { Button, Input } = window.DelzAILabsDesignSystem_bfa572 || {};
  const channels = window.SITE.channels;
  const [form, setForm] = React.useState({ name: '', email: '', company: '', workflow: '' });
  const [picked, setPicked] = React.useState(['whatsapp']);
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState(false);

  React.useEffect(() => {
    if (open) { window.lucide && window.lucide.createIcons(); document.body.style.overflow = 'hidden'; }
    else { document.body.style.overflow = ''; }
    return () => { document.body.style.overflow = ''; };
  }, [open, sent]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const toggleChannel = (k) => setPicked((p) => p.includes(k) ? p.filter((x) => x !== k) : [...p, k]);

  const validate = () => {
    const er = {};
    if (!form.name.trim()) er.name = 'Tell us your name';
    if (!form.email.trim()) er.email = 'We need an email to reply';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) er.email = 'That email looks off';
    if (!form.workflow.trim()) er.workflow = 'Describe the workflow to automate';
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setSendError(false);
    setSending(true);
    try {
      const chosen = channels.filter((c) => picked.includes(c.key)).map((c) => c.name).join(', ');
      await deliverLead({
        subject: 'Book a build - ' + form.name,
        name: form.name, email: form.email, company: form.company,
        channels: chosen, workflow: form.workflow,
        from_name: form.name, replyto: form.email, page: 'Book a build',
      });
      setSent(true);
    } catch (err) {
      setSendError(true);
    } finally {
      setSending(false);
    }
  };

  const reset = () => { setSent(false); setSending(false); setSendError(false); setForm({ name: '', email: '', company: '', workflow: '' }); setPicked(['whatsapp']); setErrors({}); onClose(); };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(7,12,36,0.55)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: 'clamp(16px, 5vh, 56px) 16px', overflowY: 'auto', animation: 'fadeIn var(--dur-base) var(--ease-standard)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(100%, 560px)', background: 'var(--surface-card)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-xl)', overflow: 'hidden', animation: 'rise var(--dur-base) var(--ease-emphasis)' }}>
        {/* header */}
        <div style={{ position: 'relative', padding: '26px 28px 22px', background: 'var(--navy-ink)', overflow: 'hidden' }}>
          <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'radial-gradient(90% 140% at 100% 0%, rgba(242,106,31,0.40), transparent 55%), radial-gradient(80% 120% at 0% 120%, rgba(27,63,196,0.45), transparent 60%)' }} />
          <button onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 16, right: 16, width: 34, height: 34, borderRadius: 'var(--radius-md)', border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(255,255,255,0.08)', color: '#fff', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <i data-lucide="x" style={{ width: 18, height: 18 }} />
          </button>
          <div style={{ position: 'relative' }}>
            <div className="eyebrow" style={{ color: 'var(--orange-300)', marginBottom: 10 }}>{sent ? 'REQUEST RECEIVED' : 'BOOK A BUILD'}</div>
            <h3 style={{ color: '#fff', fontSize: 26, margin: 0 }}>{sent ? "You're on the list" : 'Book a build'}</h3>
          </div>
        </div>

        {sent ? (
          <div style={{ padding: '36px 28px 32px', textAlign: 'center' }}>
            <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--success-50)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--success-500)', marginBottom: 18 }}>
              <i data-lucide="check" style={{ width: 30, height: 30 }} />
            </span>
            <h4 style={{ fontSize: 22, margin: '0 0 10px' }}>Thanks, {form.name.split(' ')[0] || 'there'}.</h4>
            <p style={{ fontSize: 15.5, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 380, margin: '0 auto 24px' }}>
              We'll review your workflow and get back within one business day to scope your first agent. Keep an eye on <strong style={{ color: 'var(--text-strong)' }}>{form.email}</strong>.
            </p>
            {Button && <Button variant="primary" onClick={reset}>Done</Button>}
          </div>
        ) : (
          <form onSubmit={submit} style={{ padding: '26px 28px 30px', display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="modal-row">
              <Field label="Your name" error={errors.name}>
                <input value={form.name} onChange={set('name')} placeholder="Sara Mensah" style={inputStyle(errors.name)} />
              </Field>
              <Field label="Work email" error={errors.email}>
                <input value={form.email} onChange={set('email')} placeholder="sara@company.com" style={inputStyle(errors.email)} />
              </Field>
            </div>
            <Field label="Company (optional)">
              <input value={form.company} onChange={set('company')} placeholder="Acme Inc." style={inputStyle(false)} />
            </Field>
            <div>
              <div style={labelStyle}>Which channels?</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {channels.map((c) => {
                  const on = picked.includes(c.key);
                  return (
                    <button type="button" key={c.key} onClick={() => toggleChannel(c.key)}
                      style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 13px', borderRadius: 'var(--radius-pill)', cursor: 'pointer', fontSize: 13.5, fontWeight: 500, fontFamily: 'var(--font-body)',
                        color: on ? 'var(--blue-700)' : 'var(--text-body)', background: on ? 'var(--blue-50)' : 'var(--surface-card)', border: `1px solid ${on ? 'var(--blue-300)' : 'var(--border-default)'}`, transition: 'all var(--dur-fast) var(--ease-standard)' }}>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.color }} />{c.name}
                    </button>
                  );
                })}
              </div>
            </div>
            <Field label="What workflow should the agent run?" error={errors.workflow}>
              <textarea value={form.workflow} onChange={set('workflow')} rows={3} placeholder="e.g. Reply to WhatsApp support questions, check order status in our system, and escalate refunds to a human." style={{ ...inputStyle(errors.workflow), height: 'auto', padding: '12px 14px', resize: 'vertical', lineHeight: 1.5 }} />
            </Field>
            <div style={{ display: 'flex', gap: 12 }}>
              {Button && <Button variant="secondary" size="lg" type="button" onClick={reset} disabled={sending} style={{ flex: '1 1 0' }}>Cancel</Button>}
              {Button && <Button variant="accent" size="lg" type="submit" iconRight={!sending && <i data-lucide="arrow-right" />} style={{ flex: '1.6 1 0' }} disabled={sending}>{sending ? 'Sending…' : 'Request my build'}</Button>}
            </div>
            {sendError && <p style={{ fontSize: 13, color: 'var(--error-500)', textAlign: 'center', margin: '-4px 0 0' }}>Couldn't send just now — please try again, or email hello@delzailabs.com.</p>}
            <p style={{ fontSize: 12.5, color: 'var(--text-subtle)', textAlign: 'center', margin: 0 }}>No spam. We reply within one business day.</p>
          </form>
        )}
      </div>
    </div>
  );
}

function Field({ label, error, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={labelStyle}>{label}</div>
      {children}
      {error && <div style={{ fontSize: 12.5, color: 'var(--error-500)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 5 }}><i data-lucide="alert-circle" style={{ width: 13, height: 13 }} />{error}</div>}
    </label>
  );
}
const labelStyle = { fontSize: 13.5, fontWeight: 500, color: 'var(--text-strong)', marginBottom: 7 };
function inputStyle(error) {
  return { width: '100%', height: 'var(--control-h-md)', padding: '0 14px', fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-body)', background: 'var(--surface-card)', border: `1px solid ${error ? 'var(--error-500)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-md)', outline: 'none', boxSizing: 'border-box' };
}
window.DZ.LeadModal = LeadModal;
