"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import {
  Code2,
  Disc3,
  Gamepad2,
  Zap,
  Clock,
  ChevronDown,
  ChevronUp,
  Activity,
  X,
} from "lucide-react";

// Types matching your n8n output
interface StatusData {
  status: {
    text: string;
    color: string;
  };
  music: {
    isPlaying: boolean;
    track: string;
    artist: string;
    album: string;
    albumArt: string;
    url: string;
  } | null;
  gaming: {
    isPlaying: boolean;
    name: string;
    image: string | null;
    state?: string;
    details?: string;
  } | null;
  coding: {
    isActive: boolean;
    project?: string;
    file?: string;
    language?: string;
    stats?: {
      time: string;
      topLang: string;
      topProject: string;
    };
  } | null;
}

export default function ActivityFeed() {
  const [data, setData] = useState<StatusData | null>(null);
  const [isExpanded, setIsExpanded] = useState(true);
  const [isMinimized, setIsMinimized] = useState(false);
  const [hasActivity, setHasActivity] = useState(false);
  // NOTE: Don't read localStorage during initial render.
  // Doing so can cause a hydration mismatch (SSR default vs client preference),
  // which can leave the feed stuck in its initial (small/transparent) motion styles.
  const [isTrackingEnabled, setIsTrackingEnabled] = useState(true);
  const [quote, setQuote] = useState<{
    content: string;
    author: string;
  } | null>(null);

  // Sync tracking preference after mount (client-only)
  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const stored = localStorage.getItem("activityTrackingEnabled");
      const enabled = stored !== "false"; // Default to true if not set
      setIsTrackingEnabled(enabled);
    } catch (error) {
      // localStorage might be disabled
      if (process.env.NODE_ENV === "development") {
        console.warn("Failed to read tracking preference:", error);
      }
      // Keep default (enabled)
    }
  }, []);

  // Fetch data every 30 seconds (optimized to match server cache)
  useEffect(() => {
    // Don't fetch if tracking is disabled or during SSR
    if (!isTrackingEnabled || typeof window === 'undefined') {
      return;
    }

    const fetchData = async () => {
      try {
        const fallback: StatusData = {
          status: { text: "offline", color: "gray" },
          music: null,
          gaming: null,
          coding: null,
        };

        // Check if fetch is available (should be, but safety check)
        if (typeof fetch === 'undefined') {
          setData(fallback);
          setHasActivity(false);
          return;
        }

        // Add timestamp to prevent aggressive caching but respect server cache
        const res = await fetch("/api/n8n/status", {
          cache: "default",
        }).catch((fetchError) => {
          // Handle network errors gracefully
          if (process.env.NODE_ENV === 'development') {
            console.warn('ActivityFeed: Fetch failed:', fetchError);
          }
          return null;
        });
        
        if (!res || !res.ok) {
          if (process.env.NODE_ENV === 'development' && res) {
            console.warn('ActivityFeed: API returned non-OK status:', res.status);
          }
          // Don't stay in tiny "loading" state forever; show stable fallback UI.
          setData(fallback);
          setHasActivity(false);
          return;
        }
        
        let json: unknown;
        try {
          json = await res.json();
        } catch (parseError) {
          if (process.env.NODE_ENV === 'development') {
            console.warn('ActivityFeed: Failed to parse JSON response:', parseError);
          }
          setData(fallback);
          setHasActivity(false);
          return;
        }

        if (process.env.NODE_ENV === 'development') {
          console.log("ActivityFeed data (raw):", json);
        }

        // Handle array response if API returns it wrapped
        if (Array.isArray(json)) {
          json = json[0] || null;
        }

        if (process.env.NODE_ENV === 'development') {
          console.log("ActivityFeed data (processed):", json);
        }

        if (!json || typeof json !== 'object') {
          setData(fallback);
          setHasActivity(false);
          return;
        }

        // Type assertion - API should return StatusData format
        const activityData = json as StatusData;
        setData(activityData);

        // Check if there's any active activity
        const coding = activityData.coding;
        const gaming = activityData.gaming;
        const music = activityData.music;
        
        const hasActiveActivity = Boolean(
          coding?.isActive ||
          gaming?.isPlaying ||
          music?.isPlaying
        );

        if (process.env.NODE_ENV === 'development') {
          console.log("Has activity:", hasActiveActivity, {
            coding: coding?.isActive,
            gaming: gaming?.isPlaying,
            music: music?.isPlaying,
          });
        }

        setHasActivity(hasActiveActivity);

        // Auto-expand if there's new activity and not minimized
        if (hasActiveActivity && !isMinimized) {
          setIsExpanded(true);
        }
      } catch (error) {
        // Silently fail - activity feed is not critical
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch activity:", error);
        }
        // Don't set error state - show stable fallback
        setData({
          status: { text: "offline", color: "gray" },
          music: null,
          gaming: null,
          coding: null,
        });
        setHasActivity(false);
      }
    };

    fetchData();
    // Optimized: Poll every 30 seconds instead of 10 to reduce server load
    // The n8n API already has 30s cache, so faster polling doesn't help
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, [isMinimized, isTrackingEnabled]);

  // Fetch nerdy quote when idle
  useEffect(() => {
    if (!hasActivity && !quote) {
      const techQuotes = [
        {
          content:
            "Computer Science is no more about computers than astronomy is about telescopes.",
          author: "Edsger W. Dijkstra",
        },
        {
          content: "Simplicity is prerequisite for reliability.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "The computing scientist's main challenge is not to get confused by the complexities of his own making.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "If debugging is the process of removing software bugs, then programming must be the process of putting them in.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "A program is like a poem: you cannot write a poem without writing it. Yet people talk about programming as if it were a production process and measure programmer productivity in terms of number of lines of code produced. In so doing they book that number on the wrong side of the ledger: We should always refer to the number of lines of code spent.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.",
          author: "Tony Hoare",
        },
        {
          content:
            "The best minds of my generation are thinking about how to make people click ads.",
          author: "Jeff Hammerbacher",
        },
        {
          content:
            "The tools we use have a profound and devious influence on our thinking habits, and therefore on our thinking abilities.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            'How do we convince people that in programming simplicity and clarity — in short: what mathematicians call "elegance" — are not a dispensable luxury, but a crucial matter that decides between success and failure?',
          author: "Edsger W. Dijkstra",
        },
        {
          content: "Adding manpower to a late software project makes it later.",
          author: "Fred Brooks",
        },
        {
          content:
            "Sometimes there is a silver bullet for boosting software engineering productivity. But you need to shoot the right person.",
          author: "Michael Stal",
        },
        {
          content: "Nine women can't make a baby in one month.",
          author: "Fred Brooks",
        },
        {
          content: "Deleted code is debugged code.",
          author: "Jeff Sickel",
        },
        {
          content: "When in doubt, use brute force.",
          author: "Ken Thompson",
        },
        {
          content:
            "When a task cannot be partitioned because of sequential constraints, the application of more effort has no effect on the schedule. The bearing of a child takes nine months, no matter how many women are assigned.",
          author: "Fred Brooks",
        },
        {
          content:
            "If each part of the task must be separately coordinated with each other part, the effort increases as n(n-1)/2. Three workers require three times as much pairwise intercommunication as two; four require six times as much as two.",
          author: "Fred Brooks",
        },
        {
          content:
            "Having a system architect is the most important single step toward conceptual integrity. After teaching a software engineering laboratory more than 20 times, I came to insist that student teams as small as four people choose a manager and a separate architect.",
          author: "Fred Brooks",
        },
        {
          content:
            "The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures.",
          author: "Fred Brooks",
        },
        {
          content:
            'The first false assumption that underlies the scheduling of systems programming is that all will go well, i.e., that each task will hike only as long as it "ought" to take. A large programming effort, however, consists of many tasks, some chained end-to-end. The probability that each will go well becomes vanishingly small.',
          author: "Fred Brooks",
        },
        {
          content:
            "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.",
          author: "Donald Knuth",
        },
        {
          content:
            "One of my most productive days was throwing away 1,000 lines of code.",
          author: "Ken Thompson",
        },
        {
          content:
            "One accurate measurement is worth more than a thousand expert opinions.",
          author: "Grace Hopper",
        },
        {
          content:
            "What one programmer can do in one month, two programmers can do in two months.",
          author: "Fred Brooks",
        },
        {
          content:
            "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.",
          author: "Rick Osborne",
        },
        {
          content:
            "A program that produces incorrect results twice as fast is infinitely slower.",
          author: "John Ousterhout",
        },
        {
          content:
            "I have yet to see any problem, however complicated, which when looked at in the right way, did not become more complicated.",
          author: "Poul Anderson",
        },
        {
          content:
            "Cleaning code does NOT take time. NOT cleaning code does take time.",
          author: "Robert C. Martin",
        },
        {
          content:
            "Beauty is more important in computing than anywhere else in technology because software is so complicated. Beauty is the ultimate defense against complexity.",
          author: "David Gelernter",
        },
        {
          content:
            "Walking on water and developing software from a specification are easy if both are frozen.",
          author: "Edward V. Berard",
        },
        {
          content:
            "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
          author: "Brian Kernighan",
        },
        {
          content:
            "Controlling complexity is the essence of computer programming.",
          author: "Brian Kernighan",
        },
        {
          content:
            "Debugging time increases as a square of the program's size.",
          author: "Chris Wenham",
        },
        {
          content:
            "The trouble with programmers is that you can never tell what a programmer is doing until it's too late.",
          author: "Seymour Cray",
        },
        {
          content: "Code never lies, comments sometimes do.",
          author: "Ron Jeffries",
        },
        {
          content:
            "Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them.",
          author: "Laurence J. Peter",
        },
        {
          content:
            'Make a guess, double the number, and then move to the next larger unit of time. This rule scales tasks in a very interesting way: a one-minute task explodes by a factor of 120 to take two hours. A one-hour job explodes by "only" a factor 48 to take two days, while a one-day job grows by a factor of 14 to take two weeks.',
          author: "Poul-Henning Kamp",
        },
        {
          content: "I have no special talent. I am only passionately curious.",
          author: "Albert Einstein",
        },
        {
          content:
            "The proper use of comments is to compensate for our failure to express ourself in code.",
          author: "Robert C. Martin",
        },
        {
          content:
            "When there is no type hierarchy you don't have to manage the type hierarchy.",
          author: "Rob Pike",
        },
        {
          content:
            "Everybody should learn to program a computer, because it teaches you how to think.",
          author: "Steve Jobs",
        },
        {
          content:
            "Simplicity is hard to build, easy to use, and hard to charge for. Complexity is easy to build, hard to use, and easy to charge for.",
          author: "Chris Sacca",
        },
        {
          content:
            "Measuring programming progress by lines of code is like measuring aircraft building progress by weight.",
          author: "Bill Gates",
        },
        {
          content:
            "More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity.",
          author: "William Wulf",
        },
        {
          content:
            "Testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.",
          author: "Edsger W. Dijkstra",
        },
        {
          content: "Imagination is more important than knowledge.",
          author: "Albert Einstein",
        },
        {
          content:
            "When I am working on a problem I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong.",
          author: "Buckminster Fuller",
        },
        {
          content:
            "Good code is short, simple, and symmetrical - the challenge is figuring out how to get there.",
          author: "Sean Parent",
        },
        {
          content:
            "If you think your users are idiots, only idiots will use it.",
          author: "Linus Torvalds",
        },
        {
          content: "Once you stop learning you start dying.",
          author: "Albert Einstein",
        },
        {
          content: "No code is faster than no code.",
          author: "Kevlin Henney",
        },
        {
          content:
            "Over half of the time you spend working on a project is spent thinking, and no tool, no matter how advanced, can think for you.",
          author: "Richard P. Gabriel",
        },
        {
          content:
            'We could, for instance, begin with cleaning up our language by no longer calling a bug a bug but by calling it an error. It is much more honest because it squarely puts the blame where it belongs, viz. with the programmer who made the error. The animistic metaphor of the bug that maliciously sneaked in while the programmer was not looking is intellectually dishonest as it disguises that the error is the programmer\'s own creation. The nice thing of this simple change of vocabulary is that it has such a profound effect: while, before, a program with only one bug used to be "almost correct", afterwards a program with an error is just "wrong".',
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "Once a new technology starts rolling, if you're not part of the steamroller, you're part of the road.",
          author: "Stewart Brand",
        },
        {
          content:
            "A complex system that works is invariably found to have evolved from a simple system that worked. The inverse proposition also appears to be true: A complex system designed from scratch never works and cannot be made to work.",
          author: "John Gall (author)",
        },
        {
          content:
            "The most amazing achievement of the computer software industry is its continuing cancellation of the steady and staggering gains made by the computer hardware industry.",
          author: "Henry Petroski",
        },
        {
          content:
            "I am never satisfied until I have said as much as possible in a few words, and writing briefly takes far more time than writing at length.",
          author: "Carl Friedrich Gauss",
        },
        {
          content:
            "There are only two kinds of languages: the ones people complain about and the ones nobody uses.",
          author: "Bjarne Stroustrup",
        },
        {
          content:
            "The purpose of software engineering is to control complexity, not to create it.",
          author: "Pamela Zave",
        },
        {
          content:
            "Unix is simple. It just takes a genius to understand its simplicity.",
          author: "Dennis Ritchie",
        },
        {
          content:
            "A language that doesn't have everything is actually easier to program in than some that do.",
          author: "Dennis Ritchie",
        },
        {
          content: "What I cannot build, I do not understand.",
          author: "Richard Feynman",
        },
        {
          content:
            "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius – and a lot of courage – to move in the opposite direction.",
          author: "Albert Einstein",
        },
        {
          content:
            "There is no programming language, no matter how structured, that will prevent programmers from making bad programs.",
          author: "Lawrence Flon",
        },
        {
          content:
            "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
          author: "Martin Fowler",
        },
        {
          content:
            "The problem with object-oriented languages is they've got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.",
          author: "Joe Armstrong (programmer)",
        },
        {
          content:
            "You can't trust code that you did not totally create yourself.",
          author: "Ken Thompson",
        },
        {
          content: "A clever person solves a problem. A wise person avoids it.",
          author: "Albert Einstein",
        },
        {
          content:
            "The most important single aspect of software development is to be clear about what you are trying to build.",
          author: "Bjarne Stroustrup",
        },
        {
          content:
            "The only sin is to make a choice without knowing you are making one.",
          author: "Jonathan Shewchuk",
        },
        {
          content:
            "So much complexity in software comes from trying to make one thing do two things.",
          author: "Ryan Singer",
        },
        {
          content:
            "Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.",
          author: "P. J. Plauger",
        },
        {
          content: "First, solve the problem. Then, write the code.",
          author: "John Johnson",
        },
        {
          content:
            "A good programmer is someone who looks both ways before crossing a one-way street.",
          author: "Doug Linder",
        },
        {
          content:
            "Compatibility means deliberately repeating other people's mistakes.",
          author: "David Wheeler (computer scientist)",
        },
        {
          content:
            "There are two major products that come out of Berkeley: LSD and UNIX. We don't believe this to be a coincidence.",
          author: "Jeremy S. Anderson",
        },
        {
          content:
            "The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague",
          author: "Edsger W. Dijkstra",
        },
        {
          content: "When in doubt, leave it out.",
          author: "Joshua Bloch",
        },
        {
          content:
            "I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.",
          author: "Linus Torvalds",
        },
        {
          content: "Never memorize something that you can look up.",
          author: "Albert Einstein",
        },
        {
          content:
            "Mathematicians stand on each others' shoulders and computer scientists stand on each others' toes.",
          author: "Richard Hamming",
        },
        {
          content:
            "LISP has assisted a number of our most gifted fellow humans in thinking previously impossible thoughts.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "An organisation that treats its programmers as morons will soon have programmers that are willing and able to act like morons only.",
          author: "Bjarne Stroustrup",
        },
        {
          content: "The button is working, only, it cannot be seen.",
          author: "Anonymous",
        },
        {
          content:
            "Don't worry about anything. Just do what you can and be the best you can be.",
          author: "Douglas Crockford",
        },
        {
          content:
            "The business of software building isn't really high-tech at all. It's most of all a business of talking to each other and writing things down.",
          author: "Tom DeMarco",
        },
        {
          content:
            "In programming the hard part isn't solving problems, but deciding what problems to solve.",
          author: "Paul Graham (programmer)",
        },
        {
          content:
            "The manager's function is not to make people work, but to make it possible for people to work.",
          author: "Tom DeMarco",
        },
        {
          content:
            "People under pressure don't work better; they just work faster.",
          author: "Tom DeMarco",
        },
        {
          content:
            "My main conclusion after spending ten years of my life working on the TEX project is that software is hard. It's harder than anything else I've ever had to do.",
          author: "Donald Knuth",
        },
        {
          content:
            "Science is what we understand well enough to explain to a computer. Art is everything else we do.",
          author: "Donald Knuth",
        },
        {
          content:
            "We have seen that computer programming is an art, because it applies accumulated knowledge to the world, because it requires skill and ingenuity, and especially because it produces objects of beauty.",
          author: "Donald Knuth",
        },
        {
          content:
            "Email is a wonderful thing for people whose role in life is to be on top of things. But not for me; my role is to be on the bottom of things. What I do takes long hours of studying and uninterruptible concentration.",
          author: "Donald Knuth",
        },
        {
          content: "Less code equals less bugs.",
          author: "Kevlin Henney",
        },
        {
          content:
            "As soon as an Analytical Engine exists, it will necessarily guide the future course of science.",
          author: "Charles Babbage",
        },
        {
          content:
            "The errors which arise from the absence of facts are far more numerous and more durable than those which result from unsound reasoning respecting true data.",
          author: "Charles Babbage",
        },
        {
          content:
            "We have already mentioned what may, perhaps, appear paradoxical to some of our readers, — that the division of labour can be applied with equal success to mental as to mechanical operations, and that it ensures in both the same economy of time.",
          author: "Charles Babbage",
        },
        {
          content:
            'On two occasions I have been asked [by members of Parliament]: "Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.',
          author: "Charles Babbage",
        },
        {
          content:
            "As long as there were no machines, programming was no problem at all; when we had a few weak computers, programming became a mild problem, and now we have gigantic computers, programming has become an equally gigantic problem.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "If you want more effective programmers, you will discover that they should not waste their time debugging, they should not introduce the bugs to start with.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "A picture may be worth a thousand words, a formula is worth a thousand pictures.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            'I mean, if 10 years from now, when you are doing something quick and dirty, you suddenly visualize that I am looking over your shoulders and say to yourself "Dijkstra would not have liked this", well, that would be enough immortality for me.',
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            'Don\'t blame me for the fact that competent programming will be too difficult for "the average programmer" — you must not fall into the trap of rejecting a surgical technique because it is beyond the capabilities of the barber in his shop around the corner.',
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "Young man, in mathematics you don't understand things. You just get used to them.",
          author: "John von Neumann",
        },
        {
          content: "C is quirky, flawed, and an enormous success.",
          author: "Dennis Ritchie",
        },
        {
          content:
            "It is not the task of the University to offer what society asks for, but to give what society needs.",
          author: "Edsger W. Dijkstra",
        },
        {
          content:
            "By understanding a machine-oriented language, the programmer will tend to use a much more efficient method; it is much closer to reality.",
          author: "Donald Knuth",
        },
        {
          content:
            "Another danger is that commercial pressures of one sort or another will divert the attention of the best thinkers from real innovation to exploitation of the current fad, from prospecting to mining a known lode.",
          author: "Dennis Ritchie",
        },
        {
          content:
            "Within C++, there is a much smaller and cleaner language struggling to get out.",
          author: "Bjarne Stroustrup",
        },
        {
          content:
            "Anybody who comes to you and says he has a perfect language is either naïve or a salesman.",
          author: "Bjarne Stroustrup",
        },
        {
          content:
            "A man provided with paper, pencil, and rubber, and subject to strict discipline, is in effect a universal machine.",
          author: "Alan Turing",
        },
        {
          content:
            "The idea behind digital computers may be explained by saying that these machines are intended to carry out any operations which could be done by a human computer.",
          author: "Alan Turing",
        },
        {
          content: "Machines take me by surprise with great frequency.",
          author: "Alan Turing",
        },
        {
          content:
            'Maybe "just one little global variable" isn\'t too unmanageable, but that style leads to code that is useless except to its original programmer.',
          author: "Bjarne Stroustrup",
        },
        {
          content:
            "I'm doing a free operating system (just a hobby, won't be big and professional like GNU).",
          author: "Linus Torvalds",
        },
        {
          content:
            "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.",
          author: "Linus Torvalds",
        },
        {
          content:
            "An infinite number of monkeys typing into GNU Emacs would never make a good program.",
          author: "Linus Torvalds",
        },
        {
          content:
            "If Microsoft ever does applications for Linux it means I've won.",
          author: "Linus Torvalds",
        },
        {
          content:
            "See, you not only have to be a good coder to create a system like Linux, you have to be a sneaky bastard too ;-)",
          author: "Linus Torvalds",
        },
        {
          content:
            "Really, I'm not out to destroy Microsoft. That will just be a completely unintentional side effect.",
          author: "Linus Torvalds",
        },
        {
          content: "Talk is cheap. Show me the code.",
          author: "Linus Torvalds",
        },
        {
          content:
            "The first 90 percent of the code accounts for the first 90 percent of the development time. The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
          author: "Tom Cargill",
        },
        {
          content:
            "I'm not a great programmer; I'm just a good programmer with great habits.",
          author: "Kent Beck",
        },
        {
          content:
            "There's only one trick in software, and that is using a piece of software that's already been written.",
          author: "Bill Gates",
        },
        {
          content:
            "You can't just ask customers what they want and then try to give that to them. By the time you get it built, they'll want something new.",
          author: "Steve Jobs",
        },
        {
          content:
            "What a computer is to me is it's the most remarkable tool that we have ever come up with. It's the equivalent of a bicycle for our minds.",
          author: "Steve Jobs",
        },
        {
          content:
            "Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You're building your own maze, in a way, and you might just get lost in it.",
          author: "Marijn Haverbeke",
        },
        {
          content:
            "I'm convinced that about half of what separates the successful entrepreneurs from the non-successful ones is pure perseverance. It is so hard.",
          author: "Steve Jobs",
        },
        {
          content:
            "A lot of companies hire people to tell them what to do. We hire people to tell us what to do.",
          author: "Steve Jobs",
        },
        {
          content:
            "Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed.",
          author: "Marijn Haverbeke",
        },
        {
          content:
            "A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands. But without care, a program's size and complexity will grow out of control, confusing even the person who created it.",
          author: "Marijn Haverbeke",
        },
        {
          content:
            "There are many terrible mistakes to make in program design, so go ahead and make them so that you understand them better.",
          author: "Marijn Haverbeke",
        },
        {
          content:
            "People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones.",
          author: "Donald Knuth",
        },
        {
          content:
            "Professionalism has no place in art, and hacking is art. Software Engineering might be science; but that's not what I do. I'm a hacker, not an engineer.",
          author: "Jamie Zawinski",
        },
        {
          content:
            "We who cut mere stones must always be envisioning cathedrals.",
          author: "Quarry worker's creed",
        },
        {
          content:
            "Communication must be stateless in nature, such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server.",
          author: "Roy Fielding",
        },
        {
          content:
            "When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.",
          author: "Kent Beck",
        },
        {
          content:
            "When you find you have to add a feature to a program, and the program's code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.",
          author: "Kent Beck",
        },
        {
          content:
            "It turns out that style matters in programming for the same reason that it matters in writing. It makes for better reading.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Computer programs are the most complex things that humans make.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Most programming languages contain good parts and bad parts. I discovered that I could be better programmer by using only the good parts and avoiding the bad parts.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Good architecture is necessary to give programs enough structure to be able to grow large without collapsing into a puddle of confusion.",
          author: "Douglas Crockford",
        },
        {
          content:
            "JavaScript is the world's most misunderstood programming language.",
          author: "Douglas Crockford",
        },
        {
          content:
            "In JavaScript, there is a beautiful, elegant, highly expressive language that is buried under a steaming pile of good intentions and blunders.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Software is usually expected to be modified over the course of its productive life. The process of converting one correct program into a different correct program is extremely challenging.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Every good work of software starts by scratching a developer's personal itch.",
          author: "Eric S. Raymond",
        },
        {
          content:
            "You can have the project: Done On Time. Done On Budget. Done Properly - Pick two.",
          author: "Anonymous",
        },
        {
          content:
            "No one in the brief history of computing has ever written a piece of perfect software. It's unlikely that you'll be the first.",
          author: "Andy Hunt (author)",
        },
        {
          content: "Never trust a computer you can't throw out a window.",
          author: "Steve Wozniak",
        },
        {
          content: "The best way to predict the future is to invent it.",
          author: "Alan Kay",
        },
        {
          content:
            "If you can get today's work done today, but you do it in such a way that you can't possibly get tomorrow's work done tomorrow, then you lose.",
          author: "Martin Fowler",
        },
        {
          content: "Codes are a puzzle. A game, just like any other game.",
          author: "Alan Turing",
        },
        {
          content:
            "Documentation is a love letter that you write to your future self.",
          author: "Damian Conway",
        },
        {
          content: "Life is too short to run proprietary software.",
          author: "Bdale Garbee",
        },
        {
          content:
            "W​henever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.",
          author: "Martin Fowler",
        },
        {
          content:
            "If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.",
          author: "David Leinweber",
        },
        {
          content:
            "The code you write makes you a programmer. The code you delete makes you a good one. The code you don't have to write makes you a great one.",
          author: "Mario Fusco",
        },
        {
          content: "First do it, then do it right, then do it better.",
          author: "Addy Osmani",
        },
        {
          content:
            "The cost of adding a feature isn't just the time it takes to code it. The cost also includes the addition of an obstacle to future expansion. The trick is to pick the features that don't fight each other.",
          author: "John Carmack",
        },
        {
          content:
            "First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack.",
          author: "George Carrette",
        },
        {
          content:
            "Just because people tell you it can't be done, that doesn't necessarily mean that it can't be done. It just means that they can't do it.",
          author: "Anders Hejlsberg",
        },
        {
          content:
            "The only way to learn a new programming language is by writing programs in it.",
          author: "Dennis Ritchie",
        },
        {
          content:
            "An evolving system increases its complexity unless work is done to reduce it.",
          author: "Manny Lehman (computer scientist)",
        },
        {
          content:
            "No matter how slow you are writing clean code, you will always be slower if you make a mess.",
          author: "Robert C. Martin",
        },
        {
          content:
            "Fancy algorithms are slow when n is small, and n is usually small.",
          author: "Rob Pike",
        },
        {
          content:
            "The only difference between a FA [finite automata] and a TM [Turing machine] is that the TM, unlike the FA, has paper and pencil. Think about it. It tells you something about the power of writing.",
          author: "Manuel Blum",
        },
        {
          content: "Within a computer, natural language is unnatural.",
          author: "Alan Perlis",
        },
        {
          content:
            "Just because you've implemented something doesn't mean you understand it.",
          author: "Brian Cantwell Smith",
        },
        {
          content:
            "That hardly ever happens is another way of saying 'it happens'.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Beware of bugs in the above code; I have only proved it correct, not tried it.",
          author: "Donald Knuth",
        },
        {
          content:
            "A display connected to a digital computer gives us a chance to gain familiarity with concepts not realizable in the physical world. It is a looking glass into a mathematical wonderland.",
          author: "Ivan Sutherland",
        },
        {
          content: "Before software can be reusable it first has to be usable.",
          author: "Ralph Johnson (computer scientist)",
        },
        {
          content:
            "The cheapest, fastest, and most reliable components are those that aren't there.",
          author: "Gordon Bell",
        },
        {
          content:
            "In order to understand recursion, one must first understand recursion.",
          author: "Anonymous",
        },
        {
          content: "The hardest part of design is keeping features out.",
          author: "Don Norman",
        },
        {
          content: "Premature abstraction is as bad as premature optimization.",
          author: "Luciano Ramalho",
        },
        {
          content:
            "Much of the essence of building a program is in fact the debugging of the specification.",
          author: "Fred Brooks",
        },
        {
          content: "Any product that needs a manual to work is broken.",
          author: "Elon Musk",
        },
        {
          content:
            "The act of describing a program in unambiguous detail and the act of programming are one and the same.",
          author: "Kevlin Henney",
        },
        {
          content:
            "I think you should always bear in mind that entropy is not on your side.",
          author: "Elon Musk",
        },
        {
          content:
            "The path to the CEO's office should not be through the CFO's office, and it should not be through the marketing department. It needs to be through engineering and design.",
          author: "Elon Musk",
        },
        {
          content:
            "People are mistaken when they think that technology just automatically improves. It does not automatically improve. It only improves if a lot of people work very hard to make it better, and actually it will, I think, by itself degrade, actually.",
          author: "Elon Musk",
        },
        {
          content: "With artificial intelligence we are summoning the demon.",
          author: "Elon Musk",
        },
        {
          content:
            "AI is a fundamental risk to the existence of human civilization.",
          author: "Elon Musk",
        },
        {
          content:
            "The main activity of programming is not the origination of new independent programs, but in the integration, modification, and explanation of existing ones.",
          author: "Terry Winograd",
        },
        {
          content: "Cool URIs don't change.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "I don't believe in the sort of eureka moment idea. I think it's a myth. I'm very suspicious that actually Archimedes had been thinking about that problem for a long time.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "When I invented the web, I didn't have to ask anyone's permission.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "We need to be super careful with AI. Potentially more dangerous than nukes.",
          author: "Elon Musk",
        },
        {
          content:
            "I invented the Web just because I needed it, really, because it was so frustrating that it didn't exit.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "To be a hacker - when I use the term - is somebody who is creative and does wonderful things.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "The Domain Name Server (DNS) is the Achilles heel of the Web.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "Two centuries ago Leibnitz invented a calculating machine which embodied most of the essential features of recent keyboard devices, but it could not then come into use. The economics of the situation were against it.",
          author: "Vannevar Bush",
        },
        {
          content:
            "Whenever logical processes of thought are employed, there is an opportunity for the machine.",
          author: "Vannevar Bush",
        },
        {
          content:
            "If scientific reasoning were limited to the logical processes of arithmetic, we should not get very far in our understanding of the physical world. One might as well attempt to grasp the game of poker entirely by the use of the mathematics of probability.",
          author: "Vannevar Bush",
        },
        {
          content:
            "Shipping first time code is like going into debt. A little debt speeds development so long as it is paid back promptly with a rewrite. The danger occurs when the debt is not repaid. Every minute spent on not-quite-right code counts as interest on that debt. Entire engineering organizations can be brought to a stand-still under the technical debt load.",
          author: "Ward Cunningham",
        },
        {
          content:
            "Like a financial debt, the technical debt incurs interest payments, which come in the form of the extra effort that we have to do in future development because of the quick and dirty design choice.",
          author: "Martin Fowler",
        },
        {
          content:
            "One of the important implications of technical debt is that it must be serviced. If the debt grows large enough, eventually the company will spend more on servicing its debt than it invests in increasing the value of its other assets.",
          author: "Steve McConnell",
        },
        {
          content:
            "What's very important from my point of view is that there is one web. Anyone that tries to chop it into two will find that their piece looks very boring.",
          author: "Tim Berners-Lee",
        },
        {
          content:
            "Thus it is observable that the buildings which a single architect has planned and executed, are generally more elegant and commodious than those which several have attempted to improve.",
          author: "René Descartes",
        },
        {
          content:
            "Computers are the most complex objects we human beings have ever created, but in a fundamental sense they are remarkably simple.",
          author: "Danny Hillis",
        },
        {
          content:
            "The magic of a computer lies in its ability to become almost anything you can imagine, as long as you can explain exactly what that is.",
          author: "Danny Hillis",
        },
        {
          content:
            "The computer is not just an advanced calculator or camera or paintbrush; rather, it is a device that accelerates and extends our processes of thought.",
          author: "Danny Hillis",
        },
        {
          content:
            "With the right programming, a computer can become a theater, a musical instrument, a reference book, a chess opponent. No other entity in the world except a human being has such an adaptable, universal nature.",
          author: "Danny Hillis",
        },
        {
          content:
            "Anyone who has ever written a program knows that telling a computer what you want it to do is not as easy as it sounds. Every detail of the computer's desired operation must be precisely described. For instance, if you tell an accounting program to bill your clients for the amount that each owes, then the computer will send out a weekly bill for $0.00 to clients who owe nothing.",
          author: "Danny Hillis",
        },
        {
          content:
            "A skilled programmer is like a poet who can put into words those ideas that others find inexpressible.",
          author: "Danny Hillis",
        },
        {
          content:
            "Every computer language has its Shakespeares, and it is a joy to read their code. A well-written computer program possesses style, finesse, even humor—and a clarity that rivals the best prose.",
          author: "Danny Hillis",
        },
        {
          content:
            "It turns out that there is no algorithm for examining a program and determining whether or not it is fatally infected with an endless loop. Moreover, it's not that no one has yet discovered such an algorithm; rather, no such algorithm is possible.",
          author: "Danny Hillis",
        },
        {
          content:
            "The class of problems that are computable by a digital computer apparently includes every problem that is computable by any kind of device.",
          author: "Danny Hillis",
        },
        {
          content:
            "The programs we use to conjure processes are like a sorcerer's spells. They are carefully composed from symbolic expressions in arcane and esoteric programming languages that prescribe the tasks we want our processes to perform.",
          author: "Hal Abelson",
        },
        {
          content:
            "Human beings are not accustomed to being perfect, and few areas of human activity demand it. Adjusting to the requirement for perfection is, I think, the most difficult part of learning to program.",
          author: "Fred Brooks",
        },
        {
          content:
            "Because of optimism, we usually expect the number of bugs to be smaller than it turns out to be. Therefore testing is usually the most mis-scheduled part of programming.",
          author: "Fred Brooks",
        },
        {
          content:
            "One of the greatest joys in computer programming is discovering a new, faster, more efficient algorithm for doing something — particularly if a lot of well-respected people have come up with worse solutions.",
          author: "Danny Hillis",
        },
        {
          content:
            "False scheduling to match the patron's desired date is much more common in our discipline than elsewhere in engineering.",
          author: "Fred Brooks",
        },
        {
          content:
            'The best programmers are up to 28 times better than the worst programmers, according to "individual differences" research. Given that their pay is never commensurate, they are the biggest bargains in the software field.',
          author: "Robert L. Glass",
        },
        {
          content:
            "Sackman, Erickson, and Grant were measuring performance of a group of experienced programmers. Within just this group the ratios between the best and worst performances averaged about 10:1 on productivity measurements and an amazing 5:1 on program speed and space measurements!",
          author: "Fred Brooks",
        },
        {
          content:
            "Conceptual integrity is the most important consideration in system design. It is better to have a system omit certain anomalous features and improvements, but to reflect one set of design ideas, than to have one that contains many good but independent and uncoordinated ideas.",
          author: "Fred Brooks",
        },
        {
          content:
            "The separation of architectural effort from implementation is a very powerful way of getting conceptual integrity on very large projects.",
          author: "Fred Brooks",
        },
        {
          content:
            "The general tendency is to over-design the second system, using all the ideas and frills that were cautiously sidetracked on the first one.",
          author: "Fred Brooks",
        },
        {
          content:
            "The management question, therefore, is not whether to build a pilot system and throw it away. You will do that. The only question is whether to plan in advance to build a throwaway, or to promise to deliver the throwaway to customers.",
          author: "Fred Brooks",
        },
        {
          content:
            "Program building is an entropy-decreasing process, hence inherently metastable. Program maintenance is an entropy-increasing process, and even its most skillful execution only delays the subsidence of the system into unfixable obsolescence.",
          author: "Fred Brooks",
        },
        {
          content:
            "Chemical engineers learned long ago that a process that works in the laboratory cannot be implemented in a factory in only one step.",
          author: "Fred Brooks",
        },
        {
          content:
            "First, we must observe that the anomaly is not that software progress is so slow but that computer hardware progress is so fast. No other technology since civilization began has seen six orders of magnitude price-performance gain in 30 years.",
          author: "Fred Brooks",
        },
        {
          content:
            'Coding is "90 percent finished" for half of the total coding time. Debugging is "99 percent complete" most of the time.',
          author: "Fred Brooks",
        },
        {
          content:
            "The complexity of software is an essential property, not an accidental one. Hence descriptions of a software entity that abstract away its complexity often abstract away its essence.",
          author: "Fred Brooks",
        },
        {
          content:
            "Study after study shows that the very best designers produce structures that are faster, smaller, simpler, cleaner, and produced with less effort. The differences between the great and the average approach an order of magnitude.",
          author: "Fred Brooks",
        },
        {
          content:
            "A programming systems product takes about nine times as much effort as the component programs written separately for private use.",
          author: "Fred Brooks",
        },
        {
          content:
            "My rule of thumb is 1/3 of the schedule for design, 1/6 for coding, 1/4 for component testing, and 1/4 for system testing.",
          author: "Fred Brooks",
        },
        {
          content:
            "First, my wife, my colleagues, and my editors find me to err far more often in optimism than in pessimism. I am, after all, a programmer by background, and optimism is an occupational disease of our craft.",
          author: "Fred Brooks",
        },
        {
          content:
            "Because we are uncertain about our scheduling estimates, we often lack the courage to defend them stubbornly against management and customer pressure.",
          author: "Fred Brooks",
        },
        {
          content:
            "Adding people to a software project increases the total effort necessary in three ways: the work and disruption of repartitioning itself, training the new people, and added intercommunication.",
          author: "Fred Brooks",
        },
        {
          content:
            "Very good professional programmers are ten times as productive as poor ones, at same training and two-year experience level.",
          author: "Fred Brooks",
        },
        {
          content: "Programming increases goes as a power of program size.",
          author: "Fred Brooks",
        },
        {
          content:
            "All repairs tend to destroy structure, to increase the entropy and disorder of a system.",
          author: "Fred Brooks",
        },
        {
          content:
            "To achieve conceptual integrity, a design must proceed from one mind or a small group of agreeing minds.",
          author: "Fred Brooks",
        },
        {
          content:
            "The very best technology never has as much impact as girlfriend or boyfriend trouble.",
          author: "Tom DeMarco",
        },
        {
          content:
            "Maintenance cost is strongly affected by the number of users. More users find more bugs.",
          author: "Fred Brooks",
        },
        {
          content:
            "Most errors are introduced during requirements specification!",
          author: "Daniel T. Barry",
        },
        {
          content:
            "Programming is similar to a game of golf. The point is not getting the ball in the hole but how many strokes it takes.",
          author: "Harlan Mills",
        },
        {
          content:
            "A number of studies have shown testing not very effective at finding bugs.",
          author: "Daniel T. Barry",
        },
        {
          content:
            "The key to keeping software costs down is to write code that is easily modified.",
          author: "Daniel T. Barry",
        },
        {
          content:
            "The notions of correctness in mathematics and programs are different. A mathematical model must be consistent; it need not match reality (be correct), and it need not be complete (in the formal sense). A program model must be consistent; it must match reality; and it must be complete (in the sense that it reacts gracefully to all inputs).",
          author: "Daniel T. Barry",
        },
        {
          content:
            "Programming is at least as difficult as developing a mathematical theory.",
          author: "Daniel T. Barry",
        },
        {
          content:
            "In 1971 when I joined the staff of the MIT Artificial Intelligence lab, all of us who helped develop the operating system software, we called ourselves hackers. We were not breaking any laws, at least not in doing the hacking we were paid to do. We were developing software and we were having fun. Hacking refers to the spirit of fun in which we were developing software.",
          author: "Richard Stallman",
        },
        {
          content:
            "By June 1949 people had begun to realize that it was not so easy to get programs right as at one time appeared.",
          author: "Maurice Wilkes",
        },
        {
          content:
            "Everything should be made as simple as possible. But to do that you have to master complexity.",
          author: "Butler Lampson",
        },
        {
          content:
            "If I had followed my heart instead of advice, dBASE would be much closer to perfection today.",
          author: "Wayne Ratliff",
        },
        {
          content:
            "Programming is a little bit like the army. Now that I'm out, it's neat to have had the experience.",
          author: "Wayne Ratliff",
        },
        {
          content:
            "I don't like using any tools or programs I didn't write myself or that I don't have some control over.",
          author: "Jonathan Sachs",
        },
        {
          content:
            "If you cannot explain a program to yourself, the chance of the computer getting it right is pretty small.",
          author: "Bob Frankston",
        },
        {
          content:
            "I don't comment on the code itself because I feel that properly written code is very much self-documented.",
          author: "Gary Kildall",
        },
        {
          content:
            "When a program is clean and neat, nicely structured, and consistent, it can be beautiful.",
          author: "Gary Kildall",
        },
        {
          content:
            "JavaScript, purely by accident, has become the most popular programming language in the world.",
          author: "Douglas Crockford",
        },
        {
          content:
            "Software is a discipline of detail, and that is a deep, horrendous fundamental problem with software.",
          author: "L. Peter Deutsch",
        },
        {
          content:
            "Even in the games of children there are things to interest the greatest mathematician.",
          author: "Gottfried Wilhelm Leibniz",
        },
      ];
      setQuote(techQuotes[Math.floor(Math.random() * techQuotes.length)]);
    }
  }, [hasActivity, quote]);

  // Toggle tracking on/off
  const toggleTracking = () => {
    const newValue = !isTrackingEnabled;
    setIsTrackingEnabled(newValue);
    if (typeof window !== "undefined") {
      try {
        localStorage.setItem("activityTrackingEnabled", String(newValue));
      } catch (error) {
        // localStorage might be full or disabled
        if (process.env.NODE_ENV === 'development') {
          console.warn('Failed to save tracking preference:', error);
        }
      }
    }
    // Clear data when disabling
    if (!newValue) {
      setData(null);
      setHasActivity(false);
    }
  };

  // Don't render if tracking is disabled and no data
  if (!isTrackingEnabled && !data) {
    return (
      <div className="fixed bottom-4 right-4 md:bottom-6 md:right-6 z-40 font-sans w-[280px] sm:w-[320px] max-w-[calc(100vw-2rem)] pointer-events-none">
        <motion.div
          initial={false}
          animate={{ scale: 1, opacity: 1 }}
          className="pointer-events-auto bg-black/95 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden w-full"
        >
          <div className="px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Activity size={18} className="text-white" />
              <div className="text-left">
                <h3 className="text-sm font-bold text-white">Live Activity</h3>
                <p className="text-[10px] text-white/50">Tracking disabled</p>
              </div>
            </div>
            <button
              type="button"
              onClick={toggleTracking}
              className="text-xs font-semibold px-3 py-1.5 rounded-full bg-white/10 text-white hover:bg-white/15 transition-colors border border-white/10"
              title="Enable activity tracking"
            >
              Enable
            </button>
          </div>
        </motion.div>
      </div>
    );
  }

  // If tracking disabled but we have data, show a disabled state
  if (!isTrackingEnabled && data) {
    return (
      <div className="fixed bottom-4 right-4 md:bottom-6 md:right-6 z-40 font-sans w-[280px] sm:w-[320px] max-w-[calc(100vw-2rem)] pointer-events-none">
        <motion.div
          initial={false}
          animate={{ scale: 1, opacity: 1 }}
          className="pointer-events-auto bg-black/95 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden w-full"
        >
          <div className="px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Activity size={18} className="text-white" />
              <div className="text-left">
                <h3 className="text-sm font-bold text-white">Live Activity</h3>
                <p className="text-[10px] text-white/50">Tracking disabled</p>
              </div>
            </div>
            <button
              type="button"
              onClick={toggleTracking}
              className="text-xs font-semibold px-3 py-1.5 rounded-full bg-white/10 text-white hover:bg-white/15 transition-colors border border-white/10"
              title="Enable activity tracking"
            >
              Enable
            </button>
          </div>
        </motion.div>
      </div>
    );
  }

  // Show loading state if tracking is enabled but no data yet
  // This ensures the component is visible on production even while loading
  if (!data && isTrackingEnabled) {
    return (
      <div className="fixed bottom-4 right-4 md:bottom-6 md:right-6 flex flex-col items-end gap-3 z-40 font-sans pointer-events-none w-[280px] sm:w-[320px] max-w-[calc(100vw-2rem)]">
        <motion.div
          initial={false}
          animate={{ scale: 1, opacity: 1 }}
          className="pointer-events-auto bg-black/95 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden w-full"
        >
          <div className="w-full px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="relative">
                <Activity size={18} className="text-white" />
              </div>
              <div className="text-left">
                <h3 className="text-sm font-bold text-white">Live Activity</h3>
                <p className="text-[10px] text-white/50">Loading...</p>
              </div>
            </div>
            <div className="flex items-center gap-2"></div>
          </div>
        </motion.div>
      </div>
    );
  }

  if (!data) return null;

  const activeCount = [
    data.coding?.isActive,
    data.gaming?.isPlaying,
    data.music?.isPlaying,
  ].filter(Boolean).length;

  // If minimized, show only a small indicator
  if (isMinimized) {
    return (
      <motion.button
        initial={false}
        animate={{ scale: 1 }}
        onClick={() => setIsMinimized(false)}
        className="fixed bottom-4 right-4 md:bottom-6 md:right-6 z-40 pointer-events-auto bg-white/80 backdrop-blur-xl border border-white/60 p-3 rounded-full shadow-xl hover:scale-110 transition-transform"
      >
        <Activity size={20} className="text-stone-900" />
        {activeCount > 0 && (
          <span className="absolute -top-1 -right-1 bg-stone-900 text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center">
            {activeCount}
          </span>
        )}
      </motion.button>
    );
  }

  return (
    <div className="fixed bottom-4 right-4 md:bottom-6 md:right-6 flex flex-col items-end gap-3 z-40 font-sans pointer-events-none w-[280px] sm:w-[320px] max-w-[calc(100vw-2rem)]">
      {/* Main Container */}
      <motion.div
        layout
        className="pointer-events-auto bg-black/95 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl w-full overflow-hidden [&_a]:text-inherit [&_a]:no-underline"
      >
        {/* Header - Always Visible - Changed from button to div to fix nesting error */}
        <div
          role="button"
          tabIndex={0}
          onClick={() => setIsExpanded(!isExpanded)}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              setIsExpanded(!isExpanded);
            }
          }}
          className="w-full px-4 py-3 flex items-center justify-between hover:bg-white/5 transition-colors cursor-pointer"
        >
          <div className="flex items-center gap-3">
            <div className="relative">
              <Activity size={18} className="text-white" />
              {hasActivity && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-green-500 rounded-full animate-pulse" />
              )}
            </div>
            <div className="text-left">
              <h3 className="text-sm font-bold text-white">Live Activity</h3>
              <p className="text-[10px] text-white/50">
                {activeCount > 0 ? `${activeCount} active now` : "No activity"}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div
              onClick={(e) => {
                e.stopPropagation();
                setIsMinimized(true);
              }}
              className="p-1 hover:bg-white/10 rounded-lg transition-colors cursor-pointer"
              role="button"
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.stopPropagation();
                  setIsMinimized(true);
                }
              }}
            >
              <X size={14} className="text-white/60" />
            </div>
            {isExpanded ? (
              <ChevronUp size={18} className="text-white/60" />
            ) : (
              <ChevronDown size={18} className="text-white/60" />
            )}
          </div>
        </div>

        {/* Expandable Content */}
        <AnimatePresence>
          {isExpanded && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: "auto", opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="overflow-hidden"
              style={{ overflow: 'hidden' }}
            >
              <div className="border-t border-white/10 p-3 sm:p-4 space-y-3">
                {/* CODING CARD */}
                {data.coding && (
                  <motion.div
                    layout
                    className={`relative border rounded-xl p-3 transition-all ${
                      data.coding.isActive
                        ? "bg-gradient-to-br from-green-500/10 to-emerald-500/5 border-green-500/30 shadow-lg shadow-green-500/10"
                        : "bg-white/5 border-white/10"
                    }`}
                  >
                    {/* "RIGHT NOW" Indicator */}
                    {data.coding.isActive && (
                      <div className="absolute -top-2 -right-2 bg-green-500 text-black text-[9px] font-black px-2 py-0.5 rounded-full uppercase tracking-wider shadow-lg">
                        Right Now
                      </div>
                    )}

                    <div className="flex items-start gap-3">
                      <div
                        className={`shrink-0 p-2 rounded-lg border flex items-center justify-center ${
                          data.coding.isActive
                            ? "bg-green-500/20 border-green-500/30 text-green-400"
                            : "bg-white/5 border-white/10 text-gray-400"
                        }`}
                      >
                        {data.coding.isActive ? (
                          <Zap size={16} fill="currentColor" />
                        ) : (
                          <Code2 size={16} />
                        )}
                      </div>

                      <div className="flex-1 min-w-0">
                        {data.coding.isActive ? (
                          <>
                            <div className="flex items-center gap-2 mb-1">
                              <span className="relative flex h-2 w-2">
                                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                                <span className="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                              </span>
                              <span className="text-[10px] font-bold text-green-400 uppercase tracking-wider">
                                Coding Live
                              </span>
                            </div>
                            <p className="font-bold text-sm text-white truncate mb-0.5">
                              {data.coding.project || "Active Project"}
                            </p>
                            <p className="text-xs text-white/60 truncate">
                              {data.coding.file || "Writing code..."}
                            </p>
                            {data.coding.language && (
                              <div className="mt-2 inline-flex items-center gap-1 px-2 py-0.5 bg-green-500/10 border border-green-500/20 rounded-full">
                                <span className="text-[10px] font-semibold text-green-400">
                                  {data.coding.language}
                                </span>
                              </div>
                            )}
                          </>
                        ) : (
                          <>
                            <div className="flex items-center gap-1.5 mb-1">
                              <Clock size={10} className="text-gray-400" />
                              <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider">
                                Today&apos;s Coding
                              </span>
                            </div>
                            <p className="font-bold text-sm text-white mb-0.5">
                              {data.coding.stats?.time || "0m"}
                            </p>
                            <p className="text-xs text-white/60">
                              {data.coding.stats?.topLang || "No activity yet"}
                            </p>
                          </>
                        )}
                      </div>
                    </div>
                  </motion.div>
                )}

                {/* GAMING CARD */}
                {data.gaming?.isPlaying && (
                  <motion.div
                    layout
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                    className="relative bg-gradient-to-br from-indigo-500/10 to-purple-500/5 border border-indigo-500/30 rounded-xl p-3 overflow-visible shadow-lg shadow-indigo-500/10"
                  >
                    {/* "RIGHT NOW" Indicator */}
                    <div className="absolute -top-2 -right-2 bg-indigo-500 text-white text-[9px] font-black px-2 py-0.5 rounded-full uppercase tracking-wider shadow-lg z-10 whitespace-nowrap">
                      Right Now
                    </div>

                    {/* Background Glow */}
                    <div className="absolute -right-8 -top-8 w-32 h-32 bg-indigo-500/20 blur-3xl rounded-full pointer-events-none" />

                    <div className="relative flex items-start gap-3">
                      <div className="shrink-0">
                        {data.gaming.image ? (
                          <Image
                            src={data.gaming.image}
                            alt="Game"
                            width={48}
                            height={48}
                            className="w-12 h-12 rounded-lg shadow-md object-cover ring-2 ring-indigo-500/30"
                          />
                        ) : (
                          <div className="w-12 h-12 rounded-lg bg-indigo-500/20 border border-indigo-500/30 flex items-center justify-center">
                            <Gamepad2 className="text-indigo-400" size={20} />
                          </div>
                        )}
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="relative flex h-2 w-2">
                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                            <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
                          </span>
                          <span className="text-[10px] font-bold text-indigo-300 uppercase tracking-wider">
                            Gaming Now
                          </span>
                        </div>
                        <p className="font-bold text-sm text-white truncate mb-0.5">
                          {data.gaming.name}
                        </p>
                        <p className="text-xs text-indigo-200/60 truncate">
                          {data.gaming.details ||
                            data.gaming.state ||
                            "Playing..."}
                        </p>
                      </div>
                    </div>
                  </motion.div>
                )}

                {/* MUSIC CARD */}
                {data.music?.isPlaying && (
                  <motion.div
                    layout
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                  >
                    <a
                      href={data.music.url}
                      target="_blank"
                      rel="noreferrer"
                      className="relative block bg-gradient-to-br from-green-500/10 to-emerald-500/5 border border-green-500/30 rounded-xl p-3 hover:border-green-500/50 transition-all group shadow-lg shadow-green-500/10 no-underline text-inherit"
                    >
                      {/* "RIGHT NOW" Indicator */}
                      <div className="absolute -top-2 -right-2 bg-green-500 text-black text-[9px] font-black px-2 py-0.5 rounded-full uppercase tracking-wider shadow-lg">
                        Right Now
                      </div>

                      <div className="relative flex items-start gap-3">
                        <div className="shrink-0 relative">
                          <Image
                            src={data.music.albumArt}
                            alt="Album"
                            width={48}
                            height={48}
                            className="w-12 h-12 rounded-lg shadow-md group-hover:scale-105 transition-transform ring-2 ring-green-500/30"
                          />
                          <div className="absolute -bottom-1 -right-1 bg-black rounded-full p-1 border border-green-500/30 shadow-lg">
                            <Disc3
                              size={10}
                              className="text-green-400"
                              style={{
                                animation: "spin 3s linear infinite",
                              }}
                            />
                          </div>
                        </div>

                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-[10px] font-bold text-green-400 uppercase tracking-wider">
                              Spotify
                            </span>
                            {/* Equalizer Animation */}
                            <div className="flex gap-[3px] h-3 items-end">
                              {[1, 2, 3].map((i) => (
                                <motion.div
                                  key={i}
                                  className="w-[3px] bg-green-500 rounded-full"
                                  animate={{
                                    height: ["30%", "100%", "50%"],
                                  }}
                                  transition={{
                                    duration: 0.6,
                                    repeat: Infinity,
                                    repeatType: "reverse",
                                    delay: i * 0.12,
                                  }}
                                />
                              ))}
                            </div>
                          </div>
                          <p className="font-bold text-sm text-white truncate mb-0.5 group-hover:text-green-400 transition-colors">
                            {data.music.track}
                          </p>
                          <p className="text-xs text-white/60 truncate">
                            {data.music.artist}
                          </p>
                        </div>
                      </div>
                    </a>
                  </motion.div>
                )}

                {/* Quote of the Day (when idle) */}
                {!hasActivity && quote && (
                  <div className="bg-white/5 rounded-lg p-3 border border-white/10 relative overflow-hidden group hover:bg-white/10 transition-colors">
                    <div className="absolute top-0 right-0 p-2 opacity-10 group-hover:opacity-20 transition-opacity">
                      <Code2 size={40} />
                    </div>
                    <p className="text-[10px] font-bold text-white/40 uppercase tracking-wider mb-2">
                      Quote of the moment
                    </p>
                    <p className="text-sm text-white/90 italic font-serif leading-relaxed">
                      &quot;{quote.content}&quot;
                    </p>
                    <p className="text-xs text-white/50 mt-2 text-right">
                      — {quote.author}
                    </p>
                  </div>
                )}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    </div>
  );
}
