'use client';

import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Video,
  BookOpen,
  HelpCircle,
  FileCheck,
  PartyPopper,
  Lock,
  CheckCircle2,
  Play,
  Pause,
  Clock,
  FileText,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  useAdvisorOverview,
  useOrientationOverview,
  useUpdateOrientationProgress,
  useTrainingOverview,
  useUpdateTrainingProgress,
  useCompleteTrainingModule,
  useAssessment,
  useSubmitAssessment,
  useAdvisorAgreement,
  useAcceptAgreement,
} from '../../../services/advisor-lms/queries';
import type {
  OrientationVideoView,
  TrainingModuleView,
  AssessmentQuestion,
} from '../../../services/advisor-lms/api';

type Stage = 'ORIENTATION' | 'TRAINING' | 'MCQ_ASSESSMENT' | 'AGREEMENT' | 'ACTIVATION';

const STAGE_META: { key: Stage; label: string; icon: any }[] = [
  { key: 'ORIENTATION', label: 'Orientation', icon: Video },
  { key: 'TRAINING', label: 'Training', icon: BookOpen },
  { key: 'MCQ_ASSESSMENT', label: 'Assessment', icon: HelpCircle },
  { key: 'AGREEMENT', label: 'Agreement', icon: FileCheck },
  { key: 'ACTIVATION', label: 'Activation', icon: PartyPopper },
];

// The heartbeat cadence for reporting video watch progress back to the server.
const PROGRESS_REPORT_INTERVAL_MS = 10000;

export default function CareerAdvisorOnboardingPage() {
  const { data: overview, isLoading } = useAdvisorOverview();

  const completedKeys = useMemo(
    () => new Set((overview?.stages ?? []).filter((s) => s.complete).map((s) => s.key)),
    [overview],
  );

  // Land on the first incomplete stage by default; let the advisor look back
  // at earlier (completed) stages but not skip ahead to locked ones.
  const firstIncompleteIndex = STAGE_META.findIndex((s) => !completedKeys.has(s.key as any));
  const defaultIndex = firstIncompleteIndex === -1 ? STAGE_META.length - 1 : firstIncompleteIndex;
  const [activeIndex, setActiveIndex] = useState(defaultIndex);

  useEffect(() => {
    // Re-sync the default tab once the overview finishes loading the first time.
    if (overview) setActiveIndex((prev) => (prev === 0 ? defaultIndex : prev));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [!!overview]);

  if (isLoading) {
    return (
      <div className="max-w-4xl mx-auto py-16 flex items-center justify-center gap-2 text-muted-foreground">
        <Loader2 className="h-4 w-4 animate-spin" /> Loading your onboarding status...
      </div>
    );
  }

  const activeStage = STAGE_META[activeIndex]?.key;

  return (
    <div className="max-w-7xl space-y-6 pb-16">
      <div className="border-b border-border/20 pb-4">
        <h1 className="text-sm font-black tracking-widest text-foreground uppercase flex items-center gap-2">
          <Sparkles className="h-4 w-4 text-primary" />
          Career Advisor Onboarding
        </h1>
        <p className="text-[11px] font-medium text-muted-foreground/70">
          Complete every stage in order to activate your advisor account.
        </p>
      </div>

      {/* STEPPER */}
      <div className="grid grid-cols-5 gap-2 bg-surface p-1.5 rounded-xl border border-border/40 shadow-xs">
        {STAGE_META.map((stage, idx) => {
          const Icon = stage.icon;
          const isComplete = completedKeys.has(stage.key as any);
          const isLocked = idx > defaultIndex && !isComplete;
          const isActive = idx === activeIndex;
          return (
            <button
              key={stage.key}
              type="button"
              disabled={isLocked}
              onClick={() => setActiveIndex(idx)}
              className={`flex flex-col items-center justify-center gap-1 py-2 px-2 rounded-lg text-[10px] font-bold transition-all ${
                isActive
                  ? 'bg-primary text-primary-foreground shadow-sm'
                  : isLocked
                  ? 'text-muted-foreground/30 cursor-not-allowed'
                  : 'text-muted-foreground hover:bg-muted/40 hover:text-foreground cursor-pointer'
              }`}
            >
              {isComplete ? <CheckCircle2 className="h-3.5 w-3.5" /> : isLocked ? <Lock className="h-3.5 w-3.5" /> : <Icon className="h-3.5 w-3.5" />}
              <span className="truncate">{stage.label}</span>
            </button>
          );
        })}
      </div>

      <div className="bg-surface border border-border/40 rounded-xl p-5 shadow-sm">
        {activeStage === 'ORIENTATION' && <OrientationStage onAdvance={() => setActiveIndex((i) => Math.min(i + 1, 4))} />}
        {activeStage === 'TRAINING' && <TrainingStage onAdvance={() => setActiveIndex((i) => Math.min(i + 1, 4))} />}
        {activeStage === 'MCQ_ASSESSMENT' && <AssessmentStage onAdvance={() => setActiveIndex((i) => Math.min(i + 1, 4))} />}
        {activeStage === 'AGREEMENT' && <AgreementStage onAdvance={() => setActiveIndex(4)} />}
        {activeStage === 'ACTIVATION' && <ActivationStage isActive={overview?.status === 'ACTIVE'} />}
      </div>
    </div>
  );
}

function Sparkles(props: React.SVGProps<SVGSVGElement>) {
  // small local fallback so this file doesn't need an extra lucide import line above
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} {...props}>
      <path d="M12 3l1.9 4.9L19 9.8l-4.9 1.9L12 17l-1.9-5.3L5 9.8l5.1-1.9L12 3z" />
    </svg>
  );
}

