/* global React, ReactDOM, Reveal, Button */
/* ─────────────────────────────────────────────────────────────────────────────
   CASE STUDY GATE — lead-capture modal + PDF download trigger
   Exposes: window.CaseStudyDownloadButton
   Usage:   <CaseStudyDownloadButton variant="hero|mid|end" />
   ──────────────────────────────────────────────────────────────────────────── */

const { useState: useStateG, useEffect: useEffectG, useRef: useRefG } = React;

const PDF_PATH = '/assets/protein-pals-case-study.pdf';
const LEAD_API = '/api/capture-lead';

/* ── Copy variants for the three placement positions ── */
const COPY = {
  hero: {
    heading: 'Take this with you.',
    body:    'The full breakdown: strategy, numbers, what worked and what did not. Save it as a PDF and share it with your team.',
    btn:     'Download the case study PDF',
  },
  mid: {
    heading: 'Save this for later.',
    body:    'All the numbers, charts and system diagrams above in one clean PDF. Yours in 30 seconds.',
    btn:     'Download the PDF',
  },
  end: {
    heading: 'Before you leave.',
    body:    'Take the case study with you. Share it with your business partner, your marketing team, or just read it properly offline.',
    btn:     'Download the PDF',
  },
};

/* ── Labelled form field ── */
function GateField({ label, type, name, value, onChange, required, placeholder, hint }) {
  const [focused, setFocused] = useStateG(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{
        fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
        letterSpacing: '0.09em', textTransform: 'uppercase',
        color: 'var(--fg-muted)',
      }}>
        {label}
        {required && <span style={{ color: 'var(--accent)', marginLeft: 3 }}>*</span>}
      </label>
      <input
        type={type || 'text'}
        name={name}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        required={required}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          fontFamily: 'var(--font-sans)', fontSize: 15,
          padding: '11px 13px',
          background: 'var(--bg)',
          border: `1px solid ${focused ? 'var(--accent)' : 'var(--border-strong)'}`,
          borderRadius: 3,
          color: 'var(--fg)',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          transition: 'border-color 140ms',
        }}
      />
      {hint && (
        <span style={{
          fontFamily: 'var(--font-sans)', fontSize: 12,
          color: 'var(--fg-subtle)', lineHeight: 1.45,
        }}>
          {hint}
        </span>
      )}
    </div>
  );
}

