import React, { useState, useRef } from 'react'; import { Rulebook } from '../types'; import { FoldText } from './animations/FoldText'; import { RotatingText } from './animations/RotatingText'; import { TextType } from './animations/TextType'; import { analyzeIssueApi, AIAnalysisResponse } from '../services/api'; interface RulebookSelectorProps { rulebooks: Rulebook[]; selectedCity?: string; onSelectRulebook: (rulebookId: string, initialPrompt?: string) => void; onLaunchAICase?: (aiData: AIAnalysisResponse, rawText: string) => void; onSaveAICaseToCloud?: (aiData: AIAnalysisResponse, rawText: string) => Promise; onViewAllRulebooks: () => void; onAnalyzePrompt: (prompt: string) => void; onOpenGuidedIntake?: (category?: string) => void; onOpenRtiAuditor?: () => void; } const SAMPLE_SCENARIOS = [ 'Landlord refusing to refund ₹1,40,000 security deposit after clean handover', 'Municipal corporation tender expenditure and quality audit for Ward 150 road work', 'E-commerce seller delivered defective laptop and refused refund of ₹64,990', 'Employer withholding 2 months salary and ₹1,80,000 F&F settlement after resignation', 'Bank refusing chargeback for ₹50,000 unauthorized credit card transaction', ]; export const RulebookSelector: React.FC = ({ rulebooks, selectedCity = 'Delhi (NCR)', onSelectRulebook, onLaunchAICase, onSaveAICaseToCloud, onViewAllRulebooks, onAnalyzePrompt, onOpenGuidedIntake, onOpenRtiAuditor, }) => { const [searchQuery, setSearchQuery] = useState(''); const [isInputFocused, setIsInputFocused] = useState(false); const [selectedPdf, setSelectedPdf] = useState(null); const [analyzing, setAnalyzing] = useState(false); const [analysisError, setAnalysisError] = useState(null); const [aiAnalysis, setAiAnalysis] = useState(null); const [savedToCloudFeedback, setSavedToCloudFeedback] = useState(false); const [copiedBrief, setCopiedBrief] = useState(false); const [copiedRtiDraft, setCopiedRtiDraft] = useState(false); const fileInputRef = useRef(null); const handlePdfUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) { setSelectedPdf(file); if (!searchQuery.trim()) { setSearchQuery(`Document Attached: ${file.name}`); } } else { alert('Please select a valid PDF file.'); } } }; const handleRemovePdf = () => { setSelectedPdf(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } if (searchQuery.startsWith('Document Attached:')) { setSearchQuery(''); } }; const handleAnalyze = async (textToAnalyze?: string) => { let text = (textToAnalyze ?? searchQuery).trim(); if (!text && !selectedPdf) { text = SAMPLE_SCENARIOS[0]; setSearchQuery(text); } else if (!text && selectedPdf) { text = `Analyze attached document: ${selectedPdf.name}`; setSearchQuery(text); } setAnalyzing(true); setAnalysisError(null); setAiAnalysis(null); setSavedToCloudFeedback(false); try { const result = await analyzeIssueApi(text, selectedCity, selectedPdf || undefined); setAiAnalysis(result); } catch (err: any) { console.error('Error analyzing grievance:', err); setAnalysisError(err?.message || 'Failed to reach AI analysis engine. Please try again.'); } finally { setAnalyzing(false); } }; const handleCopyBrief = () => { if (!aiAnalysis) return; const briefText = `CASE BRIEF: Title: ${aiAnalysis.title} Statute: ${aiAnalysis.statute} Category: ${aiAnalysis.category} Authority: ${aiAnalysis.officer.name} (${aiAnalysis.officer.title}, ${aiAnalysis.officer.department}) Statutory Window: ${aiAnalysis.daysRemaining} days CIVIC RIGHTS: ${aiAnalysis.civicRights?.map((r) => `• ${r}`).join('\n') || 'N/A'} ${aiAnalysis.pdfSummary ? `DOCUMENT SUMMARY:\n${aiAnalysis.pdfSummary}\n\n` : ''}DRAFTED RTI APPLICATION: ${aiAnalysis.draftedRti || aiAnalysis.formalLetter} LEGAL ASSESSMENT: ${aiAnalysis.legalDiagnosis}`; navigator.clipboard.writeText(briefText); setCopiedBrief(true); setTimeout(() => setCopiedBrief(false), 2500); }; const handleCopyRtiDraft = () => { if (!aiAnalysis) return; const textToCopy = aiAnalysis.draftedRti || aiAnalysis.formalLetter || ''; navigator.clipboard.writeText(textToCopy); setCopiedRtiDraft(true); setTimeout(() => setCopiedRtiDraft(false), 2500); }; const handleSaveToCloud = async () => { if (!aiAnalysis || !onSaveAICaseToCloud) return; try { await onSaveAICaseToCloud(aiAnalysis, searchQuery || selectedPdf?.name || SAMPLE_SCENARIOS[0]); setSavedToCloudFeedback(true); setTimeout(() => setSavedToCloudFeedback(false), 3000); } catch (err) { console.error('Failed to save to cloud:', err); } }; return (
{/* Hero Section */}

{/* Subheading with Rotating Badge */}
Generate statutory legal notices and filings for
{/* Quick Action Badges */}
{/* Search & PDF Attachment Bar */}
search
setSearchQuery(e.target.value)} onFocus={() => setIsInputFocused(true)} onBlur={() => setIsInputFocused(false)} onKeyDown={(e) => { if (e.key === 'Enter') handleAnalyze(); }} placeholder={selectedPdf ? `Attached: ${selectedPdf.name}` : ''} className="w-full pl-12 pr-48 py-4 rounded-xl bg-white border border-[#CBD5E1] focus:border-[#0F172A] focus:ring-2 focus:ring-[#0F172A]/10 text-[15px] sm:text-[16px] text-[#0F172A] shadow-sm transition-all duration-200" /> {!searchQuery && !selectedPdf && !isInputFocused && (
e.g.
)} {/* Clear button */} {searchQuery && ( )} {/* Action Group: PDF Upload + Analyze */}
{/* Attached File Indicator */} {selectedPdf && (
picture_as_pdf {selectedPdf.name} ({(selectedPdf.size / 1024).toFixed(1)} KB)
)}
{/* Quick Scenario Buttons */}
Quick Scenarios: {SAMPLE_SCENARIOS.map((prompt, idx) => ( ))}
{/* Error message */} {analysisError && (
error

Analysis Notice

{analysisError}

)} {/* AI Analysis Results Dashboard */} {aiAnalysis && (
{/* Header Strip */}
verified {aiAnalysis.category} Statute: {aiAnalysis.statute}
schedule Statutory Clock: {aiAnalysis.daysRemaining} Days
thumb_up Viability: {aiAnalysis.initialScore || 88}%
{/* Case Title & Legal Assessment */}

{aiAnalysis.title}

Legal Assessment: {aiAnalysis.legalDiagnosis}

{/* 1. Civic Rights Box */}

balance Your Civic Rights & Legal Standing

Statutory Entitlements
    {aiAnalysis.civicRights && aiAnalysis.civicRights.length > 0 ? ( aiAnalysis.civicRights.map((right, index) => (
  • check_circle {right}
  • )) ) : (
  • You have the right to seek information, demand accountability, and obtain verified responses under statutory laws.
  • )}
{/* 2. Document Summary Box */} {(aiAnalysis.pdfSummary || selectedPdf) && (

description Document Summary (Plain English)

{selectedPdf ? selectedPdf.name : 'Analyzed Document'}
{aiAnalysis.pdfSummary || `Uploaded file "${selectedPdf?.name}" was analyzed and distilled into actionable civic rights and RTI queries.`}
)} {/* 3. Drafted RTI Application Box */}

edit_document Drafted RTI Application

                  {aiAnalysis.draftedRti || aiAnalysis.formalLetter}
                
{/* Routing Authority & Protections Bar */}
{aiAnalysis.officer.avatar || 'AO'}
Routing Authority

{aiAnalysis.officer.name}

{aiAnalysis.officer.department}

shield
Privacy & Security

PII Masking Active

Personal details auto-redacted before submission

{/* Action Bar */}
{onSaveAICaseToCloud && ( )}
)}
{/* Statutory Filing Templates Catalog */}