/* ============================================================================
   STAGE 1 — ORIENTATION
============================================================================ */
function OrientationStage({ onAdvance }: { onAdvance: () => void }) {
  const { data, isLoading } = useOrientationOverview();
  const updateProgress = useUpdateOrientationProgress();
  const [openVideoId, setOpenVideoId] = useState<string | null>(null);

  useEffect(() => {
    if (data && !data.isCompleted && !openVideoId) {
      const firstUnlocked = data.videos.find((v) => !v.isLocked && !v.progress?.isCompleted);
      if (firstUnlocked) setOpenVideoId(firstUnlocked.id);
    }
  }, [data, openVideoId]);

  if (isLoading) return <StageLoading />;
  if (!data || data.videos.length === 0) return <EmptyStage label="No orientation videos have been published yet." />;

  if (data.isCompleted) {
    return <StageComplete label="Orientation complete" onAdvance={onAdvance} nextLabel="Continue to Training" />;
  }

  const openVideo = data.videos.find((v) => v.id === openVideoId) ?? null;

  return (
    <div className="space-y-4">
      <StageHeader
        icon={Video}
        title="Stage 1: Orientation"
        subtitle={`${data.completedVideos} of ${data.totalVideos} videos completed. Watch each video to at least 90% to unlock the next.`}
      />

      {openVideo && (
        <VideoPlayerCard
          key={openVideo.id}
          title={openVideo.title}
          url={openVideo.url}
          initialPositionSec={openVideo.progress?.lastPositionSec ?? 0}
          durationSec={openVideo.durationSec}
          onProgress={(watchTimeSec, lastPositionSec, percentageWatched) =>
            updateProgress.mutate({ videoId: openVideo.id, watchTimeSec, lastPositionSec, percentageWatched })
          }
        />
      )}

      <div className="space-y-2">
        {data.videos.map((video) => (
          <VideoListRow
            key={video.id}
            title={video.title}
            durationSec={video.durationSec}
            isLocked={video.isLocked}
            isCompleted={!!video.progress?.isCompleted}
            percentageWatched={video.progress?.percentageWatched ?? 0}
            isOpen={video.id === openVideoId}
            onOpen={() => setOpenVideoId(video.id)}
          />
        ))}
      </div>
    </div>
  );
}