/* ── Gate modal (portal-rendered) ── */
function GateModal({ onClose }) {
  const [form, setForm] = useStateG({
    name: '', businessName: '', website: '', email: '', phone: '',
  });
  const [status,   setStatus]   = useStateG('idle');   // idle | loading | success | error
  const [errorMsg, setErrorMsg] = useStateG('');
  const overlayRef = useRefG(null);

  /* Escape key + body scroll lock */
  useEffectG(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, []);

  function handleChange(e) {
    const { name, value } = e.target;
    setForm(f => ({ ...f, [name]: value }));
  }

  function triggerDownload() {
    const a = document.createElement('a');
    a.href     = PDF_PATH;
    a.download = 'Daee-Media-Protein-Pals-Case-Study.pdf';
    document.body.appendChild(a);
    a.click();
    setTimeout(() => document.body.removeChild(a), 200);
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus('loading');
    setErrorMsg('');
    try {
      const res = await fetch(LEAD_API, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setStatus('error');
        setErrorMsg(data.error || 'Something went wrong. Please try again.');
        return;
      }
      setStatus('success');
      triggerDownload();
    } catch {
      setStatus('error');
      setErrorMsg('Connection error. Check your internet and try again.');
    }
  }

  const isLoading = status === 'loading';

  return ReactDOM.createPortal(
    <div
      ref={overlayRef}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9000,
        background: 'rgba(0,0,0,0.68)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '20px',
      }}
    >
      <div style={{
        background: 'var(--bg)', borderRadius: 5,
        width: '100%', maxWidth: 500,
        padding: 'clamp(32px, 5vw, 48px) clamp(24px, 5vw, 44px)',
        position: 'relative',
        maxHeight: '90vh', overflowY: 'auto',
        boxShadow: '0 32px 96px rgba(0,0,0,0.44)',
      }}>

        {/* Close × */}
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 16, right: 16,
            background: 'transparent', border: 0, cursor: 'pointer',
            fontSize: 20, color: 'var(--fg-muted)', lineHeight: 1,
            padding: '4px 8px', borderRadius: 3,
          }}
        >
          &#x2715;
        </button>

        {/* ── SUCCESS STATE ── */}
        {status === 'success' ? (
          <div style={{ textAlign: 'center', padding: '16px 0 8px' }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              background: 'var(--accent-subtle)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 24px',
            }}>
              <span style={{ fontSize: 24, color: 'var(--accent)' }}>&#x2713;</span>
            </div>

            <h2 style={{
              fontFamily: 'var(--font-display)', fontSize: 26,
              letterSpacing: '-0.015em', fontWeight: 400,
              color: 'var(--fg)', margin: '0 0 12px',
            }}>
              Your download is starting.
            </h2>

            <p style={{
              fontFamily: 'var(--font-sans)', fontSize: 15,
              color: 'var(--fg-muted)', lineHeight: 1.6,
              margin: '0 auto 28px', maxWidth: 380,
            }}>
              Check your downloads folder. If the file does not appear, we will send it to your email shortly.
            </p>

            <button
              onClick={onClose}
              style={{
                fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
                background: 'var(--fg)', color: 'var(--bg)',
                border: 0, borderRadius: 3,
                padding: '12px 28px', cursor: 'pointer',
              }}
            >
              Close
            </button>
          </div>
        ) : (
        /* ── FORM STATE ── */
          <>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontSize: 26,
              letterSpacing: '-0.015em', fontWeight: 400,
              color: 'var(--fg)', margin: '0 0 8px',
            }}>
              Download the case study
            </h2>

            <p style={{
              fontFamily: 'var(--font-sans)', fontSize: 14,
              color: 'var(--fg-muted)', lineHeight: 1.5,
              margin: '0 0 28px',
            }}>
              Free. No pitch, no spam. Your details go straight to Saad at Daee Media.
            </p>

            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <GateField
                label="Your name"     name="name"
                required              value={form.name}
                onChange={handleChange}
                placeholder="Your full name"
              />
              <GateField
                label="Business name" name="businessName"
                required              value={form.businessName}
                onChange={handleChange}
                placeholder="Your company or brand"
              />
              <GateField
                label="Website"       name="website"
                required              value={form.website}
                onChange={handleChange}
                placeholder="yoursite.com"
              />
              <GateField
                label="Email address" name="email"
                type="email"          required
                value={form.email}    onChange={handleChange}
                placeholder="you@yourcompany.com"
              />
              <GateField
                label="Phone number"  name="phone"
                value={form.phone}    onChange={handleChange}
                placeholder="+1 (416) 000-0000"
                hint="Optional. Leave your number and we will reach out personally. Most clients say a 10-minute call is what convinced them."
              />

              {errorMsg && (
                <p style={{
                  fontFamily: 'var(--font-sans)', fontSize: 13,
                  color: '#bf3030', lineHeight: 1.4, margin: 0,
                }}>
                  {errorMsg}
                </p>
              )}

              <button
                type="submit"
                disabled={isLoading}
                style={{
                  fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 700,
                  letterSpacing: '0.01em',
                  background: isLoading ? 'var(--border-strong)' : 'var(--fg)',
                  color: isLoading ? 'var(--fg-muted)' : 'var(--bg)',
                  border: 0, borderRadius: 3,
                  padding: '15px 24px',
                  cursor: isLoading ? 'default' : 'pointer',
                  transition: 'background 160ms',
                  marginTop: 4,
                }}
              >
                {isLoading ? 'Sending…' : 'Download the PDF'}
              </button>

              <p style={{
                fontFamily: 'var(--font-sans)', fontSize: 11,
                color: 'var(--fg-faint)', lineHeight: 1.5,
                textAlign: 'center', margin: 0,
              }}>
                No marketing lists. No follow-up unless you want one.
              </p>
            </form>
          </>
        )}
      </div>
    </div>,
    document.body
  );
}

/* ── Inline download CTA block ── */
function CaseStudyDownloadButton({ variant }) {
  const [open, setOpen] = useStateG(false);
  const c = COPY[variant] || COPY.hero;

  /* Styling per variant */
  const boxStyle = {
    hero: {
      background: 'var(--accent-subtle)',
      border:     '1px solid var(--border)',
      margin:     '48px 0 0',
    },
    mid: {
      background: 'transparent',
      border:     '1px solid var(--border-strong)',
      margin:     '56px 0',
    },
    end: {
      background: 'var(--accent-subtle)',
      border:     '1px solid var(--border)',
      margin:     '56px 0 0',
    },
  }[variant] || {};

  return (
    <>
      <Reveal>
        <div style={{
          padding: 'clamp(28px, 4vw, 40px) clamp(24px, 4vw, 40px)',
          borderRadius: 4,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 32,
          flexWrap: 'wrap',
          ...boxStyle,
        }}>
          <div style={{ flex: '1 1 280px' }}>
            <div style={{
              fontFamily: 'var(--font-display)', fontSize: 'clamp(20px, 2.5vw, 26px)',
              letterSpacing: '-0.01em', lineHeight: 1.2, fontWeight: 400,
              color: 'var(--fg)', marginBottom: 10,
            }}>
              {c.heading}
            </div>
            <p style={{
              fontFamily: 'var(--font-sans)', fontSize: 15,
              lineHeight: 1.55, color: 'var(--fg-muted)', margin: 0,
            }}>
              {c.body}
            </p>
          </div>

          <button
            onClick={() => setOpen(true)}
            style={{
              flexShrink: 0,
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
              letterSpacing: '0.02em',
              background: 'var(--fg)', color: 'var(--bg)',
              border: 0, borderRadius: 3,
              padding: '14px 24px',
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 8,
              whiteSpace: 'nowrap',
            }}
          >
            {c.btn} <span aria-hidden style={{ opacity: 0.7 }}>&#x2193;</span>
          </button>
        </div>
      </Reveal>

      {open && <GateModal onClose={() => setOpen(false)} />}
    </>
  );
}

window.CaseStudyDownloadButton = CaseStudyDownloadButton;
