// Homepage waitlist — POST /api/public/homepage-waitlist

const { useState: useS_wl, useEffect: useE_wl, useRef: useR_wl } = React;

/** Fallback until /count loads (matches server default base). */
const WL_SOCIAL_COUNT_FALLBACK = 58;

function isValidEmailWl(s) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
}

function isValidLinkedInProfileUrlWl(s) {
  const trimmed = s.trim();
  if (!trimmed) return false;
  try {
    const url = new URL(trimmed.startsWith('http') ? trimmed : `https://${trimmed}`);
    if (!url.hostname.replace(/^www\./, '').endsWith('linkedin.com')) return false;
    return /^\/in\/[^/?#]+/i.test(url.pathname);
  } catch (_) {
    return false;
  }
}

function isLinkedInFieldValidWl(s) {
  const trimmed = s.trim();
  if (!trimmed) return true;
  return isValidLinkedInProfileUrlWl(trimmed);
}

function SubmitArrowIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M5 12h13M13 6l6 6-6 6" />
    </svg>
  );
}

function LockIcon() {
  return (
    <svg className="home-wl-lock" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="4" y="10" width="16" height="11" rx="2" />
      <path d="M8 10V7a4 4 0 0 1 8 0v3" />
    </svg>
  );
}

function HomeWaitlistScreen({ onDirectory }) {
  const [email, setEmail] = useS_wl('');
  const [linkedinUrl, setLinkedinUrl] = useS_wl('');
  const [proofCount, setProofCount] = useS_wl(WL_SOCIAL_COUNT_FALLBACK);
  const [phase, setPhase] = useS_wl('form');
  const [position, setPosition] = useS_wl(0);
  const [displayPosition, setDisplayPosition] = useS_wl(0);
  const [loading, setLoading] = useS_wl(false);
  const emailValid = isValidEmailWl(email.trim());
  const linkedinFieldValid = isLinkedInFieldValidWl(linkedinUrl);
  const animRef = useR_wl(null);

  useE_wl(function() {
    fetch('/api/public/homepage-waitlist/count')
      .then(function(r) { return r.ok ? r.json() : null; })
      .then(function(d) {
        if (d && typeof d.count === 'number' && d.count > 0) setProofCount(d.count);
      })
      .catch(function() {});
  }, []);

  useE_wl(function() {
    if (phase !== 'success') return;
    const duration = 900;
    const start = performance.now();
    function step(now) {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setDisplayPosition(Math.round(eased * position));
      if (t < 1) animRef.current = requestAnimationFrame(step);
    }
    setDisplayPosition(0);
    const id = requestAnimationFrame(step);
    animRef.current = id;
    return function() {
      if (animRef.current) cancelAnimationFrame(animRef.current);
    };
  }, [phase, position]);

  const submit = async function(ev) {
    ev.preventDefault();
    if (!emailValid || !linkedinFieldValid || loading) return;
    setLoading(true);
    const started = performance.now();
    let nextPosition = proofCount + 1;
    try {
      const resp = await fetch('/api/public/homepage-waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(),
          linkedinUrl: linkedinUrl.trim() || null,
          source: 'homepage',
        }),
      });
      if (resp.ok) {
        const data = await resp.json().catch(function() { return {}; });
        if (typeof data.position === 'number') nextPosition = data.position;
      }
    } catch (_) { /* still show success — signup may have saved */ }

    try {
      const _ph = window.posthog && typeof window.posthog.capture === 'function' ? window.posthog : null;
      if (_ph) {
        const trimmed = email.trim();
        const hashBuf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(trimmed));
        const hashHex = [...new Uint8Array(hashBuf)].map(b => b.toString(16).padStart(2, '0')).join('');
        _ph.capture('waitlist_joined', {
          email: trimmed,
          linkedinUrl: linkedinUrl.trim() || null,
          source: 'homepage',
        });
        _ph.identify(hashHex, { email: trimmed });
      }
    } catch (_) { /* non-blocking */ }

    const minDelay = 650;
    const wait = Math.max(0, minDelay - (performance.now() - started));
    setTimeout(function() {
      setPosition(nextPosition);
      setPhase('success');
      setLoading(false);
    }, wait);
  };

  if (phase === 'success') {
    return (
      <div className="home-waitlist-page" data-screen-label="00 Homepage (waitlist)">
        <main className="home-waitlist-card home-waitlist-card--success">
          <div className="home-wl-success">
            <div className="home-wl-success-mark" aria-hidden="true">
              <svg viewBox="0 0 88 88" width="88" height="88" fill="none">
                <circle cx="44" cy="44" r="40" stroke="currentColor" strokeWidth="1.5" />
                <path d="M26 44l12 12 24-28" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className="home-wl-success-label">▸ Confirmed</div>
            <h2 className="home-wl-success-title">You&apos;re on the list.</h2>
            <div className="home-wl-success-position">
              <div className="home-wl-success-position-label">Your position</div>
              <div className="home-wl-success-position-num">#<span>{displayPosition}</span></div>
            </div>
            <p className="home-wl-success-sub">
              We&apos;ll email <strong>{email.trim()}</strong> when creator onboarding opens.
            </p>
            <div className="home-wl-success-followup">
              <span className="home-wl-success-followup-icon" aria-hidden="true">→</span>
              <span>
                We&apos;ll reach out when creator onboarding opens — typically within 1–2 weeks of launch.
              </span>
            </div>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="home-waitlist-page" data-screen-label="00 Homepage (waitlist)">
      <main className="home-waitlist-card">
        <span className="home-wl-glowdot" aria-hidden="true" />

        <div className="home-wl-left">
          <header className="home-wl-header">
            <span className="home-wl-eyebrow">
              <span className="home-wl-eyebrow-tri" aria-hidden="true" />
              JOIN THE WAITLIST
            </span>
            <h1 className="home-wl-title">
              Turn your expertise into a <span className="home-wl-accent">runnable lead magnet</span> prospects can actually use.
            </h1>
            <p className="home-wl-lede">
              For <b>freelancers, consultants, and agency owners</b> who&apos;ve built a repeatable method
              <span className="home-wl-lede-extra"> — a diagnostic, audit, framework, or evaluation</span>.
              {' '}WorkApp turns it into a runnable lead magnet that gives prospects a real, personalized result.
            </p>
          </header>

          <div className="home-wl-proof" aria-label={`${proofCount} founding creators already on the list`}>
            <div className="home-wl-avatars" aria-hidden="true">
              <span className="home-wl-av home-wl-av-a">RS</span>
              <span className="home-wl-av home-wl-av-b">MK</span>
              <span className="home-wl-av home-wl-av-c">JL</span>
              <span className="home-wl-av home-wl-av-d">+</span>
            </div>
            <p className="home-wl-proof-text"><b>{proofCount}</b> founding creators already on the list</p>
          </div>

          <ul className="home-wl-props">
            <li>
              <span className="home-wl-prop-n">01</span>
              <span className="home-wl-prop-t">
                <b>A personalized result, not a static PDF.</b>{' '}
                <span className="home-wl-prop-full">Prospects experience how you think through their own situation.</span>
                <span className="home-wl-prop-short">Prospects experience how you think through their situation.</span>
              </span>
            </li>
            <li>
              <span className="home-wl-prop-n">02</span>
              <span className="home-wl-prop-t">
                <b>Live in under 15 minutes.</b>{' '}
                <span className="home-wl-prop-full">No code, no prompt engineering — start from a post or from scratch.</span>
                <span className="home-wl-prop-short">No code, no prompt engineering.</span>
              </span>
            </li>
            <li>
              <span className="home-wl-prop-n">03</span>
              <span className="home-wl-prop-t">
                <b>10× more engagement</b>{' '}
                <span className="home-wl-prop-full">— and warmer, better-qualified leads in your pipeline.</span>
                <span className="home-wl-prop-short">— and warmer, qualified leads.</span>
              </span>
            </li>
          </ul>
        </div>

        <section className="home-wl-right" aria-labelledby="home-wl-form-heading">
          <div className="home-wl-fhead" id="home-wl-form-heading">RESERVE YOUR SPOT</div>
          <form className="home-wl-form" onSubmit={submit} noValidate>
            <label className="home-wl-sr-only" htmlFor="home-wl-email">Your email</label>
            <input
              id="home-wl-email"
              className="home-wl-field"
              type="email"
              placeholder="Your email"
              autoComplete="email"
              required
              value={email}
              onChange={function(ev) { setEmail(ev.target.value); }}
            />
            <label className="home-wl-sr-only" htmlFor="home-wl-linkedin">Your LinkedIn profile URL</label>
            <input
              id="home-wl-linkedin"
              className="home-wl-field"
              type="url"
              placeholder="Your LinkedIn profile URL (optional)"
              maxLength={2048}
              autoComplete="url"
              inputMode="url"
              aria-describedby="home-wl-linkedin-hint"
              value={linkedinUrl}
              onChange={function(ev) { setLinkedinUrl(ev.target.value); }}
            />
            <p className="home-wl-hint" id="home-wl-linkedin-hint">E.G. LINKEDIN.COM/IN/YOUR-NAME</p>
            <button
              type="submit"
              className={'home-wl-submit' + (loading ? ' is-loading' : '')}
              disabled={loading}
              aria-busy={loading}
            >
              <span className="home-wl-submit-label">Reserve my spot</span>
              <SubmitArrowIcon />
            </button>
          </form>
          <div className="home-wl-incentive">
            <LockIcon />
            <span>Founding creators lock in <b>early pricing — for life.</b></span>
          </div>
        </section>
      </main>
    </div>
  );
}

Object.assign(window, { HomeWaitlistScreen });
