// SMASH — Landing page sections
// Built on top of the mobile UI kit components (Wordmark, Button, etc.)
// and the IOSDevice frame. Each section is a stand-alone component.

const { useState, useEffect, useRef } = React;

// ─── Supabase config ──────────────────────────────────────────────────────
const SUPABASE_URL = 'https://tkbhebrievhwgcxishyy.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRrYmhlYnJpZXZod2djeGlzaHl5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA4MzAzMTksImV4cCI6MjA5NjQwNjMxOX0.6XpWNem1uxpgbcg9SOGRMYxBfjsNUzM3bR_X-_vhN4k';

async function saveToWaitlist({ email, ntrp, district }) {
  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,
      ntrp: ntrp || null,
      district: district || null,
    }),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text);
  }
}

// ─── Tabler-style outline icons used on the landing page ──────────────────
const LandingIcon = {
  calendarX: (s = 32) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
  strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M16 3v4M8 3v4M3 10h18" />
      <path d="M10 14l4 4M14 14l-4 4" />
    </svg>,

  arrowsUpDown: (s = 32) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
  strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M7 4v16M3 8l4-4 4 4" />
      <path d="M17 20V4M13 16l4 4 4-4" />
    </svg>,

  clockX: (s = 32) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
  strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 2" />
      <path d="M16 16l4 4M20 16l-4 4" />
    </svg>,

  telegram: (s = 20) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor">
      <path d="M21.4 4.2L2.6 11.5c-1 .4-1 1 .1 1.3l4.7 1.5 1.8 5.6c.2.6.5.7.9.6l2.7-2.4 4.7 3.5c.8.5 1.4.2 1.6-.8l2.9-13.6c.3-1.3-.5-1.8-1.6-1.4zM10 14.3l-.4 4.1-1.5-4.8 9.9-6.4-8 7.1z" />
    </svg>,

  instagram: (s = 20) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
  strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="18" height="18" rx="5" />
      <circle cx="12" cy="12" r="4" />
      <circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" />
    </svg>,

  x: (s = 20) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.5 3h3.2l-7 8 8.3 10h-6.5l-5.1-6.7L4.5 21H1.3l7.5-8.5L1 3h6.6l4.6 6.1L17.5 3zM16.4 19h1.8L7.7 5H5.8l10.6 14z" />
    </svg>

};

// ─── Scroll reveal hook ───────────────────────────────────────────────────
function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -60px 0px' });
    document.querySelectorAll('.reveal').forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ─── Phone scaler — renders an IOSDevice at full size, scales via CSS ─────
function PhoneStage({ scale = 0.75, rotate = 0, children, width = 390, height = 812 }) {
  return (
    <div className="phone-scaler" style={{
      width: width * scale,
      height: height * scale,
      transform: `rotate(${rotate}deg)`
    }}>
      <div style={{
        transform: `scale(${scale})`,
        transformOrigin: 'top left',
        width, height
      }}>
        <IOSDevice width={width} height={height}>
          <div style={{
            paddingTop: 54,
            height: '100%', display: 'flex', flexDirection: 'column',
            background: SMASH.off
          }}>
            <div style={{ flex: 1, overflowY: 'hidden' }}>
              {children}
            </div>
            <div style={{ height: 34 }} />
          </div>
        </IOSDevice>
      </div>
    </div>);

}

// Phone with green welcome bg
function PhoneStageDark({ scale = 0.75, rotate = 0, children, width = 390, height = 812 }) {
  return (
    <div className="phone-scaler" style={{
      width: width * scale,
      height: height * scale,
      transform: `rotate(${rotate}deg)`
    }}>
      <div style={{
        transform: `scale(${scale})`,
        transformOrigin: 'top left',
        width, height
      }}>
        <IOSDevice width={width} height={height} dark>
          <div style={{
            paddingTop: 54,
            height: '100%', display: 'flex', flexDirection: 'column',
            background: SMASH.green
          }}>
            <div style={{ flex: 1, overflowY: 'hidden' }}>
              {children}
            </div>
            <div style={{ height: 34 }} />
          </div>
        </IOSDevice>
      </div>
    </div>);

}

// ─── Top nav ──────────────────────────────────────────────────────────────
function Nav() {
  return (
    <div className="nav">
      <a href="#hero" className="smash-logo" style={{ fontFamily: "\"Bebas Neue\"", textDecoration: 'none', color: 'inherit' }}>SMASH</a>
      <div className="nav-right">
        <span>смотреть демо</span>
        <span className="ghost">Войти · скоро</span>
      </div>
    </div>);

}

// ─── Waitlist form (controlled, with optional NTRP + district) ────────────
function WaitlistForm({ variant = 'dark', ctaLabel = 'Хочу играть', showExtras = false }) {
  const [email, setEmail] = useState('');
  const [ntrp, setNtrp] = useState('');
  const [district, setDistrict] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showOptional, setShowOptional] = useState(showExtras);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!email.includes('@')) return;
    setLoading(true);
    setError('');
    try {
      await saveToWaitlist({ email, ntrp, district });
      setSubmitted(true);
    } catch (err) {
      // Duplicate email — treat as success (already registered)
      if (err.message && err.message.includes('duplicate')) {
        setSubmitted(true);
      } else {
        setError('Что-то пошло не так. Попробуй ещё раз.');
      }
    } finally {
      setLoading(false);
    }
  };

  const formClass = `email-form${variant === 'light' || variant === 'yellow' ? ' light' : ''}`;
  const extrasClass = `form-extras${variant === 'light' || variant === 'yellow' ? ' light' : ''}`;
  const noteClass = `form-note${variant === 'yellow' ? ' on-yellow' : ''}`;
  const successClass = `success-msg${variant === 'yellow' ? ' on-yellow' : variant === 'light' ? ' light' : ''}`;

  if (submitted) {
    return (
      <div className={successClass}>
        <strong>Готово.</strong>
        <span className="check">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
          strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12l5 5L20 7" />
          </svg>
        </span>
        Сообщим, когда запустим. Расскажи другу — каждый приглашённый поднимает тебя в очереди.
      </div>);

  }

  return (
    <form onSubmit={onSubmit}>
      <div className={formClass}>
        <input
          type="email"
          placeholder="твой email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          onFocus={() => setShowOptional(true)}
          required
          disabled={loading} />

        <button type="submit" disabled={loading}>
          {loading ? '...' : ctaLabel}
        </button>
      </div>
      {showOptional &&
      <div className={extrasClass}>
          <select value={ntrp} onChange={(e) => setNtrp(e.target.value)} disabled={loading}>
            <option value="">NTRP — не знаю</option>
            <option value="2.0">2.0</option>
            <option value="2.5">2.5</option>
            <option value="3.0">3.0</option>
            <option value="3.5">3.5</option>
            <option value="4.0">4.0</option>
            <option value="4.5">4.5</option>
            <option value="5.0+">5.0+</option>
          </select>
          <input
          type="text"
          placeholder="район — напр. Хамовники"
          value={district}
          onChange={(e) => setDistrict(e.target.value)}
          disabled={loading} />

        </div>
      }
      {error && <div className={noteClass} style={{ color: 'var(--red, #e53e3e)', marginTop: 8 }}>{error}</div>}
      <div className={noteClass}>Оставь свой email выше и получи доступ в SMASH первым!

      </div>
    </form>);

}

Object.assign(window, { LandingIcon, useReveal, PhoneStage, PhoneStageDark, Nav, WaitlistForm });