import React, { useState, useEffect } from 'react';
import { 
  Activity, 
  FileText, 
  Dumbbell, 
  AlertCircle, 
  Pill, 
  Plus, 
  Check, 
  Upload, 
  Trash2, 
  ChevronRight,
  TrendingUp, 
  Droplet,
  Calendar,
  Layers
} from 'lucide-react';

// --- INITIAL MOCK DATA ---
const initialExercises = [
  { id: 1, name: '90/90 Hip Internal Rotation Liftoffs', sets: 3, reps: '5 reps (5s hold)', tempo: 'Controlled', notes: 'Maintain upright posture, avoid spinal compensation.' },
  { id: 2, name: 'Eccentric Calf Raises (Slant Board)', sets: 3, reps: '10 reps', tempo: '4s lowering', notes: 'Focus on full depth elongation at the bottom.' },
  { id: 3, name: 'Side-Lying Clamshells with Band Resistance', sets: 3, reps: '15 reps', tempo: '2s hold', notes: 'Keep pelvis stacked; do not roll backward.' }
];

const initialMeds = [
  { id: 1, name: 'Omega-3 Fish Oil', dosage: '2000mg', frequency: 'Daily', taken: true },
  { id: 2, name: 'Vitamin D3 + K2', dosage: '5000 IU', frequency: 'Daily', taken: true },
  { id: 3, name: 'Ibuprofen', dosage: '400mg', frequency: 'As Needed / Post-Rehab', taken: false }
];

const initialSymptomLog = [
  { id: 1, date: '2026-05-18', region: 'Right Knee', intensity: 4, tags: ['Stiffness', 'Sharp Pain'] },
  { id: 2, date: '2026-05-16', region: 'Right Knee', intensity: 6, tags: ['Swelling', 'Throbbing'] }
];

const initialDocs = [
  { id: 1, name: 'Right_Knee_MRI_Impressions.pdf', date: '2026-04-12', type: 'Imaging', notes: 'Grade II MCL sprain confirmed. Lateral meniscus structurally intact.' }
];