/* ============================================================================
   STAGE 2 — TRAINING
============================================================================ */
function TrainingStage({ onAdvance }: { onAdvance: () => void }) {
  const { data, isLoading } = useTrainingOverview();
  const updateProgress = useUpdateTrainingProgress();
  const completeModule = useCompleteTrainingModule();
  const [openModuleId, setOpenModuleId] = useState<string | null>(null);

  useEffect(() => {
    if (data && !data.isCompleted && !openModuleId) {
      const firstUnlocked = data.modules.find((m) => !m.isLocked && !m.isCompleted);
      if (firstUnlocked) setOpenModuleId(firstUnlocked.id);
    }
  }, [data, openModuleId]);

  if (isLoading) return <StageLoading />;
  if (!data || data.modules.length === 0) return <EmptyStage label="No training modules have been published yet." />;

  if (data.isCompleted) {
    return <StageComplete label="Training complete" onAdvance={onAdvance} nextLabel="Continue to Assessment" />;
  }

  const openModule = data.modules.find((m) => m.id === openModuleId) ?? null;
  const videoWatchedEnough = openModule?.videoAssetId ? !!openModule.videoProgress?.isCompleted : true;

  return (
    <div className="space-y-4">
      <StageHeader
        icon={BookOpen}
        title="Stage 2: Training Modules"
        subtitle={`${data.completedModules} of ${data.totalModules} modules completed.`}
      />

      {openModule && (
        <div className="space-y-3 border border-border/40 rounded-xl p-4 bg-background/50">
          <h3 className="text-xs font-bold text-foreground">{openModule.title}</h3>
          {openModule.description && <p className="text-[11px] text-muted-foreground/80">{openModule.description}</p>}

          {openModule.videoUrl && openModule.videoAssetId && (
            <VideoPlayerCard
              title={openModule.title}
              url={openModule.videoUrl}
              initialPositionSec={openModule.videoProgress?.lastPositionSec ?? 0}
              durationSec={openModule.durationSec}
              onProgress={(watchTimeSec, lastPositionSec, percentageWatched) =>
                updateProgress.mutate({ videoId: openModule.videoAssetId!, watchTimeSec, lastPositionSec, percentageWatched })
              }
            />
          )}

          {openModule.pdfUrl && (
            <a
              href={openModule.pdfUrl}
              target="_blank"
              rel="noreferrer"
              className="flex items-center gap-1.5 text-[11px] font-bold text-primary hover:underline w-fit"
            >
              <FileText className="h-3.5 w-3.5" /> Open study material (PDF)
            </a>
          )}

          <Button
            type="button"
            disabled={!videoWatchedEnough || completeModule.isPending}
            onClick={() => completeModule.mutate(openModule.id)}
            className="h-8 px-4 text-xs font-bold gap-1.5 bg-primary text-primary-foreground hover:bg-primary/90"
          >
            {completeModule.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}
            Mark module complete
          </Button>
          {!videoWatchedEnough && (
            <p className="flex items-center gap-1 text-[10px] text-amber-600">
              <AlertCircle className="h-3 w-3" /> Watch at least 90% of the video before marking this module complete.
            </p>
          )}
        </div>
      )}

      <div className="space-y-2">
        {data.modules.map((module) => (
          <VideoListRow
            key={module.id}
            title={module.title}
            durationSec={module.durationSec}
            isLocked={module.isLocked}
            isCompleted={module.isCompleted}
            percentageWatched={module.videoProgress?.percentageWatched ?? (module.isCompleted ? 100 : 0)}
            isOpen={module.id === openModuleId}
            onOpen={() => setOpenModuleId(module.id)}
          />
        ))}
      </div>
    </div>
  );
}

