
"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from "@/components/ui/card";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter, usePathname } from "next/navigation";
import { ArrowLeft } from "lucide-react";

export default function InvestPage() {
  const { isAuthenticated, userRole } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  useEffect(() => {
    // Set a neutral background for this page
    document.body.style.backgroundImage = 'none';
    document.body.style.backgroundColor = 'hsl(var(--background))';

    // Cleanup function to restore the original background when the component unmounts
    return () => {
      document.body.style.backgroundImage = '';
      document.body.style.backgroundColor = '';
    };
  }, []);

  useEffect(() => {
    if (isClient) {
      if (!isAuthenticated || (userRole !== 'admin' && userRole !== 'creator')) {
        // Redirect to login if not authenticated or not the correct role
        // Allow a brief moment for auth state to settle before redirecting from non-login pages
        if (pathname !== '/login') {
            setTimeout(() => router.push('/login'), 100);
        }
      }
    }
  }, [isClient, isAuthenticated, userRole, router, pathname]);


  if (!isClient || !isAuthenticated || (userRole !== 'admin' && userRole !== 'creator')) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-center">
              {isClient && !isAuthenticated ? "Redirecting to Login..." : "Access Denied"}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-center text-muted-foreground">
              {isClient && isAuthenticated && (userRole !== 'admin' && userRole !== 'creator') 
                ? "You do not have permission to view this page. Redirecting..." 
                : "Please wait or log in with appropriate credentials."}
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  const handleBackToDashboard = () => {
    if (userRole === 'admin') {
      router.push('/admin');
    } else if (userRole === 'creator') {
      router.push('/user-dashboard');
    } else {
      router.back(); // Fallback for any other case or if role is not determined yet
    }
  };

  return (
    <main className="min-h-screen flex flex-col items-center p-4 sm:p-6 md:p-8">
      <div className="w-full max-w-3xl space-y-6">
        <Card className="shadow-xl rounded-lg">
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle className="text-3xl font-bold text-foreground">
                Invest with Us: RUNINGA
              </CardTitle>
              <Button variant="outline" onClick={() => router.back()} aria-label="Go back">
                <ArrowLeft className="mr-2 h-4 w-4" /> Back
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-6 text-foreground/90 prose prose-invert prose-sm sm:prose-base lg:prose-lg xl:prose-xl 2xl:prose-2xl mx-auto">
            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">1. Executive Summary</h2>
              <p>
                RUNINGA is a feature-rich, web-based streaming platform designed to empower content creators and engage viewers with a diverse range of live video, audio, and curated video content. With a robust backend powered by Firebase, the platform offers a clean interface, flexible playback controls, and integrated community features like likes and comments. RUNINGA simplifies content delivery for creators and enhances discovery for viewers. The platform includes distinct, powerful dashboards for administrators (content moderation, advanced analytics, user oversight) and content creators (content and playlist management, performance analytics), establishing a scalable and engaging streaming ecosystem ready for growth.
              </p>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">2. Problem Statement</h2>
              <p>
                The demand for online video and live streaming continues to surge. However, challenges persist:
              </p>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Complexity for Creators:</strong> Many aspiring creators and organizations find existing streaming solutions complex to set up, especially for varied media types.</li>
                <li><strong>Content Discovery:</strong> Viewers struggle to find diverse, independent, or niche content amidst mainstream options.</li>
                <li><strong>Engagement & Monetization:</strong> Traditional streaming often lacks robust interaction tools, and independent creators face significant hurdles in monetizing their content.</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">3. The RUNINGA Solution</h2>
              <p>
                RUNINGA addresses these challenges by providing a comprehensive, yet accessible, streaming solution built on a scalable Firebase architecture.
              </p>
              <h3 className="text-xl font-medium mt-2 mb-1">For Viewers:</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>An intuitive interface to browse and watch live video, audio streams, and VOD playlists.</li>
                <li>A flexible player that supports HLS, YouTube, and other embedded media for a seamless experience.</li>
                <li>Ability to like and comment on streams, fostering an active community.</li>
              </ul>
              <h3 className="text-xl font-medium mt-2 mb-1">For Content Creators:</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>Easy submission of live stream URLs (HLS, YouTube, Dacast, etc.) for both video and audio channels.</li>
                <li>Tools to create and manage video playlists from YouTube content.</li>
                <li>A dedicated dashboard to manage content, edit details, and view performance analytics to track viewership and compare against platform trends.</li>
              </ul>
              <h3 className="text-xl font-medium mt-2 mb-1">For Administrators:</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>A powerful dashboard to approve/reject submissions and manage all platform content.</li>
                <li>Detailed analytics, including real-time RTMP stream status, daily/monthly viewership charts, and peak time analysis.</li>
                <li>Content curation tools, such as the ability to "pin" featured video and audio streams independently.</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">4. Target Audience</h2>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Content Creators:</strong> Independent broadcasters, educators, gamers, musicians, radio hosts, and community organizers.</li>
                <li><strong>Viewers:</strong> Individuals seeking diverse content and interactive experiences.</li>
                <li><strong>Administrators:</strong> Platform owners and moderation teams.</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">5. Market Opportunity</h2>
              <p>The online streaming market is vast and continues to expand globally.</p>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Growth of Niche Content:</strong> There's a growing appetite for specialized content that larger platforms might overlook, including audio-only streams.</li>
                <li><strong>Creator Economy:</strong> The number of independent creators seeking platforms to share and monetize their work is rising.</li>
                <li><strong>Demand for Accessibility:</strong> A platform that lowers the barrier to entry for various streaming formats can capture a significant segment of new and existing creators.</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">6. Unique Selling Proposition (USP)</h2>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Simplicity & Flexibility:</strong> Easy-to-use interface supporting HLS, YouTube, direct embeds, and audio-only streams.</li>
                <li><strong>Integrated Community Features:</strong> Built-in likes and comments encourage viewer engagement.</li>
                <li><strong>Data-Driven Creator Tools:</strong> Analytics empower creators to understand their audience and grow.</li>
                <li><strong>Robust & Scalable Backend:</strong> Built on Firebase, ensuring reliability and readiness for future growth.</li>
                <li><strong>Advanced Admin Controls:</strong> Comprehensive analytics and content curation tools provide full platform management.</li>
              </ul>
            </section>
            
            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">7. Technology Stack</h2>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Frontend:</strong> Next.js, React, TypeScript</li>
                <li><strong>UI Components:</strong> ShadCN UI & Tailwind CSS</li>
                <li><strong>Video/Audio Playback:</strong> HLS.js</li>
                <li><strong>Backend & Database:</strong> Firebase Authentication & Realtime Database</li>
                <li><strong>Live Ingest:</strong> Nginx with RTMP module</li>
                <li><strong>AI (Future Integration):</strong> Genkit</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">8. Monetization Strategy (Potential Avenues)</h2>
              <p>With a solid technical foundation and growing user base, RUNINGA has several potential monetization paths:</p>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Freemium Model:</strong> Offer basic streaming for free, with paid tiers for creators that unlock advanced analytics, higher stream limits, or direct VOD uploads.</li>
                <li><strong>Advertising:</strong> Pre-roll, mid-roll, or display ads, with revenue sharing for creators.</li>
                <li><strong>Tips/Donations:</strong> Allow viewers to support creators directly, with the platform taking a small percentage.</li>
                <li><strong>Pay-Per-View (PPV):</strong> For exclusive live events or premium content.</li>
              </ul>
              <p className="mt-2">
                A phased approach is recommended, starting with the Freemium model to encourage creator adoption, followed by the introduction of advertising and tipping.
              </p>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">9. Marketing and Sales Strategy</h2>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li><strong>Digital Marketing:</strong> Targeted ads on social media, SEO for niche stream categories.</li>
                <li><strong>Content Marketing:</strong> Create tutorials and success stories highlighting how easy it is to stream on RUNINGA.</li>
                <li><strong>Creator Outreach:</strong> Partner with initial content creators in diverse fields to build a base of quality content.</li>
                <li><strong>Community Building:</strong> Engage with users on social media and leverage the platform's own features to foster a loyal community.</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">10. Roadmap / Future Development</h2>
              <h3 className="text-xl font-medium mt-2 mb-1">Phase 1 (Near-Term):</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>Refine UI/UX based on user feedback.</li>
                <li>Integrate cloud storage (e.g., Firebase Storage) for direct video-on-demand (VOD) uploads.</li>
                <li>Enhance search and discovery features for viewers.</li>
              </ul>
              <h3 className="text-xl font-medium mt-2 mb-1">Phase 2 (Growth):</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>Introduce initial monetization features (e.g., tipping or creator subscriptions).</li>
                <li>Implement basic AI-powered features with Genkit (e.g., auto-tagging for streams).</li>
                <li>Develop a more advanced recommendation engine.</li>
              </ul>
              <h3 className="text-xl font-medium mt-2 mb-1">Phase 3 (Expansion):</h3>
              <ul className="list-disc list-inside space-y-1 pl-4">
                <li>Develop mobile applications (Android/iOS).</li>
                <li>Expand AI features (e.g., content summarization, automated highlight reels).</li>
                <li>Introduce expanded monetization options (e.g., advertising platform, PPV).</li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl font-semibold border-b pb-2 mb-3">11. Conclusion</h2>
              <p>
                RUNINGA has evolved from a prototype into a robust and functional streaming platform with clear user roles, powerful management tools, and engaging community features. With its scalable Firebase architecture, flexible content support, and a clear roadmap, RUNINGA is well-positioned to attract a loyal base of creators and viewers. We are seeking investment to accelerate development, expand our user base, and begin implementing our monetization strategy.
              </p>
            </section>
          </CardContent>
          <CardFooter className="flex justify-center">
             <Button variant="default" onClick={handleBackToDashboard} aria-label="Back to Dashboard">
                <ArrowLeft className="mr-2 h-4 w-4" /> Back to Dashboard
              </Button>
          </CardFooter>
        </Card>
      </div>
    </main>
  );
}