export default function PremiumHealthDashboard() {
  // --- APPLICATION STATE ---
  const [activeTab, setActiveTab] = useState('overview');
  const [hepType, setHepType] = useState('prescribed');
  const [completedExercises, setCompletedExercises] = useState({});
  const [sessionFeedback, setSessionFeedback] = useState(3);
  
  // Dynamic User lists
  const [symptoms, setSymptoms] = useState(() => {
    const local = localStorage.getItem('rt_symptoms');
    return local ? JSON.parse(local) : initialSymptomLog;
  });
  const [meds, setMeds] = useState(() => {
    const local = localStorage.getItem('rt_meds');
    return local ? JSON.parse(local) : initialMeds;
  });
  const [docs, setDocs] = useState(() => {
    const local = localStorage.getItem('rt_docs');
    return local ? JSON.parse(local) : initialDocs;
  });
  
  // Pain Form State
  const [painRegion, setPainRegion] = useState('Right Knee');
  const [painIntensity, setPainIntensity] = useState(3);
  const [selectedTags, setSelectedTags] = useState([]);
  
  // Med Form State
  const [newMedName, setNewMedName] = useState('');
  const [newMedDose, setNewMedDose] = useState('');
  const [newMedFreq, setNewMedFreq] = useState('Daily');

  // Nutrition & Water State
  const [waterIntake, setWaterIntake] = useState(48); // oz
  const [nutrition, setNutrition] = useState({ calories: 1950, protein: 145, carbs: 180, fats: 65 });
  const targets = { calories: 2400, protein: 175, carbs: 220, fats: 80, water: 100 };

  // Doc Upload Form State
  const [docName, setDocName] = useState('');
  const [docType, setDocType] = useState('Imaging');
  const [docNotes, setDocNotes] = useState('');

  // --- LOCAL STORAGE PERSISTENCE ENGINE ---
  useEffect(() => {
    localStorage.setItem('rt_symptoms', JSON.stringify(symptoms));
  }, [symptoms]);

  useEffect(() => {
    localStorage.setItem('rt_meds', JSON.stringify(meds));
  }, [meds]);

  useEffect(() => {
    localStorage.setItem('rt_docs', JSON.stringify(docs));
  }, [docs]);

  // --- COMPLIANCE CALCULATIONS ---
  const hepProgress = Math.round(
    (Object.values(completedExercises).filter(Boolean).length / initialExercises.length) * 100
  );
  const medCompliance = Math.round(
    (meds.filter(m => m.taken).length / meds.length) * 100
  );
  const nutritionProgress = Math.round((nutrition.calories / targets.calories) * 100);

  // --- HANDLERS ---
  const handleToggleExercise = (id) => {
    setCompletedExercises(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const handleAddSymptom = (e) => {
    e.preventDefault();
    const newEntry = {
      id: Date.now(),
      date: new Date().toISOString().split('T')[0],
      region: painRegion,
      intensity: Number(painIntensity),
      tags: selectedTags
    };
    setSymptoms([newEntry, ...symptoms]);
    setSelectedTags([]);
  };

  const handleToggleTag = (tag) => {
    setSelectedTags(prev => 
      prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag]
    );
  };

  const handleToggleMed = (id) => {
    setMeds(meds.map(m => m.id === id ? { ...m, taken: !m.taken } : m));
  };

  const handleAddMed = (e) => {
    e.preventDefault();
    if (!newMedName) return;
    const item = { id: Date.now(), name: newMedName, dosage: newMedDose, frequency: newMedFreq, taken: false };
    setMeds([...meds, item]);
    setNewMedName(''); setNewMedDose('');
  };

  const handleDeleteMed = (id) => {
    setMeds(meds.filter(m => m.id !== id));
  };

  const handleAddDoc = (e) => {
    e.preventDefault();
    if (!docName) return;
    const newDoc = {
      id: Date.now(),
      name: docName.endsWith('.pdf') || docName.endsWith('.jpg') ? docName : `${docName}.pdf`,
      date: new Date().toISOString().split('T')[0],
      type: docType,
      notes: docNotes
    };
    setDocs([newDoc, ...docs]);
    setDocName(''); setDocNotes('');
  };

  const handleDeleteDoc = (id) => {
    setDocs(docs.filter(d => d.id !== id));
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 font-sans antialiased selection:bg-emerald-500/30 selection:text-emerald-400">
      
      {/* GLOBAL BACKGROUND GLOWS */}
      <div className="fixed inset-0 overflow-hidden pointer-events-none z-0">
        <div className="absolute top-[-10%] left-[-10%] w-[50vw] h-[50vw] rounded-full bg-emerald-500/5 blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[40vw] h-[40vw] rounded-full bg-teal-500/5 blur-[120px]" />
      </div>

      <div className="flex min-h-screen relative z-10 pb-20 md:pb-0">
        
        {/* DESKTOP RESPONSIVE SIDEBAR */}
        <aside className="hidden md:flex flex-col w-64 bg-slate-900/60 backdrop-blur-xl border-r border-slate-800/80 p-6 space-y-8 sticky top-0 h-screen">
          <div className="flex items-center space-x-3 px-2">
            <div className="p-2 bg-emerald-500/10 rounded-xl border border-emerald-500/20 text-emerald-400">
              <Activity size={24} />
            </div>
            <div>
              <h1 className="text-md font-bold tracking-tight text-white uppercase">ReTri Portal</h1>
              <p className="text-xs text-slate-400 font-medium">Performance & Rehab</p>
            </div>
          </div>

          <nav className="flex-1 space-y-1.5">
            {[
              { id: 'overview', label: 'Dashboard Hub', icon: Activity },
              { id: 'workout', label: 'Rehab & HEP', icon: Dumbbell },
              { id: 'symptoms', label: 'Symptom & Pain Log', icon: AlertCircle },
              { id: 'meds', label: 'Meds & Nutrition', icon: Pill },
              { id: 'documents', label: 'Document Center', icon: FileText },
            ].map((tab) => {
              const Icon = tab.icon;
              const isSelected = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200 ${
                    isSelected 
                      ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 shadow-[0_0_20px_rgba(16,185,129,0.05)]' 
                      : 'text-slate-400 hover:text-slate-200 hover:bg-slate-800/40 border border-transparent'
                  }`}
                >
                  <Icon size={18} className={isSelected ? 'text-emerald-400' : 'text-slate-400'} />
                  <span>{tab.label}</span>
                </button>
              );
            })}
          </nav>

          <div className="pt-4 border-t border-slate-800/60 text-xs text-slate-500 px-2 font-mono">
            v1.2.0-secure // encrypted
          </div>
        </aside>

        {/* MAIN DISPLAY REGION */}
        <main className="flex-1 max-w-7xl mx-auto p-4 sm:p-6 lg:p-8 w-full overflow-x-hidden">
          
          {/* VIEW: HUB OVERVIEW */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-800/60 pb-5">
                <div>
                  <h2 className="text-2xl font-bold tracking-tight text-white">Welcome Back</h2>
                  <p className="text-sm text-slate-400 mt-1">Here is the current operational status of your recovery metrics.</p>
                </div>
                <div className="flex items-center space-x-2 bg-slate-900/50 backdrop-blur-md px-4 py-2 rounded-xl border border-slate-800 text-xs font-mono text-slate-300 shadow-sm w-fit">
                  <Calendar size={14} className="text-emerald-400" />
                  <span>{new Date().toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' })}</span>
                </div>
              </div>

              {/* PROGRESS RINGS GRID */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="bg-slate-900/40 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 flex items-center space-x-4">
                  <div className="relative flex items-center justify-center w-16 h-16 flex-shrink-0">
                    <svg className="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
                      <path className="text-slate-800" strokeWidth="3" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                      <path className="text-emerald-500 transition-all duration-500" strokeDasharray={`${hepProgress}, 100`} strokeWidth="3" strokeLinecap="round" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                    </svg>
                    <span className="absolute text-xs font-semibold font-mono text-white">{hepProgress}%</span>
                  </div>
                  <div>
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">Rehab Compliance</h4>
                    <p className="text-lg font-bold text-slate-100 mt-0.5">Home Exercise</p>
                  </div>
                </div>

                <div className="bg-slate-900/40 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 flex items-center space-x-4">
                  <div className="relative flex items-center justify-center w-16 h-16 flex-shrink-0">
                    <svg className="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
                      <path className="text-slate-800" strokeWidth="3" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                      <path className="text-teal-400 transition-all duration-500" strokeDasharray={`${medCompliance}, 100`} strokeWidth="3" strokeLinecap="round" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                    </svg>
                    <span className="absolute text-xs font-semibold font-mono text-white">{medCompliance}%</span>
                  </div>
                  <div>
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">Medical Routine</h4>
                    <p className="text-lg font-bold text-slate-100 mt-0.5">Meds & Supps</p>
                  </div>
                </div>

                <div className="bg-slate-900/40 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 flex items-center space-x-4">
                  <div className="relative flex items-center justify-center w-16 h-16 flex-shrink-0">
                    <svg className="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
                      <path className="text-slate-800" strokeWidth="3" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                      <path className="text-sky-400 transition-all duration-500" strokeDasharray={`${Math.min(nutritionProgress, 100)}, 100`} strokeWidth="3" strokeLinecap="round" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                    </svg>
                    <span className="absolute text-xs font-semibold font-mono text-white">{nutritionProgress}%</span>
                  </div>
                  <div>
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">Energy Targets</h4>
                    <p className="text-lg font-bold text-slate-100 mt-0.5">{nutrition.calories} / {targets.calories} kcal</p>
                  </div>
                </div>
              </div>

              {/* QUICK ACTUATORS SECTION */}
              <div className="bg-gradient-to-r from-slate-900/80 to-slate-900/30 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80">
                <h3 className="text-sm font-semibold tracking-wider uppercase text-slate-400 mb-4">Direct Task Routing</h3>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                  <button onClick={() => setActiveTab('symptoms')} className="flex items-center justify-between p-4 bg-slate-800/40 hover:bg-slate-800/80 border border-slate-700/40 rounded-xl transition-all group">
                    <span className="text-sm font-medium text-slate-200 group-hover:text-white">Log Current Symptom</span>
                    <ChevronRight size={16} className="text-slate-500 group-hover:text-emerald-400 transition-colors" />
                  </button>
                  <button onClick={() => setActiveTab('workout')} className="flex items-center justify-between p-4 bg-slate-800/40 hover:bg-slate-800/80 border border-slate-700/40 rounded-xl transition-all group">
                    <span className="text-sm font-medium text-slate-200 group-hover:text-white">Run Today's HEP Set</span>
                    <ChevronRight size={16} className="text-slate-500 group-hover:text-emerald-400 transition-colors" />
                  </button>
                  <button onClick={() => setActiveTab('meds')} className="flex items-center justify-between p-4 bg-slate-800/40 hover:bg-slate-800/80 border border-slate-700/40 rounded-xl transition-all group">
                    <span className="text-sm font-medium text-slate-200 group-hover:text-white">Update Macronutrients</span>
                    <ChevronRight size={16} className="text-slate-500 group-hover:text-emerald-400 transition-colors" />
                  </button>
                </div>
              </div>

              {/* CORRELATION DATA ENGINE (SVG METRIC VISUALIZATION) */}
              <div className="bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-3">
                  <div>
                    <div className="flex items-center space-x-2">
                      <TrendingUp size={16} className="text-emerald-400" />
                      <h3 className="text-base font-bold text-white">System Dynamics: Volume vs Pain Intensity</h3>
                    </div>
                    <p className="text-xs text-slate-400 mt-0.5">Rolling 7-day analytical overlay modeling mechanical stress outputs against neurological feedback.</p>
                  </div>
                  <div className="flex items-center space-x-4 text-xs font-medium">
                    <div className="flex items-center space-x-1.5">
                      <span className="w-3 h-3 bg-emerald-500 rounded-sm" />
                      <span className="text-slate-300">Workout Volume (Sets)</span>
                    </div>
                    <div className="flex items-center space-x-1.5">
                      <span className="w-3 h-0.5 bg-rose-400 inline-block" />
                      <span className="text-slate-300">Pain Level (VAS)</span>
                    </div>
                  </div>
                </div>

                {/* ADVANCED CUSTOM CORRELATION CHART */}
                <div className="h-64 w-full flex items-end justify-between pt-4 px-2 relative border-b border-l border-slate-800/80">
                  
                  {/* Grid Lines */}
                  <div className="absolute inset-0 flex flex-col justify-between pointer-events-none opacity-20 py-4">
                    <div className="border-b border-slate-700 w-full" />
                    <div className="border-b border-slate-700 w-full" />
                    <div className="border-b border-slate-700 w-full" />
                  </div>

                  {/* Absolute Position SVG Line Path Overlay for Pain */}
                  <svg className="absolute inset-0 h-full w-full pointer-events-none px-4 pt-4 pb-0" viewBox="0 0 100 100" preserveAspectRatio="none">
                    <path d="M 5,75 Q 20,40 35,50 T 65,25 T 95,60" fill="none" stroke="#fb7185" strokeWidth="2.5" strokeLinecap="round" />
                    {/* Data Nodes */}
                    <circle cx="5" cy="75" r="2" fill="#fb7185" />
                    <circle cx="20" cy="40" r="2" fill="#fb7185" />
                    <circle cx="35" cy="50" r="2" fill="#fb7185" />
                    <circle cx="50" cy="35" r="2" fill="#fb7185" />
                    <circle cx="65" cy="25" r="2" fill="#fb7185" />
                    <circle cx="80" cy="45" r="2" fill="#fb7185" />
                    <circle cx="95" cy="60" r="2" fill="#fb7185" />
                  </svg>

                  {/* Bars representing exercise units */}
                  {[
                    { day: 'Mon', volume: 40 },
                    { day: 'Tue', volume: 75 },
                    { day: 'Wed', volume: 20 },
                    { day: 'Thu', volume: 90 },
                    { day: 'Fri', volume: 85 },
                    { day: 'Sat', volume: 30 },
                    { day: 'Sun', volume: 10 },
                  ].map((item, idx) => (
                    <div key={idx} className="flex flex-col items-center flex-1 group z-10">
                      <div className="w-8 bg-emerald-500/20 group-hover:bg-emerald-500/40 rounded-t-sm transition-all relative" style={{ height: `${item.volume}px` }}>
                        <div className="absolute top-[-24px] left-1/2 transform -translate-x-1/2 bg-slate-900 text-[10px] font-mono px-1.5 py-0.5 rounded border border-slate-700 opacity-0 group-hover:opacity-100 transition-opacity">
                          {Math.round(item.volume / 10)}s
                        </div>
                      </div>
                      <span className="text-[10px] font-mono text-slate-500 mt-2">{item.day}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* VIEW: WORKOUT / HEP TRACKER */}
          {activeTab === 'workout' && (
            <div className="space-y-6">
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center border-b border-slate-800/60 pb-5 gap-4">
                <div>
                  <h2 className="text-2xl font-bold tracking-tight text-white">Exercise & Rehabilitation System</h2>
                  <p className="text-sm text-slate-400 mt-1">Execute your targeted loading protocols and track localized joint resilience feedback.</p>
                </div>
                
                {/* Protocol Toggle Buttons */}
                <div className="flex bg-slate-900 p-1 rounded-xl border border-slate-800">
                  <button 
                    onClick={() => setHepType('prescribed')}
                    className={`px-4 py-1.5 rounded-lg text-xs font-semibold transition-all ${hepType === 'prescribed' ? 'bg-emerald-500 text-slate-950' : 'text-slate-400 hover:text-slate-200'}`}
                  >
                    Prescribed HEP
                  </button>
                  <button 
                    onClick={() => setHepType('general')}
                    className={`px-4 py-1.5 rounded-lg text-xs font-semibold transition-all ${hepType === 'general' ? 'bg-emerald-500 text-slate-950' : 'text-slate-400 hover:text-slate-200'}`}
                  >
                    General Loading
                  </button>
                </div>
              </div>

              {/* ROUTINE MANIFEST */}
              <div className="space-y-3">
                {initialExercises.map((ex) => {
                  const isDone = !!completedExercises[ex.id];
                  return (
                    <div 
                      key={ex.id}
                      className={`p-5 rounded-2xl border transition-all duration-200 ${
                        isDone 
                          ? 'bg-slate-900/20 border-emerald-500/20 opacity-70' 
                          : 'bg-slate-900/40 border-slate-800/80 hover:border-slate-700/60'
                      }`}
                    >
                      <div className="flex items-start justify-between gap-4">
                        <div className="flex items-start space-x-4">
                          <button 
                            onClick={() => handleToggleExercise(ex.id)}
                            className={`mt-0.5 w-6 h-6 rounded-lg border flex items-center justify-center transition-all flex-shrink-0 ${
                              isDone 
                                ? 'bg-emerald-500 border-emerald-500 text-slate-950' 
                                : 'border-slate-700 hover:border-emerald-500/50 bg-slate-950 text-transparent'
                            }`}
                          >
                            <Check size={14} strokeWidth={3} />
                          </button>
                          <div>
                            <h4 className={`text-base font-bold transition-all ${isDone ? 'line-through text-slate-500' : 'text-white'}`}>
                              {ex.name}
                            </h4>
                            <div className="flex flex-wrap gap-2 mt-2">
                              <span className="text-xs px-2.5 py-0.5 bg-slate-800 rounded-md font-mono text-slate-300 border border-slate-700/50">
                                {ex.sets} Sets
                              </span>
                              <span className="text-xs px-2.5 py-0.5 bg-slate-800 rounded-md font-mono text-slate-300 border border-slate-700/50">
                                {ex.reps}
                              </span>
                              <span className="text-xs px-2.5 py-0.5 bg-emerald-950/40 text-emerald-400 rounded-md font-mono border border-emerald-900/50">
                                Tempo: {ex.tempo}
                              </span>
                            </div>
                            <p className="text-xs text-slate-400 mt-2.5 leading-relaxed bg-slate-950/40 p-2.5 rounded-lg border border-slate-800/60 max-w-2xl">
                              <span className="text-slate-400 font-semibold block mb-0.5">Execution Cue:</span>
                              {ex.notes}
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* REHAB FEEDBACK MATRIX */}
              <div className="bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 space-y-4">
                <div>
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider">Post-Session Neurological Tolerance</h3>
                  <p className="text-xs text-slate-400 mt-0.5">Quantify current structural overload or feedback symptoms post-training to adjust next pacing cycles.</p>
                </div>
                
                <div className="space-y-4 pt-2">
                  <input 
                    type="range" min="1" max="5" 
                    value={sessionFeedback}
                    onChange={(e) => setSessionFeedback(Number(e.target.value))}
                    className="w-full accent-emerald-500 h-1.5 bg-slate-800 rounded-lg cursor-pointer"
                  />
                  <div className="grid grid-cols-5 text-center text-[11px] font-medium text-slate-400 px-1 font-mono">
                    <span className={sessionFeedback === 1 ? 'text-emerald-400 font-bold' : ''}>1. Optimal</span>
                    <span className={sessionFeedback === 2 ? 'text-teal-400 font-bold' : ''}>2. Tolerable</span>
                    <span className={sessionFeedback === 3 ? 'text-yellow-400 font-bold' : ''}>3. Fatigued</span>
                    <span className={sessionFeedback === 4 ? 'text-orange-400 font-bold' : ''}>4. Minor Flare</span>
                    <span className={sessionFeedback === 5 ? 'text-rose-500 font-bold' : ''}>5. Aggravated</span>
                  </div>
                  
                  <div className="flex justify-end pt-2">
                    <button 
                      onClick={() => {
                        alert("Session execution metrics parsed into systemic tracking ledger.");
                        setCompletedExercises({});
                      }}
                      className="px-5 py-2.5 bg-emerald-500 hover:bg-emerald-400 text-slate-950 rounded-xl text-xs font-bold transition-all shadow-[0_4px_20px_rgba(16,185,129,0.15)]"
                    >
                      Commit Session Ledger
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* VIEW: SYMPTOM LOG */}
          {activeTab === 'symptoms' && (
            <div className="space-y-6">
              <div className="border-b border-slate-800/60 pb-5">
                <h2 className="text-2xl font-bold tracking-tight text-white">Neurological & Symptom Input Manifest</h2>
                <p className="text-sm text-slate-400 mt-1">Map visual patterns of localized mechanical pain signals to tracking ledgers.</p>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                
                {/* INTERACTIVE FORM PANEL */}
                <form onSubmit={handleAddSymptom} className="bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 space-y-5 lg:col-span-1">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider flex items-center space-x-2">
                    <AlertCircle size={16} className="text-emerald-400" />
                    <span>Log Active State</span>
                  </h3>

                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Target Region</label>
                    <select 
                      value={painRegion} 
                      onChange={(e) => setPainRegion(e.target.value)}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-sm text-slate-200 focus:outline-none focus:border-emerald-500/50"
                    >
                      <option>Right Knee</option>
                      <option>Left Knee</option>
                      <option>Lumbar Spine</option>
                      <option>Cervical Spine</option>
                      <option>Right Shoulder (GHL)</option>
                      <option>Left Ankle / Achilles</option>
                      <option>Plantar Fascia</option>
                    </select>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between items-center text-xs text-slate-400 uppercase tracking-wider font-medium">
                      <span>Pain Intensity</span>
                      <span className="font-mono text-sm font-bold text-emerald-400 bg-slate-950 px-2 py-0.5 rounded border border-slate-800">{painIntensity} / 10</span>
                    </div>
                    <input 
                      type="range" min="0" max="10" 
                      value={painIntensity} 
                      onChange={(e) => setPainIntensity(e.target.value)}
                      className="w-full accent-emerald-500 h-1.5 bg-slate-800 rounded-lg cursor-pointer"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-xs font-medium text-slate-400 uppercase tracking-wider block">Symptom Descriptor Profiles</label>
                    <div className="flex flex-wrap gap-1.5">
                      {['Stiffness', 'Sharp Pain', 'Throbbing', 'Dull Ache', 'Numbness', 'Swelling', 'Instability'].map((tag) => {
                        const active = selectedTags.includes(tag);
                        return (
                          <button
                            key={tag} type="button"
                            onClick={() => handleToggleTag(tag)}
                            className={`text-xs px-2.5 py-1 rounded-md border font-medium transition-all ${
                              active 
                                ? 'bg-emerald-500/10 border-emerald-500/40 text-emerald-400' 
                                : 'bg-slate-950 border-slate-800 text-slate-400 hover:border-slate-700'
                            }`}
                          >
                            {tag}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <button type="submit" className="w-full py-2.5 bg-emerald-500 hover:bg-emerald-400 text-slate-950 rounded-xl text-xs font-bold transition-all shadow-[0_4px_20px_rgba(16,185,129,0.15)] flex items-center justify-center space-x-2">
                    <Plus size={14} strokeWidth={3} />
                    <span>Commit Entry</span>
                  </button>
                </form>

                {/* HISTORICAL HISTOGRAM GRID */}
                <div className="lg:col-span-2 space-y-3">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider px-1">Symptom Registry Chronology</h3>
                  {symptoms.length === 0 ? (
                    <div className="p-8 text-center bg-slate-900/20 rounded-2xl border border-slate-800 text-slate-500 text-sm">
                      No mechanical symptoms registered. System is functional.
                    </div>
                  ) : (
                    symptoms.map((log) => (
                      <div key={log.id} className="bg-slate-900/40 backdrop-blur-md p-4 rounded-xl border border-slate-800/80 flex items-center justify-between gap-4">
                        <div className="space-y-1">
                          <div className="flex items-center space-x-3">
                            <span className="text-sm font-bold text-white">{log.region}</span>
                            <span className="text-[10px] font-mono text-slate-500 bg-slate-950 px-2 py-0.5 rounded border border-slate-800">{log.date}</span>
                          </div>
                          <div className="flex flex-wrap gap-1.5 pt-1">
                            {log.tags.map((t, i) => (
                              <span key={i} className="text-[10px] bg-slate-800 text-slate-300 px-2 py-0.5 rounded border border-slate-700/50 font-medium">
                                {t}
                              </span>
                            ))}
                          </div>
                        </div>

                        <div className="flex items-center space-x-4">
                          <div className="text-right">
                            <span className={`text-xl font-black font-mono tracking-tight ${
                              log.intensity >= 7 ? 'text-rose-500' : log.intensity >= 4 ? 'text-amber-400' : 'text-emerald-400'
                            }`}>
                              {log.intensity}
                            </span>
                            <span className="text-[10px] text-slate-500 uppercase font-bold tracking-wider block">VAS</span>
                          </div>
                          <button 
                            onClick={() => setSymptoms(symptoms.filter(s => s.id !== log.id))}
                            className="p-1.5 text-slate-500 hover:text-rose-400 transition-colors"
                          >
                            <Trash2 size={14} />
                          </button>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </div>
          )}

          {/* VIEW: MEDS & NUTRITION */}
          {activeTab === 'meds' && (
            <div className="space-y-6">
              <div className="border-b border-slate-800/60 pb-5">
                <h2 className="text-2xl font-bold tracking-tight text-white">Biochemical & Energy Optimization Manager</h2>
                <p className="text-sm text-slate-400 mt-1">Regulate supplemental workflows, clinical prescriptions, and fluid/macronutrient balances.</p>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                
                {/* PHARMACEUTICAL AND SUPPLEMENT TRACKER */}
                <div className="bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 space-y-4">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider flex items-center space-x-2">
                    <Pill size={16} className="text-emerald-400" />
                    <span>Meds & Supplements Manifest</span>
                  </h3>

                  <form onSubmit={handleAddMed} className="grid grid-cols-1 sm:grid-cols-3 gap-2 bg-slate-950 p-2.5 rounded-xl border border-slate-800/60">
                    <input 
                      type="text" placeholder="Compound Name" required value={newMedName}
                      onChange={(e) => setNewMedName(e.target.value)}
                      className="bg-slate-900 text-xs text-slate-200 px-3 py-2 rounded-lg border border-slate-800 focus:outline-none focus:border-emerald-500/40"
                    />
                    <input 
                      type="text" placeholder="Dosage (e.g. 500mg)" required value={newMedDose}
                      onChange={(e) => setNewMedDose(e.target.value)}
                      className="bg-slate-900 text-xs text-slate-200 px-3 py-2 rounded-lg border border-slate-800 focus:outline-none focus:border-emerald-500/40"
                    />
                    <button type="submit" className="py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-bold text-xs rounded-lg transition-all flex items-center justify-center space-x-1">
                      <Plus size={14} strokeWidth={3} />
                      <span>Add Entry</span>
                    </button>
                  </form>

                  <div className="space-y-2 pt-2">
                    {meds.map((med) => (
                      <div key={med.id} className="flex items-center justify-between p-3 bg-slate-950/60 border border-slate-800/80 rounded-xl">
                        <div className="flex items-center space-x-3">
                          <button 
                            onClick={() => handleToggleMed(med.id)}
                            className={`w-5 h-5 rounded-md border flex items-center justify-center transition-all ${
                              med.taken ? 'bg-emerald-500 border-emerald-500 text-slate-950' : 'border-slate-700 text-transparent bg-slate-900'
                            }`}
                          >
                            <Check size={12} strokeWidth={3} />
                          </button>
                          <div>
                            <span className={`text-xs font-bold block ${med.taken ? 'text-slate-500 line-through' : 'text-slate-200'}`}>{med.name}</span>
                            <span className="text-[10px] font-mono text-slate-500">{med.dosage} · {med.frequency}</span>
                          </div>
                        </div>
                        <button onClick={() => handleDeleteMed(med.id)} className="text-slate-600 hover:text-rose-400 p-1 transition-colors">
                          <Trash2 size={14} />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                {/* MACRONUTRIENT & HYDRATION TRACKER */}
                <div className="bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 space-y-6">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider flex items-center space-x-2">
                    <Droplet size={16} className="text-emerald-400" />
                    <span>Metabolic & Hydration Analytics</span>
                  </h3>

                  {/* Water intake controller */}
                  <div className="bg-slate-950/60 p-4 rounded-xl border border-slate-800/80 flex items-center justify-between">
                    <div>
                      <span className="text-xs font-bold text-slate-300 block">Systemic Hydration Log</span>
                      <span className="text-xl font-black font-mono text-sky-400 mt-0.5 block">{waterIntake} <span className="text-xs text-slate-500 uppercase font-medium">/ {targets.water} oz</span></span>
                    </div>
                    <div className="flex space-x-1">
                      <button onClick={() => setWaterIntake(w => Math.max(0, w - 8))} className="px-3 py-1.5 bg-slate-900 border border-slate-800 rounded-lg text-xs font-mono text-slate-400 hover:text-slate-200">-8oz</button>
                      <button onClick={() => setWaterIntake(w => w + 8)} className="px-3 py-1.5 bg-sky-500/10 border border-sky-500/20 text-sky-400 rounded-lg text-xs font-mono font-bold hover:bg-sky-500/20">+8oz</button>
                    </div>
                  </div>

                  {/* Macro breakdown vectors */}
                  <div className="space-y-3">
                    <span className="text-xs font-bold text-slate-400 uppercase tracking-wider block">Macronutrient Densities</span>
                    
                    <div>
                      <div className="flex justify-between text-xs font-mono text-slate-400 mb-1">
                        <span>Protein (Structural Amino Blocks)</span>
                        <span className="text-slate-200 font-bold">{nutrition.protein}g / {targets.protein}g</span>
                      </div>
                      <div className="w-full bg-slate-950 h-2 rounded-full overflow-hidden border border-slate-800">
                        <div className="bg-emerald-500 h-full transition-all duration-300" style={{ width: `${Math.min((nutrition.protein/targets.protein)*100, 100)}%` }} />
                      </div>
                    </div>

                    <div>
                      <div className="flex justify-between text-xs font-mono text-slate-400 mb-1">
                        <span>Carbohydrates (Glycogen Resupply)</span>
                        <span className="text-slate-200 font-bold">{nutrition.carbs}g / {targets.carbs}g</span>
                      </div>
                      <div className="w-full bg-slate-950 h-2 rounded-full overflow-hidden border border-slate-800">
                        <div className="bg-teal-400 h-full transition-all duration-300" style={{ width: `${Math.min((nutrition.carbs/targets.carbs)*100, 100)}%` }} />
                      </div>
                    </div>

                    <div>
                      <div className="flex justify-between text-xs font-mono text-slate-400 mb-1">
                        <span>Lipids / Fats (Hormonal Synthetics)</span>
                        <span className="text-slate-200 font-bold">{nutrition.fats}g / {targets.fats}g</span>
                      </div>
                      <div className="w-full bg-slate-950 h-2 rounded-full overflow-hidden border border-slate-800">
                        <div className="bg-sky-400 h-full transition-all duration-300" style={{ width: `${Math.min((nutrition.fats/targets.fats)*100, 100)}%` }} />
                      </div>
                    </div>
                  </div>
                </div>

              </div>
            </div>
          )}

          {/* VIEW: DOCUMENT CENTER */}
          {activeTab === 'documents' && (
            <div className="space-y-6">
              <div className="border-b border-slate-800/60 pb-5">
                <h2 className="text-2xl font-bold tracking-tight text-white">Clinical Data Vault & Imaging Registry</h2>
                <p className="text-sm text-slate-400 mt-1">Upload external records, radiology parameters, and bloodwork parameters into secure containment fields.</p>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                
                {/* UPLOAD SIMULATOR ENGINE */}
                <div className="lg:col-span-1 bg-slate-900/40 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 space-y-4">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider flex items-center space-x-2">
                    <Upload size={16} className="text-emerald-400" />
                    <span>Upload Record File</span>
                  </h3>

                  <form onSubmit={handleAddDoc} className="space-y-3">
                    <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Document Name / Title</label>
                      <input 
                        type="text" placeholder="e.g. Bloodwork_Panel_Q2" required value={docName}
                        onChange={(e) => setDocName(e.target.value)}
                        className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-200 focus:outline-none focus:border-emerald-500/40"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Classification Matrix</label>
                      <select 
                        value={docType} onChange={(e) => setDocType(e.target.value)}
                        className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-200 focus:outline-none focus:border-emerald-500/40"
                      >
                        <option>Imaging (MRI, X-Ray, US)</option>
                        <option>Bloodwork / Lab Panel</option>
                        <option>Clinical Notes / Scripts</option>
                        <option>Other Manifests</option>
                      </select>
                    </div>

                    <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Clinical Annotations & Personal Impressions</label>
                      <textarea 
                        rows="3" placeholder="Log physical reactions, operational parameters or primary notes here..." value={docNotes}
                        onChange={(e) => setDocNotes(e.target.value)}
                        className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-200 focus:outline-none focus:border-emerald-500/40 resize-none"
                      />
                    </div>

                    {/* Drag and Drop Zone Wrapper Mock */}
                    <div className="border border-dashed border-slate-700 bg-slate-950/40 rounded-xl p-4 text-center cursor-pointer hover:border-emerald-500/30 transition-colors">
                      <Layers size={20} className="text-slate-600 mx-auto mb-1.5" />
                      <span className="text-[10px] text-slate-400 block font-medium">Drag raw file targets directly here</span>
                    </div>

                    <button type="submit" className="w-full py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-bold text-xs rounded-xl transition-all shadow-md">
                      Commit Document Target
                    </button>
                  </form>
                </div>

                {/* ARCHIVAL MANIFEST REGISTRY */}
                <div className="lg:col-span-2 space-y-3">
                  <h3 className="text-sm font-bold text-white uppercase tracking-wider px-1">Secure Digital Archive Vault</h3>
                  
                  {docs.length === 0 ? (
                    <div className="p-8 text-center bg-slate-900/20 rounded-2xl border border-slate-800 text-slate-500 text-sm">
                      No external data uploads indexed in profile matrix.
                    </div>
                  ) : (
                    docs.map((doc) => (
                      <div key={doc.id} className="bg-slate-900/40 backdrop-blur-md p-4 rounded-xl border border-slate-800/80 space-y-2">
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex items-center space-x-3">
                            <div className="p-2.5 bg-slate-950 rounded-lg border border-slate-800 text-emerald-400">
                              <FileText size={18} />
                            </div>
                            <div>
                              <span className="text-xs font-bold text-white block">{doc.name}</span>
                              <div className="flex items-center space-x-2 mt-0.5">
                                <span className="text-[9px] font-mono font-bold bg-emerald-950/50 text-emerald-400 border border-emerald-900 px-1.5 py-0.2 rounded">
                                  {doc.type}
                                </span>
                                <span className="text-[10px] font-mono text-slate-500">{doc.date}</span>
                              </div>
                            </div>
                          </div>
                          
                          <button onClick={() => handleDeleteDoc(doc.id)} className="p-1.5 text-slate-600 hover:text-rose-400 transition-colors">
                            <Trash2 size={14} />
                          </button>
                        </div>
                        {doc.notes && (
                          <p className="text-[11px] leading-relaxed text-slate-400 bg-slate-950/50 border border-slate-800/80 p-2.5 rounded-lg mt-1 font-mono">
                            <span className="text-slate-500 font-bold uppercase block text-[9px] mb-0.5 tracking-wider">// Clinical Annotations:</span>
                            {doc.notes}
                          </p>
                        )}
                      </div>
                    ))
                  )}
                </div>
              </div>
            </div>
          )}

        </main>

        {/* MOBILE BOTTOM NAVIGATION BAR */}
        <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-slate-900/90 backdrop-blur-lg border-t border-slate-800/80 px-2 py-2 flex justify-around items-center z-50 shadow-xl">
          {[
            { id: 'overview', label: 'Hub', icon: Activity },
            { id: 'workout', label: 'Rehab', icon: Dumbbell },
            { id: 'symptoms', label: 'Pain', icon: AlertCircle },
            { id: 'meds', label: 'Meds', icon: Pill },
            { id: 'documents', label: 'Vault', icon: FileText },
          ].map((tab) => {
            const Icon = tab.icon;
            const isSelected = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex flex-col items-center space-y-0.5 px-2 py-1.5 rounded-lg transition-colors ${
                  isSelected ? 'text-emerald-400' : 'text-slate-500'
                }`}
              >
                <Icon size={18} />
                <span className="text-[10px] font-medium tracking-tight">{tab.label}</span>
              </button>
            );
          })}
        </nav>

      </div>
    </div>
  );
}