// Hero — the only page. Wordmark, one line of copy, email input, join button.
// Positioned above the waterline (upper third) so waves can occasionally wash up to it.

const ACTIVITY_HINTS = [
  'bowling on Smith St',
  'karting in Port Melbourne',
  'pool at a Fitzroy pub',
  'escape room in the CBD',
  'mini golf on Chapel',
  'trivia night in Carlton',
  'ping pong in Collingwood',
  'darts in Brunswick',
  'arcade in Richmond',
];

const SUPABASE_URL      = window.TIDES_CONFIG?.SUPABASE_URL;
const SUPABASE_ANON_KEY = window.TIDES_CONFIG?.SUPABASE_ANON_KEY;

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

const Hero = ({ tweaks }) => {
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [hintIdx, setHintIdx] = React.useState(0);
  const [hintKey, setHintKey] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => {
      setHintIdx(i => (i + 1) % ACTIVITY_HINTS.length);
      setHintKey(k => k + 1);
    }, 3200);
    return () => clearInterval(id);
  }, []);

  const triggerOcean = (target) => {
    const w = window.__tides?.state;
    if (!w) return;
    w.washes.push({ t0: w.t, strength: 1.15 });
    const formRect = target.getBoundingClientRect();
    const cx = formRect.left + formRect.width / 2;
    const cy = formRect.top + formRect.height / 2;
    for (let i = 0; i < 14; i++) {
      const a = (Math.PI * 2 * i) / 14;
      const r = 60 + Math.random() * 140;
      w.ripples.push({
        x: cx + Math.cos(a) * r,
        y: cy + Math.sin(a) * r * 0.3 + 80,
        t0: w.t,
        strength: 0.8 + Math.random() * 0.3,
      });
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    setError('');

    if (!EMAIL_RE.test(email.trim())) {
      setError('Please enter a valid email address.');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch(`${SUPABASE_URL}/rest/v1/waitlist`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'apikey': SUPABASE_ANON_KEY,
          'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
          'Prefer': 'return=minimal',
        },
        body: JSON.stringify({ email: email.trim().toLowerCase() }),
      });

      if (res.status === 409 || (await res.text().catch(() => '')).includes('duplicate')) {
        setError("You're already on the list!");
        setLoading(false);
        return;
      }
      if (!res.ok) {
        setError('Something went wrong — try again.');
        setLoading(false);
        return;
      }

      setSubmitted(true);
      triggerOcean(e.target);
      setTimeout(() => window.location.reload(), 2800);
    } catch {
      setError('Something went wrong — try again.');
      setLoading(false);
    }
  };

  const isMobile = window.innerWidth < 600 || window.matchMedia('(pointer: coarse)').matches;

  return (
    <div style={{
      position: 'relative',
      zIndex: 3,
      height: '100%',
      width: '100%',
      display: 'grid',
      gridTemplateRows: 'auto 1fr auto',
      padding: 'clamp(20px, 3vw, 40px)',
      pointerEvents: 'none',
      overflowY: isMobile ? 'auto' : 'visible',
      overflowX: 'hidden',
    }}>
      {/* Top bar — removed */}
      <header style={{ pointerEvents: 'none' }} />

      {/* Center: wordmark + copy */}
      <main style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', textAlign: 'center',
        transform: isMobile ? 'none' : 'translateY(-4vh)',
        padding: isMobile ? '24px 0 40px' : 0,
      }}>
        <Wordmark tweaks={tweaks} />

        <p style={{
          marginTop: 'clamp(16px, 2.2vh, 28px)',
          fontSize: isMobile ? 15 : 'clamp(15px, 1.4vw, 21px)',
          color: 'var(--ink)',
          maxWidth: isMobile ? '88vw' : 620,
          lineHeight: 1.55,
          fontWeight: 400,
          letterSpacing: '0.01em',
          textWrap: 'pretty',
        }}>
          Discover what's live, grab the deal, get out there
          <span style={{ position: 'relative', display: 'inline-block', minWidth: isMobile ? 'unset' : 200 }}>
            <span
              key={hintKey}
              style={{
                fontStyle: 'italic',
                color: 'var(--deep)',
                animation: 'hintIn 0.6s ease both',
                display: 'inline-block',
                marginLeft: 4,
              }}
            >
              {ACTIVITY_HINTS[hintIdx]}
            </span>
          </span>.
        </p>

        {/* Waitlist + info bubble */}
        <div style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', marginTop: 'clamp(20px, 3vh, 40px)', width: isMobile ? 'min(380px, calc(100vw - 56px))' : 'auto' }}>

        <form onSubmit={submit} style={{
          pointerEvents: 'auto',
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          alignItems: 'stretch',
          gap: isMobile ? 6 : 0,
          background: 'rgba(255,255,255,0.55)',
          backdropFilter: 'blur(14px)',
          WebkitBackdropFilter: 'blur(14px)',
          border: '1px solid rgba(26,58,74,0.12)',
          borderRadius: isMobile ? 18 : 999,
          padding: isMobile ? '10px 10px 10px 10px' : 4,
          boxShadow: '0 10px 30px -12px rgba(26,58,74,0.18), inset 0 1px 0 rgba(255,255,255,0.6)',
          width: isMobile ? '100%' : 'auto',
          minWidth: isMobile ? 'unset' : 'clamp(380px, 30vw, 480px)',
          animation: isMobile && !email ? 'formPulse 2.8s ease-in-out 1.2s 3' : 'none',
        }}>
          {!submitted ? (
            <>
              {isMobile && (
                <p style={{
                  margin: '2px 0 4px 4px',
                  fontSize: 11,
                  fontWeight: 600,
                  letterSpacing: '0.08em',
                  textTransform: 'uppercase',
                  color: 'var(--deep)',
                  opacity: 0.6,
                }}>Your email</p>
              )}
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="Enter your email"
                autoComplete="email"
                style={{
                  flex: 1,
                  border: isMobile ? '1.5px solid rgba(26,58,74,0.15)' : 'none',
                  background: isMobile ? 'rgba(255,255,255,0.75)' : 'transparent',
                  padding: isMobile ? '13px 16px' : '16px 22px',
                  fontSize: isMobile ? 15 : 16,
                  color: 'var(--ink)',
                  fontFamily: 'inherit',
                  outline: 'none',
                  minWidth: 0,
                  borderRadius: isMobile ? 12 : 0,
                  WebkitBoxShadow: '0 0 0 1000px rgba(255,255,255,0.75) inset',
                  WebkitTextFillColor: 'var(--ink)',
                  transition: 'background-color 9999s ease-in-out 0s, border-color 0.2s ease',
                  boxShadow: isMobile ? '0 2px 8px rgba(26,58,74,0.08)' : 'none',
                }}
                onFocus={(e) => { if (isMobile) e.target.style.borderColor = 'var(--deep)' }}
                onBlur={(e) => { if (isMobile) e.target.style.borderColor = 'rgba(26,58,74,0.15)' }}
              />
              <button type="submit" disabled={loading} style={{
                border: 'none',
                background: loading ? 'var(--shallow)' : 'var(--ink)',
                color: 'var(--sky)',
                padding: isMobile ? '14px 26px' : '14px 30px',
                borderRadius: 999,
                fontSize: isMobile ? 14 : 15,
                fontFamily: 'inherit',
                fontWeight: 500,
                letterSpacing: '0.02em',
                transition: 'transform 0.15s ease, background 0.2s ease',
                opacity: loading ? 0.7 : 1,
                ...(isMobile ? { width: '100%' } : {}),
              }}
              onMouseEnter={(e) => { if (!loading) e.currentTarget.style.background = 'var(--deep)'; }}
              onMouseLeave={(e) => { if (!loading) e.currentTarget.style.background = 'var(--ink)'; }}
              >
                {loading ? 'Joining…' : 'Join the waitlist'}
              </button>
            </>
          ) : (
            <div style={{
              flex: 1,
              padding: '14px 24px',
              fontSize: 15,
              color: 'var(--ink)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 12,
              animation: 'successIn 0.7s cubic-bezier(.2,.9,.3,1.2) both',
              position: 'relative',
              overflow: 'hidden',
            }}>
              {/* shimmer wash sweep */}
              <span style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(90deg, transparent 0%, rgba(127,179,201,0.4) 50%, transparent 100%)',
                animation: 'successWash 1.2s ease-out 0.1s',
                pointerEvents: 'none',
              }} />
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none" style={{ flexShrink: 0 }}>
                <circle cx="11" cy="11" r="10" stroke="var(--deep)" strokeWidth="1.3"
                  style={{ animation: 'successCircle 0.5s ease-out both' }}
                  pathLength="1" strokeDasharray="1" strokeDashoffset="1" />
                <path d="M6 11.5 L 9.5 14.5 L 16 7.5" stroke="var(--deep)" strokeWidth="1.8"
                  fill="none" strokeLinecap="round" strokeLinejoin="round"
                  pathLength="1" strokeDasharray="1" strokeDashoffset="1"
                  style={{ animation: 'successCheck 0.4s ease-out 0.35s both' }} />
              </svg>
              <span style={{
                fontFamily: "'Fraunces', serif",
                fontStyle: 'italic',
                fontSize: 16,
              }}>
                You're in. We'll wash up soon.
              </span>
            </div>
          )}
        </form>

        </div>{/* end wrapper */}

        {error && (
          <p style={{
            marginTop: 10, fontSize: 13, color: 'var(--deep)',
            fontStyle: 'italic', animation: 'fadeIn 0.3s ease both',
          }}>
            {error}
          </p>
        )}

        <div style={{
          marginTop: isMobile ? 8 : 16, fontSize: isMobile ? 10 : 12, opacity: 0.55, letterSpacing: '0.02em',
          pointerEvents: 'auto',
          transition: 'opacity 0.4s ease',
          ...(submitted ? { opacity: 0.75 } : {}),
        }}>
          {submitted
            ? "We'll send one note when the tide rolls in — check your inbox."
            : "No spam, we'll just let you know when we're live!"}
        </div>
      </main>

      {/* Bottom: removed — creature lives in its own component */}
      <footer />

      <style>{`
        @keyframes hintIn {
          from { opacity: 0; transform: translateY(6px); filter: blur(4px); }
          to { opacity: 1; transform: translateY(0); filter: blur(0); }
        }
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes successIn {
          0%   { opacity: 0; transform: scale(0.94); }
          60%  { opacity: 1; transform: scale(1.02); }
          100% { opacity: 1; transform: scale(1); }
        }
        @keyframes successWash {
          from { transform: translateX(-100%); }
          to   { transform: translateX(100%); }
        }
        @keyframes successCircle {
          to { stroke-dashoffset: 0; }
        }
        @keyframes successCheck {
          to { stroke-dashoffset: 0; }
        }
        @keyframes formPulse {
          0%   { box-shadow: 0 10px 30px -12px rgba(26,58,74,0.18), inset 0 1px 0 rgba(255,255,255,0.6); }
          50%  { box-shadow: 0 10px 30px -12px rgba(26,58,74,0.18), inset 0 1px 0 rgba(255,255,255,0.6), 0 0 0 3px rgba(30,90,120,0.25); }
          100% { box-shadow: 0 10px 30px -12px rgba(26,58,74,0.18), inset 0 1px 0 rgba(255,255,255,0.6); }
        }
        input::placeholder { color: rgba(26,58,74,0.4); }
        /* Kill browser autofill yellow/white box */
        input:-webkit-autofill,
        input:-webkit-autofill:hover,
        input:-webkit-autofill:focus,
        input:-webkit-autofill:active {
          -webkit-box-shadow: 0 0 0 1000px transparent inset !important;
          box-shadow: 0 0 0 1000px transparent inset !important;
          -webkit-text-fill-color: #1A3A4A !important;
          caret-color: #1A3A4A;
          transition: background-color 9999s ease-in-out 0s;
          background-color: transparent !important;
        }
      `}</style>
    </div>
  );
};

window.Hero = Hero;