/* ============================================================================
   STAGE 3 — MCQ ASSESSMENT
============================================================================ */
function AssessmentStage({ onAdvance }: { onAdvance: () => void }) {
  const { data, isLoading, error } = useAssessment();
  const submitAssessment = useSubmitAssessment();
  const [answers, setAnswers] = useState<Record<string, string[]>>({});
  const [remainingSec, setRemainingSec] = useState<number | null>(null);

  useEffect(() => {
    if (data) {
      const elapsedSec = Math.floor((Date.now() - new Date(data.startedAt).getTime()) / 1000);
      setRemainingSec(Math.max(0, data.timerMinutes * 60 - elapsedSec));
    }
  }, [data]);

  useEffect(() => {
    if (remainingSec === null) return;
    if (remainingSec <= 0) {
      handleSubmit();
      return;
    }
    const t = setTimeout(() => setRemainingSec((s) => (s !== null ? s - 1 : s)), 1000);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [remainingSec]);

  if (isLoading) return <StageLoading />;
  if (error) {
    return <EmptyStage label={(error as any)?.response?.data?.message || 'The assessment is not available right now.'} />;
  }
  if (!data) return <EmptyStage label="No assessment is currently available." />;

  const toggleOption = (question: AssessmentQuestion, optionId: string) => {
    setAnswers((prev) => {
      const current = prev[question.id] ?? [];
      if (question.type === 'MULTIPLE_CORRECT') {
        return { ...prev, [question.id]: current.includes(optionId) ? current.filter((id) => id !== optionId) : [...current, optionId] };
      }
      return { ...prev, [question.id]: [optionId] };
    });
  };

  function handleSubmit() {
    const payload = data!.questions.map((q) => ({ questionId: q.id, selectedOptionIds: answers[q.id] ?? [] }));
    submitAssessment.mutate(payload, { onSuccess: (result) => result.passed && onAdvance() });
  }

  const answeredCount = Object.values(answers).filter((a) => a.length > 0).length;
  const minutes = remainingSec !== null ? Math.floor(remainingSec / 60) : 0;
  const seconds = remainingSec !== null ? remainingSec % 60 : 0;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <StageHeader icon={HelpCircle} title="Stage 3: Assessment" subtitle={`${answeredCount} of ${data.questions.length} answered.`} />
        {remainingSec !== null && (
          <span className={`flex items-center gap-1.5 text-xs font-mono font-bold px-3 py-1.5 rounded-lg border ${remainingSec < 60 ? 'text-destructive border-destructive/30 bg-destructive/10' : 'text-foreground border-border/40 bg-background'}`}>
            <Clock className="h-3.5 w-3.5" /> {minutes}:{seconds.toString().padStart(2, '0')}
          </span>
        )}
      </div>

      <div className="space-y-4">
        {data.questions.map((question, idx) => (
          <div key={question.id} className="border border-border/40 rounded-xl p-4 bg-background/50 space-y-2.5">
            <p className="text-xs font-bold text-foreground">
              <span className="text-primary mr-1.5">Q{idx + 1}.</span>
              {question.questionText}
            </p>
            <div className="space-y-1.5">
              {question.options.map((option) => {
                const selected = (answers[question.id] ?? []).includes(option.id);
                return (
                  <label
                    key={option.id}
                    className={`flex items-center gap-2.5 p-2 rounded-lg border text-xs font-medium cursor-pointer transition-all ${
                      selected ? 'bg-primary/5 border-primary/40 text-foreground' : 'bg-background border-border/30 text-muted-foreground hover:text-foreground'
                    }`}
                  >
                    <input
                      type={question.type === 'MULTIPLE_CORRECT' ? 'checkbox' : 'radio'}
                      name={question.id}
                      checked={selected}
                      onChange={() => toggleOption(question, option.id)}
                      className="h-3.5 w-3.5"
                    />
                    {option.optionText}
                  </label>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      <div className="flex justify-end">
        <Button
          type="button"
          disabled={submitAssessment.isPending}
          onClick={handleSubmit}
          className="h-9 px-6 rounded-lg text-xs font-bold gap-1.5 bg-primary text-primary-foreground hover:bg-primary/90"
        >
          {submitAssessment.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle2 className="h-4 w-4" />}
          Submit Assessment
        </Button>
      </div>
    </div>
  );
}

/* ============================================================================
   STAGE 4 — AGREEMENT
============================================================================ */
function AgreementStage({ onAdvance }: { onAdvance: () => void }) {
  const { data, isLoading } = useAdvisorAgreement();
  const acceptAgreement = useAcceptAgreement();
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [acceptedPrivacy, setAcceptedPrivacy] = useState(false);
  const [acceptedCodeOfConduct, setAcceptedCodeOfConduct] = useState(false);

  if (isLoading) return <StageLoading />;
  if (!data) return <EmptyStage label="No agreement is currently available to sign." />;

  if (data.signature) {
    return <StageComplete label="Agreement signed" onAdvance={onAdvance} nextLabel="Continue" />;
  }

  const allAccepted = acceptedTerms && acceptedPrivacy && acceptedCodeOfConduct;

  return (
    <div className="space-y-4">
      <StageHeader icon={FileCheck} title="Stage 4: Digital Agreement" subtitle={`Version ${data.agreement.version}`} />

      <div className="border border-border/40 rounded-xl p-4 bg-background/50 max-h-72 overflow-y-auto">
        <h3 className="text-xs font-bold text-foreground mb-2">{data.agreement.title}</h3>
        <div className="text-[11px] text-muted-foreground/90 leading-relaxed" dangerouslySetInnerHTML={{ __html: data.agreement.bodyHtml }} />
      </div>

      <div className="space-y-2">
        <AgreementCheckbox
          checked={acceptedTerms}
          onChange={setAcceptedTerms}
          label="I have read and accept the Terms of Engagement"
          linkUrl={data.agreement.termsUrl}
        />
        <AgreementCheckbox
          checked={acceptedPrivacy}
          onChange={setAcceptedPrivacy}
          label="I have read and accept the Privacy Policy"
          linkUrl={data.agreement.privacyPolicyUrl}
        />
        <AgreementCheckbox
          checked={acceptedCodeOfConduct}
          onChange={setAcceptedCodeOfConduct}
          label="I have read and accept the Code of Conduct"
          linkUrl={data.agreement.codeOfConductUrl}
        />
      </div>

      <div className="flex justify-end">
        <Button
          type="button"
          disabled={!allAccepted || acceptAgreement.isPending}
          onClick={() =>
            acceptAgreement.mutate(
              { agreementId: data.agreement.id, acceptedTerms: true, acceptedPrivacy: true, acceptedCodeOfConduct: true, method: 'DIGITAL_SIGNATURE' },
              { onSuccess: onAdvance },
            )
          }
          className="h-9 px-6 rounded-lg text-xs font-bold gap-1.5 bg-primary text-primary-foreground hover:bg-primary/90"
        >
          {acceptAgreement.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileCheck className="h-4 w-4" />}
          Accept & Sign
        </Button>
      </div>
    </div>
  );
}

function AgreementCheckbox({ checked, onChange, label, linkUrl }: { checked: boolean; onChange: (v: boolean) => void; label: string; linkUrl?: string | null }) {
  return (
    <label className="flex items-center gap-2.5 text-xs font-medium text-foreground cursor-pointer">
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} className="h-4 w-4 rounded border-border/40 text-primary" />
      {label}
      {linkUrl && (
        <a href={linkUrl} target="_blank" rel="noreferrer" className="text-primary hover:underline text-[10px] font-bold">
          (view)
        </a>
      )}
    </label>
  );
}

/* ============================================================================
   STAGE 5 — ACTIVATION
============================================================================ */
function ActivationStage({ isActive }: { isActive?: boolean }) {
  return (
    <div className="py-10 flex flex-col items-center text-center gap-3">
      <div className="h-14 w-14 rounded-full bg-emerald-500/10 flex items-center justify-center">
        <PartyPopper className="h-7 w-7 text-emerald-500" />
      </div>
      <h2 className="text-sm font-black text-foreground uppercase tracking-wide">
        {isActive ? "You're activated!" : 'Almost there'}
      </h2>
      <p className="text-xs text-muted-foreground/80 max-w-sm">
        {isActive
          ? 'Your Career Advisor account is now active. You can start counselling and enrolling students right away.'
          : 'Finish the remaining stages above and your account will activate automatically.'}
      </p>
    </div>
  );
}

/* ============================================================================
   SHARED PIECES
============================================================================ */
function StageHeader({ icon: Icon, title, subtitle }: { icon: any; title: string; subtitle: string }) {
  return (
    <div className="flex items-center gap-2 border-b border-border/10 pb-2">
      <Icon className="h-4 w-4 text-primary" />
      <div>
        <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">{title}</h2>
        <p className="text-[10px] text-muted-foreground/70">{subtitle}</p>
      </div>
    </div>
  );
}

function StageLoading() {
  return (
    <div className="py-10 flex items-center justify-center gap-2 text-xs text-muted-foreground">
      <Loader2 className="h-4 w-4 animate-spin" /> Loading...
    </div>
  );
}

function EmptyStage({ label }: { label: string }) {
  return (
    <div className="py-10 flex flex-col items-center gap-2 text-center">
      <AlertCircle className="h-5 w-5 text-muted-foreground/40" />
      <p className="text-xs font-bold text-muted-foreground">{label}</p>
    </div>
  );
}

function StageComplete({ label, onAdvance, nextLabel }: { label: string; onAdvance: () => void; nextLabel: string }) {
  return (
    <div className="py-8 flex flex-col items-center gap-3 text-center">
      <CheckCircle2 className="h-8 w-8 text-emerald-500" />
      <p className="text-xs font-bold text-foreground">{label}</p>
      <Button type="button" onClick={onAdvance} className="h-8 px-4 text-xs font-bold bg-primary text-primary-foreground hover:bg-primary/90">
        {nextLabel}
      </Button>
    </div>
  );
}

function VideoListRow({
  title,
  durationSec,
  isLocked,
  isCompleted,
  percentageWatched,
  isOpen,
  onOpen,
}: {
  title: string;
  durationSec: number;
  isLocked: boolean;
  isCompleted: boolean;
  percentageWatched: number;
  isOpen: boolean;
  onOpen: () => void;
}) {
  return (
    <button
      type="button"
      disabled={isLocked}
      onClick={onOpen}
      className={`w-full flex items-center justify-between gap-3 p-3 rounded-xl border text-left transition-all ${
        isOpen ? 'border-primary/40 bg-primary/5' : 'border-border/30 bg-background/40'
      } ${isLocked ? 'opacity-50 cursor-not-allowed' : 'hover:border-border/60 cursor-pointer'}`}
    >
      <div className="flex items-center gap-3 min-w-0">
        {isCompleted ? (
          <CheckCircle2 className="h-4 w-4 text-emerald-500 shrink-0" />
        ) : isLocked ? (
          <Lock className="h-4 w-4 text-muted-foreground/40 shrink-0" />
        ) : (
          <Play className="h-4 w-4 text-primary shrink-0" />
        )}
        <span className="text-xs font-bold text-foreground truncate">{title}</span>
      </div>
      <div className="flex items-center gap-2 shrink-0">
        {!isCompleted && !isLocked && percentageWatched > 0 && (
          <span className="text-[10px] font-mono text-muted-foreground">{Math.round(percentageWatched)}%</span>
        )}
        <span className="text-[10px] font-mono text-muted-foreground flex items-center gap-1">
          <Clock className="h-3 w-3" /> {Math.round(durationSec / 60)}m
        </span>
      </div>
    </button>
  );
}

/**
 * HTML5 video player that reports watch progress on a heartbeat. Reports
 * the max watch position/percentage reached, throttled to
 * PROGRESS_REPORT_INTERVAL_MS, plus a final report on pause/unmount so a
 * quick skim right up to closing the tab still gets credited.
 */
function VideoPlayerCard({
  title,
  url,
  durationSec,
  initialPositionSec,
  onProgress,
}: {
  title: string;
  url: string;
  durationSec: number;
  initialPositionSec: number;
  onProgress: (watchTimeSec: number, lastPositionSec: number, percentageWatched: number) => void;
}) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const watchTimeRef = useRef(0);
  const lastReportRef = useRef(0);
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    const video = videoRef.current;
    if (video && initialPositionSec > 0) {
      video.currentTime = initialPositionSec;
    }
  }, [initialPositionSec]);

  const report = () => {
    const video = videoRef.current;
    if (!video) return;
    const currentTime = Math.floor(video.currentTime);
    const total = video.duration || durationSec || 1;
    const percentageWatched = Math.min(100, (currentTime / total) * 100);
    onProgress(watchTimeRef.current, currentTime, percentageWatched);
  };

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      watchTimeRef.current += 0.25; // ~4 timeupdate events/sec in most browsers
      const now = Date.now();
      if (now - lastReportRef.current > PROGRESS_REPORT_INTERVAL_MS) {
        lastReportRef.current = now;
        report();
      }
    };
    const handlePause = () => report();
    const handleEnded = () => report();
    const handlePlay = () => setIsPlaying(true);
    const handleStop = () => setIsPlaying(false);

    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('pause', handlePause);
    video.addEventListener('ended', handleEnded);
    video.addEventListener('play', handlePlay);
    video.addEventListener('pause', handleStop);

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('pause', handlePause);
      video.removeEventListener('ended', handleEnded);
      video.removeEventListener('play', handlePlay);
      video.removeEventListener('pause', handleStop);
      report(); // final report on unmount (e.g. switching to another video)
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url]);

  return (
    <div className="rounded-xl overflow-hidden border border-border/40 bg-black">
      <video ref={videoRef} src={url} controls className="w-full max-h-96 bg-black" />
      <div className="flex items-center gap-2 px-3 py-2 bg-surface text-[10px] font-bold text-muted-foreground">
        {isPlaying ? <Pause className="h-3 w-3" /> : <Play className="h-3 w-3" />}
        {title}
      </div>
    </div>
  );
}