import { Component, createSignal, onMount } from 'solid-js';
import { A, useSearchParams } from '@solidjs/router';
import { useWaitlistSignup, useWaitlistCount } from '../../lib/api/trpc-hooks';

export const Landing: Component = () => {
  const [searchParams] = useSearchParams();
  const [email, setEmail] = createSignal('');
  const [name, setName] = createSignal('');
  const [submitted, setSubmitted] = createSignal(false);
  const [error, setError] = createSignal('');
  const [referralCode, setReferralCode] = createSignal('');
  const [myReferralCode, setMyReferralCode] = createSignal('');

  const signup = useWaitlistSignup();
  const count = useWaitlistCount();

  onMount(() => {
    const ref = searchParams.ref;
    if (ref && typeof ref === 'string') {
      setReferralCode(ref);
    }
  });

  const handleSubmit = async (e: Event) => {
    e.preventDefault();
    setError('');

    if (!email().trim()) {
      setError('Please enter your email address.');
      return;
    }

    try {
      const result = await signup.mutateAsync({
        email: email().trim(),
        name: name().trim() || undefined,
        source: referralCode() ? 'referral' : 'organic',
        referralCode: referralCode() || undefined,
      });
      if (result.referralCode) {
        setMyReferralCode(result.referralCode);
      }
      setSubmitted(true);
    } catch (err: any) {
      setError(err?.message || 'Something went wrong. Please try again.');
    }
  };

  const waitlistCount = () => {
    const c = count.data?.count;
    if (!c) return '0';
    if (c >= 1000) return `${(c / 1000).toFixed(1)}k+`;
    return String(c);
  };

  const shareUrl = () => {
    if (!myReferralCode()) return '';
    return `${window.location.origin}?ref=${myReferralCode()}`;
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl());
    } catch {
      const input = document.createElement('input');
      input.value = shareUrl();
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
    }
  };

  return (
    <div class="landing-page">
      {/* Navigation */}
      <nav class="landing-nav">
        <div class="nav-container">
          <div class="nav-logo">
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
              <path d="M16 2L4 8V24L16 30L28 24V8L16 2Z" fill="#518ac8"/>
              <path d="M16 6L8 10V22L16 26L24 22V10L16 6Z" fill="#76b3e1"/>
            </svg>
            <span class="logo-text">Scripter</span>
          </div>
          <div class="nav-links">
            <a href="#features">Features</a>
            <a href="#pricing">Pricing</a>
            <a href="/blog">Blog</a>
            <A href="/sign-in" class="nav-signin">Sign In</A>
          </div>
        </div>
      </nav>

      {/* Hero Section */}
      <section class="hero">
        <div class="hero-content">
          <h1 class="hero-headline">Write Faster.</h1>
          <p class="hero-subheadline">
            The modern screenwriting platform built for how you actually work.
            Real-time collaboration, AI-powered writing, and industry-standard formatting — all in one place.
          </p>

          {submitted() ? (
            <div class="waitlist-success">
              <div class="success-icon">🎉</div>
              <h3>You're on the list!</h3>
              <p>We'll notify you when Scripter launches. In the meantime, spread the word.</p>
              {myReferralCode() && (
                <div class="referral-share">
                  <p class="referral-label">Share your unique referral link:</p>
                  <div class="referral-link-box">
                    <input type="text" value={shareUrl()} readonly class="referral-input" />
                    <button onClick={copyToClipboard} class="copy-btn">Copy</button>
                  </div>
                  <p class="referral-hint">Earn early access perks for every friend who joins!</p>
                </div>
              )}
              <A href="/sign-up" class="cta-primary">Explore the App</A>
            </div>
          ) : (
            <form onSubmit={handleSubmit} class="waitlist-form">
              <div class="form-row">
                <input
                  type="text"
                  placeholder="Your name (optional)"
                  value={name()}
                  onInput={(e) => setName(e.currentTarget.value)}
                  class="form-input"
                />
              </div>
              <div class="form-row">
                <input
                  type="email"
                  placeholder="Enter your email"
                  value={email()}
                  onInput={(e) => setEmail(e.currentTarget.value)}
                  class="form-input"
                  required
                />
                <button type="submit" class="cta-primary" disabled={signup.isPending}>
                  {signup.isPending ? 'Joining...' : 'Join the Waitlist'}
                </button>
              </div>
              {error() && <p class="form-error">{error()}</p>}
              {referralCode() && (
                <p class="referral-notice">You were referred by a friend!</p>
              )}
            </form>
          )}
        </div>
        <div class="hero-visual">
          <div class="screenshot-mockup">
            <div class="mockup-header">
              <div class="mockup-dots">
                <span></span><span></span><span></span>
              </div>
            </div>
            <div class="mockup-content">
              <pre>{`FADE IN:

EXT. COFFEE SHOP - DAY

SARAH (28, determined) types furiously on her laptop. 
The barista calls her name.

                    BARISTA
          Sarah! Your latte is ready!

She doesn't look up. In the zone.`}</pre>
            </div>
          </div>
        </div>
      </section>

      {/* Social Proof */}
      <section class="social-proof">
        <p>Join the growing community of screenwriters</p>
        <div class="proof-badges">
          <span class="badge counter-badge">
            <span class="counter-number">{waitlistCount()}</span> writers on the waitlist
          </span>
          <span class="badge">🎬 Industry Standard</span>
          <span class="badge">⭐ 5-Star Reviews</span>
        </div>
      </section>

      {/* Features Overview */}
      <section id="features" class="features">
        <h2 class="section-title">Everything you need to write</h2>
        <div class="features-grid">
          <div class="feature-card">
            <div class="feature-icon">📝</div>
            <h3>Industry-Standard Formatting</h3>
            <p>Automatic screenplay formatting. Scene headings, action, dialogue, parentheticals — all formatted to spec.</p>
          </div>
          <div class="feature-card">
            <div class="feature-icon">👥</div>
            <h3>Real-Time Collaboration</h3>
            <p>Write together with your team. See changes live, leave comments, chat with video.</p>
          </div>
          <div class="feature-card">
            <div class="feature-icon">🤖</div>
            <h3>AI Writing Assistant</h3>
            <p>Get help with dialogue, scene descriptions, character analysis, and more.</p>
          </div>
        </div>
      </section>

      {/* Comparison Section */}
      <section class="comparison">
        <h2 class="section-title">Why switch to Scripter?</h2>
        <div class="comparison-grid">
          <div class="comparison-col">
            <h3>vs Final Draft</h3>
            <ul>
              <li><span class="check">✓</span> $7.99/mo vs $199 one-time</li>
              <li><span class="check">✓</span> Real-time collaboration vs desktop-only</li>
              <li><span class="check">✓</span> Works on any device</li>
              <li><span class="check">✓</span> Cloud backup included</li>
            </ul>
          </div>
          <div class="comparison-col">
            <h3>vs WriterDuet</h3>
            <ul>
              <li><span class="check">✓</span> Unlimited projects (free)</li>
              <li><span class="check">✓</span> Faster native app (Tauri)</li>
              <li><span class="check">✓</span> Built-in AI assistant</li>
              <li><span class="check">✓</span> 33% lower pricing</li>
            </ul>
          </div>
        </div>
      </section>

      {/* Pricing Section */}
      <section id="pricing" class="pricing">
        <h2 class="section-title">Simple pricing for every screenwriter</h2>
        <p class="section-subtitle">Start free. Upgrade when you need more.</p>

        <div class="pricing-grid">
          <div class="pricing-card">
            <h3>Free</h3>
            <div class="price">$0<span>/mo</span></div>
            <ul class="features-list">
              <li>Unlimited projects</li>
              <li>Industry-standard formatting</li>
              <li>Auto cloud saving</li>
              <li>Mobile editing</li>
              <li>Comments & mentions</li>
            </ul>
            <A href="/sign-up" class="pricing-cta">Get Started Free</A>
          </div>

          <div class="pricing-card featured">
            <div class="featured-badge">Most Popular</div>
            <h3>Pro</h3>
            <div class="price">$7.99<span>/mo</span></div>
            <ul class="features-list">
              <li>Everything in Free, plus:</li>
              <li>Real-time collaboration</li>
              <li>Desktop app (Mac, Windows, Linux)</li>
              <li>Offline writing</li>
              <li>Video chat</li>
              <li>Revision tracking</li>
            </ul>
            <A href="/sign-up" class="pricing-cta">Start Pro Trial</A>
            <p class="trial-note">14-day free trial</p>
          </div>

          <div class="pricing-card">
            <h3>Premium</h3>
            <div class="price">$10.99<span>/mo</span></div>
            <ul class="features-list">
              <li>Everything in Pro, plus:</li>
              <li>Infinite document history</li>
              <li>AI writing assistant</li>
              <li>Auto-translate (30+ languages)</li>
              <li>ReadAloud narration</li>
              <li>Priority support</li>
            </ul>
            <A href="/sign-up" class="pricing-cta">Start Premium Trial</A>
            <p class="trial-note">14-day free trial</p>
          </div>
        </div>
      </section>

      {/* Final CTA */}
      <section class="final-cta">
        <h2>Ready to write your next script?</h2>
        <p>Join thousands of screenwriters who've made the switch.</p>
        <A href="/sign-up" class="cta-primary">Start Writing Free</A>
      </section>

      {/* Footer */}
      <footer class="landing-footer">
        <div class="footer-content">
          <div class="footer-brand">
            <div class="nav-logo">
              <svg width="24" height="24" viewBox="0 0 32 32" fill="none">
                <path d="M16 2L4 8V24L16 30L28 24V8L16 2Z" fill="#518ac8"/>
              </svg>
              <span>Scripter</span>
            </div>
            <p>Write Faster.</p>
          </div>
          <div class="footer-links">
            <div class="footer-col">
              <h4>Product</h4>
              <a href="#features">Features</a>
              <a href="#pricing">Pricing</a>
              <a href="/blog">Blog</a>
            </div>
            <div class="footer-col">
              <h4>Company</h4>
              <a href="/about">About</a>
              <a href="/faq">FAQ</a>
              <a href="/contact">Contact</a>
            </div>
            <div class="footer-col">
              <h4>Legal</h4>
              <a href="/terms">Terms</a>
              <a href="/privacy">Privacy</a>
            </div>
          </div>
        </div>
        <div class="footer-bottom">
          <p>&copy; 2026 Scripter. All rights reserved.</p>
        </div>
      </footer>
    </div>
  );
};
