// TagWave — Onboarding Tour
// Cursor-guided animated walkthrough — speech bubble style

const TOUR_KEY = "tagwave_tour_seen_v1";

const TOUR_I18N = {
  en: {
    skip: "Don't show again",
    next: "Next →",
    done: "Get started →",
    steps: [
      { title: "Welcome to TagWave", body: "Your DJ library, finally organized. Let's show you around in 30 seconds." },
      { title: "Open your music folder", body: "Drag any folder here. TagWave scans thousands of tracks in seconds." },
      { title: "Everything analyzed automatically", body: "BPM, key, genre, artwork — detected and filled in for every track." },
      { title: "Edit any tag instantly", body: "Click a track to open the inspector. Change anything and save with one click." },
      { title: "Export to your DJ software", body: "Send your library directly to Serato, Rekordbox or Traktor. Ready for the set." },
      { title: "Meet your AI assistant", body: "Ask anything about your library — find tracks by mood, BPM range, or key. The assistant learns how you work." },
    ],
  },
  pt: {
    skip: "Não mostrar novamente",
    next: "Próximo →",
    done: "Começar →",
    steps: [
      { title: "Bem-vindo ao TagWave", body: "Sua biblioteca de DJ, finalmente organizada. Deixa a gente te mostrar em 30 segundos." },
      { title: "Abra sua pasta de músicas", body: "Arraste qualquer pasta aqui. O TagWave escaneia milhares de faixas em segundos." },
      { title: "Tudo analisado automaticamente", body: "BPM, tom, gênero, capa — detectados e preenchidos em cada faixa." },
      { title: "Edite qualquer tag na hora", body: "Clique numa faixa para abrir o inspector. Altere o que quiser e salve com um clique." },
      { title: "Exporte para o seu software DJ", body: "Envie sua biblioteca direto para Serato, Rekordbox ou Traktor. Pronto pro set." },
      { title: "Conheça seu assistente virtual", body: "Pergunte qualquer coisa sobre sua biblioteca — encontre faixas por mood, BPM ou tom. O assistente aprende como você trabalha." },
    ],
  },
  es: {
    skip: "No mostrar de nuevo",
    next: "Siguiente →",
    done: "Empezar →",
    steps: [
      { title: "Bienvenido a TagWave", body: "Tu biblioteca de DJ, por fin organizada. Te la mostramos en 30 segundos." },
      { title: "Abre tu carpeta de música", body: "Arrastra cualquier carpeta aquí. TagWave escanea miles de pistas en segundos." },
      { title: "Todo analizado automáticamente", body: "BPM, tonalidad, género, carátula — detectados y completados en cada pista." },
      { title: "Edita cualquier etiqueta al instante", body: "Haz clic en una pista para abrir el inspector. Cambia lo que quieras y guarda con un clic." },
      { title: "Exporta a tu software DJ", body: "Envía tu biblioteca directamente a Serato, Rekordbox o Traktor. Listo para el set." },
      { title: "Conoce tu asistente virtual", body: "Pregunta cualquier cosa sobre tu biblioteca — encuentra pistas por mood, BPM o tonalidad. El asistente aprende cómo trabajas." },
    ],
  },
};

// Each step: cursor position (% of mock window) + bubble direction
const STEPS_CONFIG = [
  { x: 50, y: 48, bubble: "bottom", highlight: null },        // 0 welcome — center, bubble below
  { x: 14, y: 50, bubble: "right",  highlight: "sidebar" },   // 1 sidebar  — bubble to the right
  { x: 50, y: 42, bubble: "bottom", highlight: "table" },     // 2 table    — bubble below cursor
  { x: 82, y: 42, bubble: "left",   highlight: "inspector" }, // 3 inspector — bubble to the left
  { x: 50, y: 14, bubble: "bottom", highlight: "toolbar" },   // 4 toolbar  — bubble below
  { x: 88, y: 88, bubble: "bottom-right", highlight: "ai" },  // 5 AI — bolha acima, cursor abaixo apontando para cima
];

// Cursor tip is at SVG coords (2,2) — all bubble/tail positioning anchors from there
const TIP_X = 2; // px offset from container left
const TIP_Y = 2; // px offset from container top