Statutory Filing Templates

Select a statutory template to assess your rights and draft a legally binding notice.

{/* 2x2 Grid */}
{/* Card 1: RTI */}
onOpenGuidedIntake ? onOpenGuidedIntake('rti') : onSelectRulebook('rti')} className="bg-white border border-[#CBD5E1] rounded-xl p-6 flex flex-col gap-4 hover:border-[#006c4a] hover:shadow-md transition-all duration-200 group cursor-pointer relative overflow-hidden" >
description

Right to Information (RTI)

ACTIVE TEMPLATE

File formal requests to access certified records, file notesheets, tender expenditures, or status reports held by public authorities under RTI Act 2005.

timer Est. 15 mins to draft
{/* Card 2: Consumer Disputes */}
onOpenGuidedIntake ? onOpenGuidedIntake('consumer') : onSelectRulebook('consumer')} className="bg-white border border-[#CBD5E1] rounded-xl p-6 flex flex-col gap-4 hover:border-[#006c4a] hover:shadow-md transition-all duration-200 group cursor-pointer relative overflow-hidden" >
shopping_bag

Consumer Disputes & Refunds

ACTIVE TEMPLATE

Demand full refunds, replacements, or damages from sellers, airlines, or service providers for defective goods and service deficiencies under Consumer Protection Act 2019.

timer Est. 20 mins to draft
{/* Card 3: Tenancy Notice */}
onOpenGuidedIntake ? onOpenGuidedIntake('tenancy') : onSelectRulebook('tenancy')} className="bg-white border border-[#CBD5E1] rounded-xl p-6 flex flex-col gap-4 hover:border-[#006c4a] hover:shadow-md transition-all duration-200 group cursor-pointer relative overflow-hidden" >
home_work

Tenancy & Security Deposit Notice

ACTIVE TEMPLATE

Statutory pre-litigation notices for landlords unlawfully withholding rental deposits, arbitrary deductions, or illegal eviction notices under Tenancy Acts.

timer Est. 15 mins to draft
{/* Card 4: Wage Recovery */}
onOpenGuidedIntake ? onOpenGuidedIntake('employment') : onSelectRulebook('employment')} className="bg-white border border-[#CBD5E1] rounded-xl p-6 flex flex-col gap-4 hover:border-[#006c4a] hover:shadow-md transition-all duration-200 group cursor-pointer relative overflow-hidden" >
payments

Wage Recovery & Labor Settlement

ACTIVE TEMPLATE

Formal demand notices for unpaid salary, withheld full & final settlement (F&F), gratuity, and relieving certificates under Payment of Wages and Labor laws.

timer Est. 18 mins to draft
); };