import { useState, useEffect, useRef } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { APP_VERSION, RELEASE_NOTES } from '@/lib/version';
import { Sparkles } from 'lucide-react';

const STORAGE_KEY = `bt-release-seen-${APP_VERSION}`;

export function ReleaseNotesDialog() {
  const [open, setOpen] = useState(false);
  const titleRef = useRef(null);

  useEffect(() => {
    const seen = localStorage.getItem(STORAGE_KEY);
    if (!seen) setOpen(true);
  }, []);

  const handleClose = () => {
    localStorage.setItem(STORAGE_KEY, 'true');
    setOpen(false);
    // Return focus to where it was before the dialog opened
    const previouslyFocused = document.activeElement;
    if (previouslyFocused && typeof previouslyFocused.focus === 'function') {
      setTimeout(() => previouslyFocused.focus(), 0);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(o) => { if (!o) handleClose(); }}>
      <DialogContent className="max-w-md" aria-labelledby={titleRef.current?.id}>
        <DialogHeader>
          <div className="flex items-center gap-2 mb-1">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
              <Sparkles className="h-4 w-4 text-primary" />
            </div>
            <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
              What's new in v{RELEASE_NOTES.version}
            </span>
          </div>
          <DialogTitle ref={titleRef} className="text-xl">Bill Tracker is brand new</DialogTitle>
          <DialogDescription className="sr-only">Release notes and new features overview</DialogDescription>
        </DialogHeader>

        <div className="mt-2 space-y-3" role="list" aria-label="Release highlights">
          {RELEASE_NOTES.highlights.map((item, i) => (
            <div key={i} className="flex gap-3 items-start" role="listitem">
              <span className="text-lg leading-none mt-0.5" aria-hidden="true">{item.icon}</span>
              <div>
                <p className="text-sm font-medium text-foreground">{item.title}</p>
                <p className="text-xs text-muted-foreground mt-0.5">{item.desc}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="mt-4 pt-4 border-t border-border flex items-center justify-between">
          <a
            href="/legacy"
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs text-muted-foreground hover:text-foreground transition-colors"
            aria-label="Access original UI"
          >
            Access original UI
          </a>
          <Button size="sm" onClick={handleClose}>
            Get started
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