// Cursor rotation per bubble direction (tip points toward bubble)
const CURSOR_ROTATION = {
  top:       0,    // tip points up (natural)
  bottom:    180,  // tip flips down
  right:     90,   // tip points right
  left:      -90,  // tip points left
  "top-right": -135,
  "bottom-right": 45,  // tip aponta para cima-esquerda (em direção ao bico da bolha acima)
};

// Bubble tail — accepts optional tailOffset to shift tail horizontally/vertically
function BubbleTail({ dir, color, tailX, tailY }) {
  const size = 9;
  const baseStyles = {
    position: "absolute",
    width: 0, height: 0,
  };

  const styles = {
    "top-right": {
      ...baseStyles,
      bottom: -size,
      right: 12,
      borderLeft: `${size}px solid transparent`,
      borderRight: `${size}px solid transparent`,
      borderTop: `${size}px solid ${color}`,
    },
    "bottom-right": {
      ...baseStyles,
      bottom: -size,
      right: 16,
      borderLeft: `${size}px solid transparent`,
      borderRight: `${size}px solid transparent`,
      borderTop: `${size}px solid ${color}`,
    },
    right: {
      ...baseStyles,
      left: -size,
      top: tailY !== undefined ? tailY : "50%",
      transform: tailY !== undefined ? "none" : "translateY(-50%)",
      borderTop: `${size}px solid transparent`,
      borderBottom: `${size}px solid transparent`,
      borderRight: `${size}px solid ${color}`,
    },
    left: {
      ...baseStyles,
      right: -size,
      top: tailY !== undefined ? tailY : "50%",
      transform: tailY !== undefined ? "none" : "translateY(-50%)",
      borderTop: `${size}px solid transparent`,
      borderBottom: `${size}px solid transparent`,
      borderLeft: `${size}px solid ${color}`,
    },
    bottom: {
      ...baseStyles,
      top: -size,
      left: tailX !== undefined ? tailX : "50%",
      transform: tailX !== undefined ? "none" : "translateX(-50%)",
      borderLeft: `${size}px solid transparent`,
      borderRight: `${size}px solid transparent`,
      borderBottom: `${size}px solid ${color}`,
    },
    top: {
      ...baseStyles,
      bottom: -size,
      left: tailX !== undefined ? tailX : "50%",
      transform: tailX !== undefined ? "none" : "translateX(-50%)",
      borderLeft: `${size}px solid transparent`,
      borderRight: `${size}px solid transparent`,
      borderTop: `${size}px solid ${color}`,
    },
  };
  return <div style={styles[dir] || styles.bottom} />;
}

// Calculate bubble position so tail aligns with cursor tip at (TIP_X, TIP_Y)
// Returns { style, tailX, tailY } — tailX/Y = position of tail within bubble
function getBubbleLayout(dir) {
  const gap = 14; // gap between tip and bubble edge
  const tailSize = 9;
  const bubbleW = 220;

  // We want the tail's apex to land on (TIP_X, TIP_Y) of the container
  switch (dir) {
    case "bottom": {
      // Bubble below, tail points up. Tail apex at container (TIP_X, TIP_Y)
      // bubble.top = TIP_Y + gap
      // tail.left within bubble = TIP_X - bubble.left - tailSize/2 ... approx TIP_X - bubble.left
      const bubbleLeft = TIP_X - 16; // slight left offset so tail is near left edge
      const tailX = TIP_X - bubbleLeft - tailSize / 2;
      return {
        style: { top: TIP_Y + gap, left: bubbleLeft },
        tailX: Math.max(8, tailX),
        tailY: undefined,
        transform: "none",
      };
    }
    case "top": {
      // Bubble above, tail points down. Normal cursor orientation.
      const bubbleLeft = TIP_X - bubbleW / 2;
      return {
        style: { bottom: -(TIP_Y - gap), left: bubbleLeft },
        tailX: bubbleW / 2 - tailSize,
        tailY: undefined,
        transform: "none",
      };
    }
    case "right": {
      // Bubble to the right, tail points left. Cursor rotated 90°.
      const tailY = TIP_Y - tailSize;
      return {
        style: { left: TIP_X + gap, top: TIP_Y - 24 },
        tailX: undefined,
        tailY: Math.max(8, tailY),
        transform: "none",
      };
    }
    case "left": {
      // Bubble to the left, tail points right. Cursor rotated -90°.
      return {
        style: { right: -(TIP_X - gap) + 22, top: TIP_Y - 24 },
        tailX: undefined,
        tailY: Math.max(8, TIP_Y - tailSize),
        transform: "none",
      };
    }
    case "top-right": {
      return {
        style: { bottom: gap, right: 0 },
        tailX: undefined, tailY: undefined,
        transform: "none",
      };
    }
    case "bottom-right": {
      // Bolha acima e à direita, bico aponta para baixo-direita em direção ao cursor
      // Cursor fica abaixo da bolha rotacionado 45° apontando para cima
      return {
        style: { bottom: gap + 22, right: 0 },
        tailX: undefined, tailY: undefined,
        transform: "none",
      };
    }
    default: {
      return {
        style: { top: TIP_Y + gap, left: TIP_X - bubbleW / 2 },
        tailX: bubbleW / 2 - tailSize,
        tailY: undefined,
        transform: "none",
      };
    }
  }
}

