import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../widgets/gradient_mesh.dart';

class LegalScreen extends StatelessWidget {
  final bool showTerms; // true=terms, false=privacy

  const LegalScreen({super.key, this.showTerms = true});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      body: Stack(
        children: [
          const Positioned.fill(child: GradientMesh()),
          SafeArea(
            child: Column(
              children: [
                // App bar
                Padding(
                  padding: const EdgeInsets.fromLTRB(8, 8, 16, 0),
                  child: Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.arrow_back_rounded, color: AppColors.textPrimary),
                        onPressed: () => Navigator.pop(context),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        showTerms ? 'Terms of Service' : 'Privacy Policy',
                        style: AppTypography.headingMd.copyWith(color: AppColors.textPrimary),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                // Content
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.fromLTRB(24, 0, 24, 40),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(20),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                        child: Container(
                          padding: const EdgeInsets.all(24),
                          decoration: BoxDecoration(
                            color: Colors.white.withValues(alpha: 0.06),
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(color: AppColors.glassBorder),
                          ),
                          child: showTerms ? buildTerms() : buildPrivacy(),
                        ),
                      ),
                    ),
                  ),
                ),
                // View on web link
                Padding(
                  padding: const EdgeInsets.fromLTRB(24, 8, 24, 16),
                  child: GestureDetector(
                    onTap: () {
                      final url = showTerms
                          ? 'https://nomazra.kelthos.com/terms'
                          : 'https://nomazra.kelthos.com/privacy';
                      launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
                    },
                    child: Text(
                      'View full version on web →',
                      style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buildTerms() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading('Terms of Service'),
        date('Last updated: March 25, 2026'),
        para('Welcome to Reasonable Doubt. By using our app, you agree to these Terms of Service. Please read them carefully.'),

        section('1. Acceptance of Terms'),
        para('By creating an account or using Reasonable Doubt, you agree to be bound by these Terms. If you do not agree, do not use the Service.'),

        section('2. Description of Service'),
        para('Reasonable Doubt is an AI-powered legal information assistant. It provides general legal information, rights cards, glossary terms, document analysis, and AI-assisted legal chat for educational and informational purposes.'),

        section('3. Not Legal Advice'),
        para('IMPORTANT: Reasonable Doubt does NOT provide legal advice. The information provided by our AI is for general educational and informational purposes only. It is not a substitute for professional legal counsel. Always consult a qualified attorney for legal matters.'),

        section('4. User Accounts'),
        para('You must provide accurate information when creating an account. You are responsible for maintaining the confidentiality of your credentials. You must be at least 16 years old to use Reasonable Doubt.'),

        section('5. Acceptable Use'),
        para('You agree not to: use the service for illegal purposes, attempt to gain unauthorized access, share your account, or use automated systems to access the service.'),

        section('6. Subscription Plans'),
        para('Reasonable Doubt offers free and paid subscription plans. Paid plans are billed through Google Play. You may cancel at any time through your Google Play subscription settings. Refunds are subject to Google Play policies.'),

        section('7. Intellectual Property'),
        para('All content, features, and functionality of Reasonable Doubt are owned by Kelthos and protected by copyright and other intellectual property laws.'),

        section('8. Privacy'),
        para('Your use of Reasonable Doubt is also governed by our Privacy Policy. By using the service, you consent to the collection and use of information as described therein.'),

        section('9. Limitation of Liability'),
        para('Reasonable Doubt and Kelthos shall not be liable for any indirect, incidental, special, consequential, or punitive damages arising from your use of the service. Our total liability shall not exceed the amount you paid in the 12 months prior to the claim.'),

        section('10. Termination'),
        para('We reserve the right to suspend or terminate your account at any time for violation of these Terms. You may delete your account at any time through the app settings.'),

        section('11. Changes to Terms'),
        para('We may modify these Terms at any time. Continued use after changes constitutes acceptance. We will notify users of material changes via the app or email.'),

        section('12. Contact'),
        para('For questions about these Terms, contact us at support@kelthos.com.'),
      ],
    );
  }

  Widget buildPrivacy() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading('Privacy Policy'),
        date('Last updated: March 25, 2026'),
        para('This Privacy Policy describes how Reasonable Doubt ("we", "us", "our") collects, uses, and protects your personal information.'),

        section('1. Information We Collect'),
        para('• Account info: email, display name, country\n• Usage data: queries, documents uploaded, features used\n• Device info: device type, OS version, app version\n• Voice data: audio is processed in real-time and not stored after transcription'),

        section('2. How We Use Your Information'),
        para('• To provide and improve our AI legal assistant service\n• To personalize your experience based on your country\n• To send reminders and notifications you have set\n• To enforce usage limits per your subscription plan\n• To communicate service updates'),

        section('3. Data Storage & Security'),
        para('Your data is stored on secure servers with encryption at rest and in transit. Documents are stored on Cloudflare R2 with access controls. We use industry-standard security measures.'),

        section('4. Data Sharing'),
        para('We do NOT sell your personal information. We share data only with:\n• AI processing services (OpenAI) — conversations are sent for processing\n• Cloud storage (Cloudflare R2) — for document storage\n• Payment processors (Google Play) — for subscription management'),

        section('5. Your Rights'),
        para('You have the right to:\n• Access your personal data\n• Correct inaccurate data\n• Delete your account and all associated data\n• Export your data\n• Opt out of non-essential communications'),

        section('6. Data Retention'),
        para('We retain your data for as long as your account is active. Upon account deletion, all personal data is permanently removed within 30 days. Anonymous, aggregated analytics may be retained.'),

        section('7. Children\'s Privacy'),
        para('Reasonable Doubt is not intended for users under 16. We do not knowingly collect data from children under 16.'),

        section('8. Changes to Policy'),
        para('We may update this Privacy Policy periodically. We will notify you of significant changes via the app or email.'),

        section('9. Contact'),
        para('For privacy inquiries: support@kelthos.com'),
      ],
    );
  }

  Widget heading(String text) => Padding(
    padding: const EdgeInsets.only(bottom: 8),
    child: Text(text, style: AppTypography.headingLg.copyWith(color: AppColors.textPrimary)),
  );

  Widget date(String text) => Padding(
    padding: const EdgeInsets.only(bottom: 16),
    child: Text(text, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
  );

  Widget section(String text) => Padding(
    padding: const EdgeInsets.only(top: 20, bottom: 8),
    child: Text(text, style: AppTypography.headingMd.copyWith(color: AppColors.gold, fontSize: 16)),
  );

  Widget para(String text) => Padding(
    padding: const EdgeInsets.only(bottom: 8),
    child: Text(text, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary, height: 1.6)),
  );
}
