// ============================================================
// LANDING — shared bits (Request Access modal)
// ============================================================
// Imported by landing-c.jsx. The modal POSTs to /landing/request-access
// which writes to the platform DB so an admin can follow up with an
// invite code.

const { useState: useStL } = React;

function RequestAccessModal({ open, onClose }) {
  const [submitted, setSubmitted] = useStL(false);
  const [submitting, setSubmitting] = useStL(false);
  const [error, setError] = useStL(null);
  const [email, setEmail] = useStL('');
  const [company, setCompany] = useStL('');
  const [role, setRole] = useStL('ops');

  if (!open) return null;

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const resp = await fetch('/landing/request-access', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim().toLowerCase(), company: company.trim(), role }),
      });
      if (!resp.ok) {
        const data = await resp.json().catch(() => ({}));
        throw new Error(data.detail || `Request failed (${resp.status})`);
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  // Inline colors instead of var() — the landing page doesn't carry a
  // data-theme attribute, so the portal's themed tokens (--surface,
  // --text-strong, --border, …) resolve to empty here and the modal
  // would render transparent. Hardcoding keeps the modal looking like
  // a real card against the dark page.
  const C = {
    ink:        '#1A1714',
    ink2:       '#2F2A24',
    ink3:       '#58524A',
    ink4:       '#847C71',
    paper:      '#FBFAF7',
    paperSunk:  '#F5F3EE',
    rule:       '#E6E1D6',
    accent:     '#FF7A59',
    successSoft:'#D1FAE5',
    success:    '#047857',
    errSoft:    '#FEE2E2',
    err:        '#B91C1C',
  };

  return (
    <div className="lpc-modal-overlay">
      <div className="lpc-modal-card">
        <button
          onClick={onClose}
          aria-label="Close"
          className="lpc-modal-close"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
        </button>

        {submitted ? (
          <div>
            <div style={{
              width: 44, height: 44, borderRadius: 999,
              background: C.successSoft, color: C.success,
              display: 'grid', placeItems: 'center', marginBottom: 16,
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
            </div>
            <div style={{ fontFamily: "'Newsreader', Georgia, serif", fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', color: C.ink, marginBottom: 8 }}>
              You're on the list.
            </div>
            <p style={{ color: C.ink3, fontSize: 14.5, lineHeight: 1.55, margin: 0 }}>
              We'll be in touch within two business days with an invite code and a short call to learn about your process.
            </p>
            <div style={{ marginTop: 22, fontSize: 13, color: C.ink4 }}>
              Already have a code? <a href="/auth/signup" style={{ color: C.accent, fontWeight: 500 }}>Sign up →</a>
            </div>
          </div>
        ) : (
          <form onSubmit={onSubmit}>
            <div style={{ fontFamily: "'Newsreader', Georgia, serif", fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', color: C.ink, marginBottom: 6 }}>
              Request access
            </div>
            <p style={{ color: C.ink3, fontSize: 14, marginBottom: 22, lineHeight: 1.5 }}>
              Tell us a little about your team. We'll send you an invite code within two business days.
            </p>
            <FormField label="Work email">
              <input
                className="lpc-modal-input"
                type="email"
                placeholder="you@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={submitting}
              />
            </FormField>
            <FormField label="Company">
              <input
                className="lpc-modal-input"
                placeholder="Inicio Press"
                value={company}
                onChange={(e) => setCompany(e.target.value)}
                disabled={submitting}
              />
            </FormField>
            <FormField label="Your role">
              <select
                className="lpc-modal-input"
                value={role}
                onChange={(e) => setRole(e.target.value)}
                disabled={submitting}
              >
                <option value="ops">Operations leader</option>
                <option value="founder">Founder / CEO</option>
                <option value="consultant">Consultant or advisor</option>
                <option value="team-lead">Team lead</option>
                <option value="other">Other</option>
              </select>
            </FormField>
            {error && (
              <div style={{
                marginTop: 12, padding: '8px 12px',
                background: C.errSoft, color: C.err,
                borderRadius: 6, fontSize: 13,
              }}>
                {error}
              </div>
            )}
            <button
              type="submit"
              className="lpc-btn lpc-btn--accent"
              style={{ width: '100%', justifyContent: 'center', marginTop: 16 }}
              disabled={submitting || !email.trim()}
            >
              {submitting ? 'Sending…' : 'Request access'}
            </button>
            <div style={{ marginTop: 14, fontSize: 12.5, color: C.ink4, textAlign: 'center' }}>
              Already have an invite code? <a href="/auth/signup" style={{ color: C.accent, fontWeight: 500 }}>Sign up →</a>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function FormField({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{
        display: 'block',
        fontFamily: "'Geist Mono', ui-monospace, monospace",
        fontSize: 10.5,
        letterSpacing: '0.1em',
        textTransform: 'uppercase',
        color: '#847C71',
        marginBottom: 6,
        fontWeight: 500,
      }}>{label}</label>
      {children}
    </div>
  );
}

// ============================================================
// Video modal — plays the 2-minute Remotion tour on the landing page
// ============================================================
function VideoModal({ open, onClose, src }) {
  const videoRef = React.useRef(null);

  // Close on Escape; pause + reset when the modal closes.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    if (open) {
      v.currentTime = 0;
      v.play().catch(() => { /* autoplay may be blocked; user can hit play */ });
    } else {
      v.pause();
    }
  }, [open]);

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 110,
        display: 'grid',
        placeItems: 'center',
        background: 'color-mix(in oklab, #000 75%, transparent)',
        backdropFilter: 'blur(8px)',
        padding: 24,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 'min(1200px, 100%)',
          aspectRatio: '16 / 9',
          position: 'relative',
          borderRadius: 14,
          overflow: 'hidden',
          boxShadow: '0 40px 120px -40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.06)',
          background: '#07080a',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Close video"
          style={{
            position: 'absolute',
            top: 14,
            right: 14,
            zIndex: 2,
            width: 36,
            height: 36,
            borderRadius: 999,
            background: 'rgba(0,0,0,0.5)',
            color: '#fff',
            border: 0,
            display: 'grid',
            placeItems: 'center',
            cursor: 'pointer',
            backdropFilter: 'blur(8px)',
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
        </button>
        <video
          ref={videoRef}
          src={src}
          controls
          playsInline
          style={{ width: '100%', height: '100%', display: 'block', background: '#07080a' }}
        />
      </div>
    </div>
  );
}

Object.assign(window, { RequestAccessModal, VideoModal });