function OnboardingTour({ onDone }) {
  const { lang } = useLang();
  const t = TOUR_I18N[lang] || TOUR_I18N.en;

  const [step, setStep] = React.useState(0);
  const [visible, setVisible] = React.useState(true);
  const [bubbleVisible, setBubbleVisible] = React.useState(true);
  const [leaving, setLeaving] = React.useState(false);

  const cfg = STEPS_CONFIG[step];
  const isLast = step === t.steps.length - 1;
  const bubbleLayout = getBubbleLayout(cfg.bubble);
  const cursorRotation = CURSOR_ROTATION[cfg.bubble] || 0;

  const goNext = () => {
    if (isLast) { handleDone(); return; }
    // 1. esconde a bolha
    setBubbleVisible(false);
    // 2. após fade-out (280ms), troca o step — cursor começa a mover
    setTimeout(() => {
      setStep(s => s + 1);
    }, 320);
    // 3. após cursor chegar (transição 1s) + margem, mostra a bolha
    setTimeout(() => {
      setBubbleVisible(true);
    }, 320 + 1000 + 150);
  };

  const handleDone = () => {
    setLeaving(true);
    try { localStorage.setItem(TOUR_KEY, "1"); } catch {}
    setTimeout(() => {
      setVisible(false);
      if (onDone) onDone();
    }, 500);
  };

  if (!visible) return null;

  const bubbleBg = "#D95340";
  const bubbleBorder = "#C4422E";

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 9999,
      background: "rgba(5,4,3,0.88)",
      display: "flex", alignItems: "center", justifyContent: "center",
      flexDirection: "column",
      opacity: leaving ? 0 : 1,
      transition: "opacity 0.5s ease",
      backdropFilter: "blur(8px)",
      WebkitBackdropFilter: "blur(8px)",
    }}>

      {/* Pular / Skip */}
      <button onClick={handleDone} style={{
        position: "absolute", top: 20, right: 24,
        background: "rgba(244,237,228,0.06)",
        border: "1px solid rgba(244,237,228,0.12)",
        borderRadius: 8,
        cursor: "pointer",
        color: "#8F8883", fontSize: 11,
        fontFamily: "'JetBrains Mono', monospace",
        letterSpacing: "0.08em", textTransform: "uppercase",
        transition: "all .2s",
        padding: "8px 16px",
        display: "flex", alignItems: "center", gap: 8,
        zIndex: 10,
      }}
        onMouseEnter={e => { e.currentTarget.style.background = "rgba(244,237,228,0.12)"; e.currentTarget.style.color = "#F5F5F4"; e.currentTarget.style.borderColor = "rgba(244,237,228,0.2)"; }}
        onMouseLeave={e => { e.currentTarget.style.background = "rgba(244,237,228,0.06)"; e.currentTarget.style.color = "#8F8883"; e.currentTarget.style.borderColor = "rgba(244,237,228,0.12)"; }}
      >
        {t.skip}
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M2 2l8 4-8 4V2z" fill="#605A55"/>
          <rect x="9" y="2" width="1.5" height="8" rx="0.75" fill="#605A55"/>
        </svg>
      </button>

      {/* Progress dots */}
      <div style={{ display: "flex", gap: 6, marginBottom: 20 }}>
        {t.steps.map((_, i) => (
          <div key={i} style={{
            width: i === step ? 22 : 6, height: 6, borderRadius: 3,
            background: i === step ? "#D95340" : i < step ? "rgba(217,83,64,0.35)" : "rgba(244,237,228,0.15)",
            transition: "all 0.35s ease",
          }} />
        ))}
      </div>

      {/* App window */}
      <div style={{
        position: "relative",
        width: "min(860px, 90vw)",
        height: "min(480px, 52vw)",
        borderRadius: 14, overflow: "hidden",
        border: "1px solid rgba(244,237,228,0.08)",
        boxShadow: "0 40px 120px -20px rgba(0,0,0,0.8)",
        background: "#0E0D0C",
      }}>

        {/* Toolbar */}
        <div style={{
          height: 36, background: "#23201E",
          borderBottom: "1px solid rgba(244,237,228,0.06)",
          display: "flex", alignItems: "center", padding: "0 10px", gap: 6,
          transition: "background 0.4s",
          boxShadow: cfg.highlight === "toolbar" ? "inset 0 0 0 1px rgba(217,83,64,0.3)" : "none",
        }}>
          {/* Traffic lights */}
          <div style={{ display: "flex", gap: 5, marginRight: 4 }}>
            {["#FF5F57","#FFBD2E","#28C840"].map((c,i) => (
              <div key={i} style={{ width: 11, height: 11, borderRadius: "50%", background: c }} />
            ))}
          </div>
          {/* Logo ring */}
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{ marginRight: 2 }}>
            <circle cx="9" cy="9" r="7.5" stroke="#D95340" strokeWidth="1.5" fill="none"/>
            <circle cx="9" cy="9" r="3.5" stroke="#D95340" strokeWidth="1.2" fill="none"/>
            <line x1="9" y1="1.5" x2="9" y2="5.5" stroke="#D95340" strokeWidth="1.2"/>
            <line x1="9" y1="12.5" x2="9" y2="16.5" stroke="#D95340" strokeWidth="1.2"/>
          </svg>
          {/* Sidebar toggle */}
          <div style={{ width: 26, height: 22, borderRadius: 5, background: "rgba(244,237,228,0.06)", border: "1px solid rgba(244,237,228,0.07)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 2.5, cursor: "pointer" }}>
            {[0,1,2].map(i => <div key={i} style={{ width: 10, height: 1.2, background: "#8F8883", borderRadius: 1 }} />)}
          </div>
          {/* Folder button */}
          <div style={{ height: 22, borderRadius: 5, background: "#D95340", padding: "0 7px", display: "flex", alignItems: "center", gap: 4, cursor: "pointer" }}>
            <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
              <path d="M1 3.5C1 2.95 1.45 2.5 2 2.5H4L5 1.5H8C8.55 1.5 9 1.95 9 2.5V7.5C9 8.05 8.55 8.5 8 8.5H2C1.45 8.5 1 8.05 1 7.5V3.5Z" fill="white"/>
            </svg>
            <span style={{ fontSize: 9, color: "#fff", fontFamily: "'Geist',sans-serif", fontWeight: 600 }}>Abrir</span>
          </div>
          {/* Action chips */}
          <div style={{ flex: 1, display: "flex", gap: 4, alignItems: "center" }}>
            {["Analisar","Corrigir","Exportar"].map((label, i) => (
              <div key={i} style={{ height: 22, borderRadius: 5, background: "rgba(244,237,228,0.05)", border: "1px solid rgba(244,237,228,0.08)", padding: "0 7px", display: "flex", alignItems: "center" }}>
                <span style={{ fontSize: 9, color: "#8F8883", fontFamily: "'Geist',sans-serif" }}>{label}</span>
              </div>
            ))}
          </div>
          {/* Filter chips */}
          <div style={{ display: "flex", gap: 3, alignItems: "center" }}>
            {[["TODAS","#D95340","#D95340"],["+73","#1e1c1a","#605A55"],["★0","#1e1c1a","#605A55"],["⚠4","#1e1c1a","#C4422E"],["✓72","#1e1c1a","#605A55"]].map(([label,bg,color],i) => (
              <div key={i} style={{ height: 19, borderRadius: 4, background: bg, padding: "0 5px", display: "flex", alignItems: "center", border: i>0 ? "1px solid rgba(244,237,228,0.08)" : "none" }}>
                <span style={{ fontSize: 8, color, fontFamily: "'JetBrains Mono',monospace", fontWeight: 600 }}>{label}</span>
              </div>
            ))}
          </div>
          {/* Version */}
          <div style={{ fontSize: 8, color: "#4C4743", fontFamily: "'JetBrains Mono',monospace", marginLeft: 4 }}>v0.4.3</div>
        </div>

        {/* Body */}
        <div style={{ display: "flex", height: "calc(100% - 36px)" }}>

          {/* Sidebar */}
          <div style={{
            width: "17%", borderRight: "1px solid rgba(244,237,228,0.06)",
            background: cfg.highlight === "sidebar" ? "rgba(217,83,64,0.07)" : "#0E0D0C",
            transition: "background 0.4s ease",
            display: "flex", flexDirection: "column",
          }}>
            {/* Tabs */}
            <div style={{ display: "flex", borderBottom: "1px solid rgba(244,237,228,0.06)", flexShrink: 0 }}>
              {["Recentes","Favoritos"].map((tab, i) => (
                <div key={i} style={{
                  flex: 1, height: 26, display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 8, fontFamily: "'Geist',sans-serif", fontWeight: i===0?600:400,
                  color: i===0 ? "#F5F5F4" : "#605A55",
                  borderBottom: i===0 ? "1.5px solid #D95340" : "1.5px solid transparent",
                  marginBottom: -1,
                }}>{tab}</div>
              ))}
            </div>
            {/* Folders */}
            {[["House Sets","#D95340"],["Techno","#8F8883"],["Deep House","#8F8883"],["Drum & Bass","#8F8883"]].map(([name, iconColor], i) => (
              <div key={i} style={{
                padding: "6px 8px", display: "flex", alignItems: "center", gap: 5,
                background: i===0 ? "rgba(217,83,64,0.1)" : "transparent",
                borderBottom: "1px solid rgba(244,237,228,0.03)",
              }}>
                <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{ flexShrink: 0 }}>
                  <path d="M0.5 3.2C0.5 2.65 0.95 2.2 1.5 2.2H3.8L4.5 1.3H8.5C9.05 1.3 9.5 1.75 9.5 2.3V7.3C9.5 7.85 9.05 8.3 8.5 8.3H1.5C0.95 8.3 0.5 7.85 0.5 7.3V3.2Z" fill={iconColor} fillOpacity="0.7"/>
                </svg>
                <span style={{ fontSize: 9, color: i===0 ? "#F5F5F4" : "#8F8883", fontFamily: "'Geist',sans-serif", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</span>
              </div>
            ))}
            {/* Devices */}
            <div style={{ padding: "8px 8px 4px", fontSize: 7, color: "#4C4743", fontFamily: "'JetBrains Mono',monospace", letterSpacing: "0.12em", textTransform: "uppercase" }}>Dispositivos</div>
            {[["Macintosh HD","#8F8883"]].map(([name, color], i) => (
              <div key={i} style={{ padding: "5px 8px", display: "flex", alignItems: "center", gap: 5 }}>
                <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{ flexShrink: 0 }}>
                  <rect x="0.8" y="1.2" width="8.4" height="6" rx="1" stroke={color} strokeWidth="0.9" fill="none"/>
                  <path d="M3.5 7.2V8.5" stroke={color} strokeWidth="0.9"/>
                  <path d="M6.5 7.2V8.5" stroke={color} strokeWidth="0.9"/>
                  <path d="M2 8.5H8" stroke={color} strokeWidth="0.9"/>
                  <circle cx="5" cy="4.2" r="1" fill={color} fillOpacity="0.6"/>
                </svg>
                <span style={{ fontSize: 9, color: "#8F8883", fontFamily: "'Geist',sans-serif" }}>{name}</span>
              </div>
            ))}
          </div>

          {/* Main — track table */}
          <div style={{
            flex: 1, overflow: "hidden", display: "flex", flexDirection: "column",
            background: cfg.highlight === "table" ? "rgba(217,83,64,0.03)" : "transparent",
            transition: "background 0.4s ease",
          }}>
            {/* Áudio/Vídeo sub-tabs */}
            <div style={{ display: "flex", padding: "0 12px", borderBottom: "1px solid rgba(244,237,228,0.06)", height: 28, alignItems: "flex-end", gap: 14, flexShrink: 0 }}>
              {["Áudio","Vídeo"].map((tab, i) => (
                <div key={i} style={{
                  fontSize: 9, fontFamily: "'Geist',sans-serif", fontWeight: i===0?600:400,
                  color: i===0 ? "#F5F5F4" : "#605A55",
                  paddingBottom: 5,
                  borderBottom: i===0 ? "1.5px solid #D95340" : "1.5px solid transparent",
                  cursor: "pointer",
                }}>{tab}</div>
              ))}
            </div>
            {/* Column headers */}
            <div style={{
              display: "grid", gridTemplateColumns: "28px 1fr 52px 40px 44px",
              padding: "0 10px", height: 24,
              borderBottom: "1px solid rgba(244,237,228,0.06)",
              alignItems: "center", flexShrink: 0,
            }}>
              {["","TÍTULO","BPM","TOM","DUR"].map((h, i) => (
                <div key={i} style={{ fontSize: 7.5, color: "#605A55", fontFamily: "'JetBrains Mono',monospace", letterSpacing: "0.1em" }}>{h}</div>
              ))}
            </div>
            {/* Tracks */}
            {[
              { title: "Midnight Geometry", artist: "Helios Drift",  bpm: "128", key: "8A",  dur: "6:42", genre: "DEEP·MELODIC", genreColor: "#4A3A8C", keyColor: "#6B5FC5" },
              { title: "Crimson Hours",      artist: "Sol Rive",      bpm: "126", key: "9A",  dur: "7:04", genre: "HOUSE",       genreColor: "#1E4A3A", keyColor: "#5BA055" },
              { title: "Floor of Glass",     artist: "Voss Project",  bpm: "130", key: "5A",  dur: "6:18", genre: "PROGRESSIVE", genreColor: "#4A2A1A", keyColor: "#C47A40" },
              { title: "Ocean Protocol",     artist: "DJ Espejo",     bpm: "—",   key: "—",   dur: "8:02", genre: "",            genreColor: "", keyColor: "" },
              { title: "Phase Shift",        artist: "Lunar Seq.",    bpm: "—",   key: "—",   dur: "6:11", genre: "",            genreColor: "", keyColor: "" },
            ].map((track, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "28px 1fr 52px 40px 44px",
                padding: "0 10px", height: 32,
                borderBottom: "1px solid rgba(244,237,228,0.03)",
                alignItems: "center",
                background: i===0 ? "rgba(244,237,228,0.04)" : "transparent",
              }}>
                {/* Cover */}
                <div style={{ width: 18, height: 18, borderRadius: 3, background: i<3 ? `linear-gradient(135deg,${["#2a1e40","#1a2e1e","#2e1a0e"][i]},#0e0d0c)` : "rgba(244,237,228,0.04)", border: "1px solid rgba(244,237,228,0.06)" }} />
                <div>
                  <div style={{ fontSize: 9, color: "#F5F5F4", fontWeight: 500, lineHeight: 1.3, display: "flex", alignItems: "center", gap: 4 }}>
                    {track.title}
                    {track.genre && <span style={{ fontSize: 7, padding: "1px 4px", borderRadius: 3, background: track.genreColor, color: "#F5F5F4", fontFamily: "'JetBrains Mono',monospace", opacity: 0.9 }}>{track.genre}</span>}
                  </div>
                  <div style={{ fontSize: 8, color: "#8F8883" }}>{track.artist}</div>
                </div>
                <div style={{ fontSize: 9, color: track.bpm==="—" ? "#4C4743" : "#D95340", fontFamily: "'JetBrains Mono',monospace" }}>{track.bpm}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 3 }}>
                  {track.key !== "—" ? (
                    <div style={{ width: 16, height: 16, borderRadius: 3, background: track.keyColor, display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <span style={{ fontSize: 7, color: "#fff", fontFamily: "'JetBrains Mono',monospace", fontWeight: 700 }}>{track.key}</span>
                    </div>
                  ) : <span style={{ fontSize: 9, color: "#4C4743", fontFamily: "'JetBrains Mono',monospace" }}>—</span>}
                </div>
                <div style={{ fontSize: 8, color: "#8F8883", fontFamily: "'JetBrains Mono',monospace" }}>{track.dur}</div>
              </div>
            ))}
          </div>

          {/* Inspector */}
          <div style={{
            width: "21%", borderLeft: "1px solid rgba(244,237,228,0.06)",
            background: cfg.highlight === "inspector" ? "rgba(217,83,64,0.06)" : "#141210",
            transition: "background 0.4s ease",
            display: "flex", flexDirection: "column",
          }}>
            {/* Tabs */}
            <div style={{ display: "flex", borderBottom: "1px solid rgba(244,237,228,0.06)", flexShrink: 0 }}>
              {["Selecionado","Biblioteca"].map((tab, i) => (
                <div key={i} style={{
                  flex: 1, height: 26, display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 7.5, fontFamily: "'Geist',sans-serif", fontWeight: i===0?600:400,
                  color: i===0 ? "#F5F5F4" : "#605A55",
                  borderBottom: i===0 ? "1.5px solid #D95340" : "1.5px solid transparent",
                  marginBottom: -1,
                }}>{tab}</div>
              ))}
            </div>
            {/* Cover + fields */}
            <div style={{ padding: "8px 10px", display: "flex", flexDirection: "column", gap: 6, flex: 1 }}>
              <div style={{ width: "100%", aspectRatio: "1", borderRadius: 6, background: "linear-gradient(135deg,#2a1e40,#0e0d0c)", border: "1px solid rgba(244,237,228,0.06)", maxHeight: 60 }} />
              {[["TÍTULO","Midnight Geometry"],["ARTISTA","Helios Drift"],["BPM","128"]].map(([label,val],i) => (
                <div key={i}>
                  <div style={{ fontSize: 7, color: "#605A55", letterSpacing: "0.12em", fontFamily: "'JetBrains Mono',monospace", marginBottom: 2 }}>{label}</div>
                  <div style={{ fontSize: 9, color: "#F5F5F4", background: "rgba(244,237,228,0.04)", borderRadius: 4, padding: "3px 6px", border: "1px solid rgba(244,237,228,0.06)" }}>{val}</div>
                </div>
              ))}
              {/* Coverage bars */}
              <div style={{ marginTop: 4 }}>
                <div style={{ fontSize: 7, color: "#605A55", letterSpacing: "0.12em", fontFamily: "'JetBrains Mono',monospace", marginBottom: 5 }}>COBERTURA</div>
                {[["BPM",100],["Tom",87],["Gênero",94],["Capa",72]].map(([label,pct],i) => (
                  <div key={i} style={{ marginBottom: 4 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 2 }}>
                      <span style={{ fontSize: 7.5, color: "#8F8883", fontFamily: "'Geist',sans-serif" }}>{label}</span>
                      <span style={{ fontSize: 7, color: "#605A55", fontFamily: "'JetBrains Mono',monospace" }}>{pct}%</span>
                    </div>
                    <div style={{ height: 3, borderRadius: 2, background: "rgba(244,237,228,0.07)" }}>
                      <div style={{ height: "100%", borderRadius: 2, width: `${pct}%`, background: pct===100 ? "#5BA055" : "#D95340", opacity: 0.85 }} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* AI assistant button — bottom-right (matches real app) */}
        <div style={{
          position: "absolute", bottom: 16, right: 16,
          width: 36, height: 36, borderRadius: "50%",
          background: cfg.highlight === "ai" ? "#D95340" : "#1e1c1a",
          border: `2px solid ${cfg.highlight === "ai" ? "#D95340" : "rgba(217,83,64,0.45)"}`,
          boxShadow: cfg.highlight === "ai" ? "0 0 18px rgba(217,83,64,0.9), 0 0 36px rgba(217,83,64,0.4)" : "none",
          display: "flex", alignItems: "center", justifyContent: "center",
          transition: "all 0.5s ease",
          zIndex: 5,
        }}>
          <div style={{
            width: 16, height: 16, borderRadius: "50%",
            background: cfg.highlight === "ai" ? "#0E0D0C" : "rgba(217,83,64,0.3)",
            transition: "all 0.5s ease",
          }} />
        </div>

        {/* ── ANIMATED CURSOR ── */}
        <div style={{
          position: "absolute",
          left: `${cfg.x}%`,
          top: `${cfg.y}%`,
          transition: "left 1s cubic-bezier(0.4, 0, 0.2, 1), top 1s cubic-bezier(0.4, 0, 0.2, 1)",
          pointerEvents: "none",
          zIndex: 20,
          filter: "drop-shadow(0 2px 10px rgba(217,83,64,0.7))",
        }}>
          {/* SVG cursor — rotates around tip at (2,2) so tip always anchors to bubble tail */}
          <svg
            width="22" height="26" viewBox="0 0 22 26" fill="none"
            style={{
              display: "block",
              position: "relative", zIndex: 40,
              transformOrigin: "2px 2px",
              transform: `rotate(${cursorRotation}deg)`,
              transition: "transform 1s cubic-bezier(0.34, 1.56, 0.64, 1)",
            }}
          >
            <path d="M2 2L2 20L7 15L10 22L13 21L10 14L17 14L2 2Z" fill="white" stroke="#D95340" strokeWidth="1.5" strokeLinejoin="round"/>
          </svg>

          {/* Pulse ring — stays at tip */}
          <div style={{
            position: "absolute", top: -3, left: -3,
            width: 16, height: 16, borderRadius: "50%",
            border: "1.5px solid rgba(217,83,64,0.6)",
            animation: "twPulse 2.4s ease-out infinite",
            pointerEvents: "none",
          }} />

          {/* ── SPEECH BUBBLE ── */}
          <div style={{
            position: "absolute",
            ...bubbleLayout.style,
            width: 220,
            background: bubbleBg,
            border: `1px solid ${bubbleBorder}`,
            borderRadius: 12,
            padding: "14px 16px 12px",
            boxShadow: "0 16px 40px rgba(0,0,0,0.6), 0 0 0 1px rgba(217,83,64,0.1)",
            opacity: bubbleVisible ? 1 : 0,
            transform: bubbleVisible ? "scale(1)" : "scale(0.92)",
            transition: "opacity 0.28s ease, transform 0.28s ease",
            zIndex: 30,
            pointerEvents: "all",
          }}>
            {/* Tail — cor única, sem camada extra que quebra a cor */}
            <BubbleTail dir={cfg.bubble} color={bubbleBg} tailX={bubbleLayout.tailX} tailY={bubbleLayout.tailY} />

            {/* Step label */}
            <div style={{
              fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase",
              color: "rgba(11,9,8,0.5)", fontFamily: "'JetBrains Mono', monospace",
              marginBottom: 6,
            }}>{step + 1} / {t.steps.length}</div>

            {/* Title */}
            <div style={{
              fontSize: 13, fontWeight: 700, color: "#0b0908",
              letterSpacing: "-0.02em", lineHeight: 1.3, marginBottom: 6,
            }}>{t.steps[step].title}</div>

            {/* Body */}
            <p style={{
              margin: "0 0 12px", fontSize: 11.5, color: "rgba(11,9,8,0.72)",
              lineHeight: 1.55,
            }}>{t.steps[step].body}</p>

            {/* Button */}
            <button
              onClick={goNext}
              style={{
                width: "100%", padding: "8px 14px", borderRadius: 8,
                background: "#0b0908", border: "none", cursor: "pointer",
                color: "#F5F5F4", fontSize: 11, fontWeight: 600,
                fontFamily: "'Geist', sans-serif", letterSpacing: "-0.01em",
                display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                transition: "background 0.2s",
              }}
              onMouseEnter={e => e.currentTarget.style.background = "#1c1a18"}
              onMouseLeave={e => e.currentTarget.style.background = "#0b0908"}
            >
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#D95340", flexShrink: 0 }} />
              {isLast ? t.done : t.next}
            </button>
          </div>
        </div>

        {/* Spotlight overlay */}
        {cfg.highlight && (
          <div style={{
            position: "absolute", inset: 0, pointerEvents: "none",
            background: `radial-gradient(ellipse 220px 180px at ${cfg.x}% ${cfg.y}%, transparent 50%, rgba(5,4,3,0.3) 100%)`,
            transition: "all 0.65s ease",
          }} />
        )}
      </div>

      {/* Bottom hint */}
      <p style={{
        marginTop: 20, fontSize: 11, color: "rgba(244,237,228,0.2)",
        fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.08em",
      }}>
        {step + 1} / {t.steps.length}
      </p>

      <style>{`
        @keyframes twPulse {
          0%   { transform: scale(1); opacity: 0.5; }
          100% { transform: scale(2.4); opacity: 0; }
        }
      `}</style>
    </div>
  );
}

function shouldShowTour() {
  try { return !localStorage.getItem(TOUR_KEY); } catch { return false; }
}

Object.assign(window, { OnboardingTour, shouldShowTour });
