"use client";

import { TUTORIAL_STEPS } from "./TutorialOverlay";

// Catppuccin Latte accents
const CAT = {
  red: "#d20f39",
  teal: "#179299",
  peach: "#fe640b",
  blue: "#1e66f5",
  green: "#40a02b",
  mauve: "#8839ef",
  sapphire: "#209fb5",
  pink: "#ea76cb",
  surface: "#dce0e8",
};

interface HelpPanelProps {
  isOpen: boolean;
  onClose: () => void;
  tutorialStep?: number | null;
  onStartTutorial?: () => void;
  onNextStep?: () => void;
  onPrevStep?: () => void;
  onEndTutorial?: () => void;
}

export function HelpPanel({
  isOpen,
  onClose,
  tutorialStep = null,
  onStartTutorial,
  onNextStep,
  onPrevStep,
  onEndTutorial,
}: HelpPanelProps) {
  const isTutorialActive = tutorialStep !== null;
  const headerText = isTutorialActive ? "Tutorial" : "Welcome to Heartbeads";

  const content = isTutorialActive ? (
    <TutorialContent
      step={tutorialStep}
      onNext={onNextStep!}
      onPrev={onPrevStep!}
      onEnd={onEndTutorial!}
    />
  ) : (
    <HelpContent onStartTutorial={onStartTutorial} />
  );

  return (
    <>
      {/* Desktop: right sidebar — z-[60] during tutorial so it sits above the overlay */}
      <aside
        className={`hidden md:flex absolute top-0 right-0 h-full w-[360px] bg-white dark:bg-zinc-900 border-l border-zinc-200 dark:border-zinc-700 flex-col shadow-xl transform transition-transform duration-300 ease-out ${
          isOpen ? "translate-x-0" : "translate-x-full"
        } ${isTutorialActive ? "z-[60]" : "z-30"}`}
      >
        <div className="flex items-center justify-between px-5 py-3 border-b border-zinc-100 dark:border-zinc-800 shrink-0">
          <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
            {headerText}
          </h2>
          <button
            onClick={onClose}
            className="p-1 text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="flex-1 overflow-y-auto custom-scrollbar">
          {content}
        </div>
      </aside>

      {/* Mobile: bottom drawer */}
      <div
        className={`md:hidden fixed inset-x-0 bottom-0 transform transition-transform duration-300 ease-out ${
          isOpen ? "translate-y-0" : "translate-y-full"
        } ${isTutorialActive ? "z-[60]" : "z-20"}`}
      >
        <div className="bg-white dark:bg-zinc-900 rounded-t-2xl shadow-2xl border-t border-zinc-200 dark:border-zinc-700 max-h-[70vh] flex flex-col">
          <div className="flex items-center justify-between px-5 py-3 border-b border-zinc-100 dark:border-zinc-800 shrink-0">
            <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
              {headerText}
            </h2>
            <button
              onClick={onClose}
              className="p-1 text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          <div className="flex-1 overflow-y-auto custom-scrollbar">
            {content}
          </div>
        </div>
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Tutorial step-by-step content                                      */
/* ------------------------------------------------------------------ */

function TutorialContent({
  step,
  onNext,
  onPrev,
  onEnd,
}: {
  step: number;
  onNext: () => void;
  onPrev: () => void;
  onEnd: () => void;
}) {
  const currentStep = TUTORIAL_STEPS[step];
  const totalSteps = TUTORIAL_STEPS.length;
  const isFirst = step === 0;
  const isLast = step === totalSteps - 1;

  return (
    <div className="px-5 py-4 flex flex-col min-h-[300px]">
      {/* Step indicator */}
      <div className="flex items-center justify-between mb-4">
        <span className="text-xs font-medium" style={{ color: CAT.teal }}>
          {step + 1} / {totalSteps}
        </span>
        <div className="flex gap-1">
          {Array.from({ length: totalSteps }).map((_, i) => (
            <div
              key={i}
              className="w-1.5 h-1.5 rounded-full transition-colors"
              style={{
                backgroundColor:
                  i === step ? CAT.green : i < step ? CAT.teal : CAT.surface,
              }}
            />
          ))}
        </div>
      </div>

      {/* Step title */}
      <h3 className="text-base font-semibold text-zinc-900 dark:text-zinc-100 mb-2">
        {currentStep.title}
      </h3>

      {/* Step description */}
      <p className="text-[13px] text-zinc-600 dark:text-zinc-300 leading-relaxed mb-6">
        {currentStep.description}
      </p>

      {/* Spacer */}
      <div className="flex-1" />

      {/* Navigation */}
      <div className="flex items-center gap-2 pt-4 border-t border-zinc-100 dark:border-zinc-800">
        {isFirst ? (
          <button
            onClick={onEnd}
            className="px-4 py-2 text-sm font-medium text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
          >
            Skip
          </button>
        ) : (
          <button
            onClick={onPrev}
            className="px-4 py-2 text-sm font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
            style={{ color: CAT.blue }}
          >
            {"Back"}
          </button>
        )}
        <div className="flex-1" />
        {isLast ? (
          <button
            onClick={onEnd}
            className="px-4 py-2 text-sm font-medium text-white rounded-lg bg-emerald-500 hover:bg-emerald-600 transition-colors"
          >
            {"Done"}
          </button>
        ) : (
          <button
            onClick={onNext}
            className="px-4 py-2 text-sm font-medium text-white rounded-lg bg-emerald-500 hover:bg-emerald-600 transition-colors"
          >
            {"Next"}
          </button>
        )}
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Bullet with Catppuccin colored dot                                 */
/* ------------------------------------------------------------------ */

function Bullet({ color, children }: { color: string; children: React.ReactNode }) {
  return (
    <li className="flex gap-2.5 items-start">
      <span
        className="w-1.5 h-1.5 rounded-full mt-[6px] shrink-0"
        style={{ backgroundColor: color }}
      />
      <span>{children}</span>
    </li>
  );
}

function SectionTitle({ children, color }: { children: React.ReactNode; color: string }) {
  return (
    <h3
      className="text-[11px] font-semibold uppercase tracking-widest mb-2 mt-5 first:mt-0"
      style={{ color }}
    >
      {children}
    </h3>
  );
}

/* ------------------------------------------------------------------ */
/*  Static help content                                                */
/* ------------------------------------------------------------------ */

function HelpContent({ onStartTutorial }: { onStartTutorial?: () => void }) {
  return (
    <div className="px-5 py-4 text-[13px] text-zinc-600 dark:text-zinc-300 leading-relaxed">
      {/* Start Tutorial */}
      {onStartTutorial && (
        <button
          onClick={onStartTutorial}
          className="w-full flex items-center justify-center gap-2 px-4 py-2.5 mb-5 text-white text-sm font-medium rounded-lg bg-emerald-500 hover:bg-emerald-600 transition-colors"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 18v-5.25m0 0a6.01 6.01 0 001.5-.189m-1.5.189a6.01 6.01 0 01-1.5-.189m3.75 7.478a12.06 12.06 0 01-4.5 0m3.75 2.383a14.406 14.406 0 01-3 0M14.25 18v-.192c0-.983.658-1.823 1.508-2.316a7.5 7.5 0 10-7.517 0c.85.493 1.509 1.333 1.509 2.316V18" />
          </svg>
          Take the guided tour
        </button>
      )}

      <p className="text-zinc-900 dark:text-zinc-100 font-medium mb-1">
        Your command center for AI coding tasks.
      </p>
      <p className="mb-4 text-zinc-500 dark:text-zinc-400">
        Heartbeads shows everything your AI agents are working on as a
        live, interactive graph &mdash; tasks, dependencies, who&apos;s doing what, and
        what&apos;s blocking progress.
      </p>

      <SectionTitle color={CAT.red}>The graph</SectionTitle>
      <p className="mb-2">
        Each <strong>circle</strong> is a task. <strong>Flowing particles</strong>{" "}
        stream between them to show dependency direction.
      </p>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.red}><strong>Bigger circles</strong> &mdash; more connected, more important</Bullet>
        <Bullet color={CAT.red}><strong>Solid lines + particles</strong> &mdash; &ldquo;blocks&rdquo; (A must finish before B)</Bullet>
        <Bullet color={CAT.red}><strong>Dashed lines</strong> &mdash; parent-child grouping</Bullet>
        <Bullet color={CAT.red}><strong>Colored ring</strong> &mdash; which project it belongs to</Bullet>
        <Bullet color={CAT.red}><strong>Avatars</strong> &mdash; small profile pictures on nodes show who claimed or is assigned to that task</Bullet>
        <Bullet color={CAT.red}><strong>Labels</strong> &mdash; tags like &ldquo;mobile&rdquo;, &ldquo;ux&rdquo;, or &ldquo;build&rdquo; shown as pills in node details and hover tooltips</Bullet>
      </ul>

      <SectionTitle color={CAT.blue}>Navigation</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.blue}><strong>Click</strong> a node to open its details</Bullet>
        <Bullet color={CAT.blue}><strong>Hover</strong> for a quick summary</Bullet>
        <Bullet color={CAT.blue}><strong>Right-click</strong> for actions &mdash; descriptions, comments, claims, collapse, or focus on an epic</Bullet>
        <Bullet color={CAT.blue}><strong>Scroll</strong> to zoom, <strong>drag</strong> to pan</Bullet>
      </ul>

      <SectionTitle color={CAT.blue}>Keyboard shortcuts</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.blue}><strong>Cmd/Ctrl+F</strong> &mdash; search by name, ID, owner, or commenter</Bullet>
        <Bullet color={CAT.blue}><strong>Shift+0</strong> &mdash; zoom to the most recently edited node</Bullet>
        <Bullet color={CAT.blue}><strong>Shift+1-9</strong> &mdash; zoom to a node from the #1-#9 leaderboard contributor</Bullet>
        <Bullet color={CAT.blue}><strong>Escape</strong> &mdash; clear search or multi-selection</Bullet>
      </ul>

      <SectionTitle color={CAT.teal}>Layouts</SectionTitle>
      <p className="mb-2">
        Top-left buttons rearrange the graph:
      </p>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.teal}><strong>Force</strong> &mdash; organic, physics-based</Bullet>
        <Bullet color={CAT.teal}><strong>DAG</strong> &mdash; clean top-down tree</Bullet>
        <Bullet color={CAT.teal}><strong>Radial</strong> &mdash; rings from center outward</Bullet>
        <Bullet color={CAT.teal}><strong>Cluster</strong> &mdash; grouped by project</Bullet>
        <Bullet color={CAT.teal}><strong>Spread</strong> &mdash; spaced out for screenshots</Bullet>
      </ul>

      <SectionTitle color={CAT.peach}>Color modes</SectionTitle>
      <p className="mb-2">
        Bottom-right panel &mdash; paint nodes by:
      </p>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.peach}><strong>Status</strong> &mdash; open, in progress, blocked, closed</Bullet>
        <Bullet color={CAT.peach}><strong>Priority</strong> &mdash; P0 critical to P4 backlog</Bullet>
        <Bullet color={CAT.peach}><strong>Type</strong> &mdash; epic, task, bug, feature, or chore</Bullet>
        <Bullet color={CAT.peach}><strong>Owner</strong> &mdash; who created it</Bullet>
        <Bullet color={CAT.peach}><strong>Assignee</strong> &mdash; who&apos;s working on it</Bullet>
        <Bullet color={CAT.peach}><strong>Prefix</strong> &mdash; which project</Bullet>
        <Bullet color={CAT.peach}><strong>Click to filter</strong> &mdash; click any legend label to show only matching nodes. Combine multiple for a union view</Bullet>
      </ul>

      <SectionTitle color={CAT.mauve}>More</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.mauve}><strong>Collapse/Expand</strong> &mdash; tidy up epics into single nodes</Bullet>
        <Bullet color={CAT.mauve}><strong>Focus on epic</strong> &mdash; right-click an epic to isolate its subgraph (children + dependencies). Click the banner or right-click again to return</Bullet>
        <Bullet color={CAT.mauve}><strong>Clusters</strong> &mdash; dashed circles grouping projects when zoomed out</Bullet>
        <Bullet color={CAT.mauve}><strong>Replay</strong> &mdash; step through your project&apos;s history</Bullet>
        <Bullet color={CAT.mauve}><strong>Comments</strong> &mdash; leave notes on tasks (sign in first)</Bullet>
        <Bullet color={CAT.mauve}><strong>Activity feed</strong> &mdash; compact overlay in top-right and full sidebar. Real-time local changes with pagination. During replay, filters to the current point in time</Bullet>
        <Bullet color={CAT.mauve}><strong>Claim tasks</strong> &mdash; right-click to mark as yours</Bullet>
        <Bullet color={CAT.mauve}><strong>Minimap</strong> &mdash; click to jump, drag edges to resize</Bullet>
        <Bullet color={CAT.mauve}><strong>Auto-fit</strong> &mdash; top-left toggle to lock/unlock automatic camera reframing</Bullet>
        <Bullet color={CAT.mauve}><strong>Pulse</strong> &mdash; the most recently active node pulses with emerald ripples. Toggle it on/off in view controls</Bullet>
        <Bullet color={CAT.mauve}><strong>Copy</strong> &mdash; clipboard icon copies task with project info</Bullet>
      </ul>

      <SectionTitle color={CAT.green}>Multi-select</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.green}><strong>Right-click + drag</strong> &mdash; draw a rectangle on the canvas background to select multiple nodes</Bullet>
        <Bullet color={CAT.green}><strong>Shift + click</strong> &mdash; toggle individual nodes into or out of the selection</Bullet>
        <Bullet color={CAT.green}><strong>Group drag</strong> &mdash; drag any selected node to move them all together</Bullet>
        <Bullet color={CAT.green}><strong>Escape</strong> &mdash; clear the selection</Bullet>
      </ul>

      <SectionTitle color={CAT.sapphire}>Leaderboard & Profiles</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.sapphire}><strong>Leaderboard</strong> &mdash; top-right overlay ranking contributors by closed, created, and commented issues. Click &ldquo;See all&rdquo; for the full sidebar</Bullet>
        <Bullet color={CAT.sapphire}><strong>Profiles</strong> &mdash; click any avatar on the graph to open their profile panel with stats and recent activity</Bullet>
        <Bullet color={CAT.sapphire}><strong>Your profile</strong> &mdash; click your handle in the sign-in dropdown to see your own stats</Bullet>
      </ul>

      <SectionTitle color={CAT.pink}>Sharing & Settings</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.pink}><strong>Shareable URLs</strong> &mdash; the current view state is stored in the URL. Copy it to share a specific node, panel, color mode, or filter with anyone</Bullet>
        <Bullet color={CAT.pink}><strong>Text-to-speech</strong> &mdash; open a task description and click the speaker icon to hear it read aloud. Select text for targeted playback. Adjust speed in settings</Bullet>
        <Bullet color={CAT.pink}><strong>Settings</strong> &mdash; gear icon for TTS voice, playback speed, and dashboard access controls</Bullet>
      </ul>

      <SectionTitle color={CAT.mauve}>Appearance</SectionTitle>
      <ul className="space-y-1.5 mb-3">
        <Bullet color={CAT.mauve}><strong>Dark mode</strong> &mdash; click the moon/sun icon in the header to toggle. Your preference is saved to localStorage and persists across sessions</Bullet>
        <Bullet color={CAT.mauve}><strong>System preference</strong> &mdash; on first visit, heartbeads follows your OS dark/light setting automatically</Bullet>
      </ul>

      <div className="mt-5 pt-4 border-t border-zinc-100 dark:border-zinc-800 text-xs text-zinc-400 dark:text-zinc-500">
        Built with{" "}
        <a
          href="https://github.com/GainForest/beads"
          target="_blank"
          rel="noopener noreferrer"
          className="underline underline-offset-2 transition-colors"
          style={{ color: CAT.green }}
        >
          beads
        </a>{" "}
        &mdash; open-source issue tracking for AI-native development. Heartbeads is built for the GainForest agentic workflow and open-sourced at{" "}
        <a
          href="https://github.com/daviddao/heartbeads"
          target="_blank"
          rel="noopener noreferrer"
          className="underline underline-offset-2 transition-colors"
          style={{ color: CAT.green }}
        >
          github.com/daviddao/heartbeads
        </a>.
      </div>
    </div>
  );
}
