// Tutorial.jsx — first-session onboarding, replay-able from Profile.
// 5 steps walking through Welcome → Setlist → Search → Modal → Status.
// Reuses LavidMark, lvRise, hlfadeUp, hldrift, lvHaloPulse keyframes.
// Persistence flag: localStorage 'lavid:tutorialSeen' (set by parent on done/skip).

const TUT_EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';

// ─── Mini reusable bits for hero zones ───────────────────────────────────

function HymnalMiniRow({ idx, name, artist, status, last }) {
  const dotColor = status === 'pub' ? '#F5C56B' : status === 'send' ? '#FBBF24' : '#E8DCC4';
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '20px 1fr auto', gap: 10,
      padding: '8px 4px', alignItems: 'center',
      borderBottom: last ? 'none' : '1px solid rgba(232,220,196,0.08)',
    }}>
      <span style={{
        fontFamily: 'var(--hl-font-display)', fontStyle: 'italic', fontSize: 14,
        color: 'rgba(232,220,196,0.6)', textAlign: 'center',
      }}>{idx + 1}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontSize: 13, color: '#fff', fontWeight: 500,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{name}</div>
        <div style={{
          fontSize: 10, color: 'rgba(232,220,196,0.5)',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{artist}</div>
      </div>
      <div style={{
        width: 7, height: 7, borderRadius: '50%', background: dotColor,
        boxShadow: `0 0 10px ${dotColor}88`,
        animation: status === 'send' ? 'hlbreathe 1.2s ease-in-out infinite' : undefined,
      }} />
    </div>
  );
}

// ─── Hero components per step ─────────────────────────────────────────────

function HeroWelcome() {
  return (
    <div style={{
      position: 'relative', width: 280, height: 280,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {/* breathing aura */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        width: 260, height: 260, borderRadius: '50%',
        transform: 'translate(-50%, -50%)',
        background: 'radial-gradient(circle, rgba(192,132,252,0.45), transparent 60%)',
        filter: 'blur(50px)',
        animation: 'lvHalo 4.2s ease-in-out infinite',
      }} />

      {/* concentric rings — three breathing layers, staggered */}
      {[1, 2, 3].map(i => (
        <div key={i} style={{
          position: 'absolute', top: '50%', left: '50%',
          width: 130 + i * 50, height: 130 + i * 50, borderRadius: '50%',
          transform: 'translate(-50%, -50%)',
          border: `1px solid rgba(221, 214, 254, ${0.28 - i * 0.06})`,
          animation: `hlbreathe ${3.4 + i * 0.5}s ease-in-out infinite`,
          animationDelay: `${i * 0.25}s`,
        }} />
      ))}

      {/* sparkle particles */}
      {[
        { x: '15%', y: '18%', d: 0 },
        { x: '82%', y: '20%', d: 0.4 },
        { x: '88%', y: '70%', d: 0.8 },
        { x: '10%', y: '75%', d: 1.2 },
        { x: '50%', y: '8%',  d: 1.6 },
      ].map((p, i) => (
        <div key={i} style={{
          position: 'absolute', left: p.x, top: p.y,
          width: 4, height: 4, borderRadius: '50%',
          background: 'white', boxShadow: '0 0 12px rgba(255,255,255,0.9)',
          animation: 'hlsparkle 2.4s ease-in-out infinite',
          animationDelay: `${p.d}s`,
        }} />
      ))}

      {/* the mark itself with the splash glow */}
      <div style={{
        position: 'relative', zIndex: 2,
        filter: 'drop-shadow(0 0 22px rgba(221,214,254,0.85)) drop-shadow(0 0 60px rgba(168,85,247,0.55))',
      }}>
        {typeof LavidMark === 'function'
          ? <LavidMark size={130} animated strokeWidth={45} />
          : null}
      </div>
    </div>
  );
}

function HeroSetlist() {
  return (
    <div style={{
      width: 250, padding: 14,
      background: 'rgba(255,255,255,0.035)',
      border: '1px solid rgba(232,220,196,0.1)',
      borderRadius: 14,
      boxShadow: '0 12px 30px rgba(0,0,0,0.3)',
    }}>
      <div style={{
        fontFamily: 'var(--hl-font-mono)', fontSize: 8, color: 'rgba(232,220,196,0.5)',
        letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 6,
      }}>Adoración</div>
      <div style={{ borderTop: '1px solid rgba(232,220,196,0.1)' }}>
        <HymnalMiniRow idx={0} name="Reckless Love" artist="Cory Asbury" status="pub" />
        <HymnalMiniRow idx={1} name="Océanos" artist="Hillsong UNITED" status="pub" />
        <HymnalMiniRow idx={2} name="Que se Abra el Cielo" artist="Casa Worship" status="send" last />
      </div>
    </div>
  );
}

function HeroSearch() {
  return (
    <div style={{ width: 250, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{
        height: 38, borderRadius: 11,
        background: 'rgba(255,255,255,0.05)',
        border: '1px solid rgba(192,132,252,0.45)',
        boxShadow: '0 0 0 4px rgba(168,85,247,0.1), 0 8px 20px rgba(168,85,247,0.15)',
        display: 'flex', alignItems: 'center', padding: '0 12px', gap: 8,
        fontSize: 12, fontFamily: 'var(--hl-font-ui)',
      }}>
        <svg width="12" height="12" viewBox="0 0 16 16" fill="none">
          <circle cx="7" cy="7" r="5" stroke="rgba(192,132,252,0.85)" strokeWidth="1.6"/>
          <path d="M11 11l3 3" stroke="rgba(192,132,252,0.85)" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
        <span style={{ color: '#fff', fontWeight: 500 }}>tu mirada</span>
        <span style={{
          marginLeft: 'auto', width: 10, height: 10, borderRadius: '50%',
          border: '1.5px solid rgba(255,255,255,0.2)',
          borderTopColor: 'var(--vesper-glow)',
          animation: 'hlspin 0.8s linear infinite',
        }} />
      </div>
      {[
        { name: 'Tu mirada', artist: 'Marcos Witt', genre: 'Gospel/Religioso', delay: 0.18 },
        { name: 'Tu Mirada', artist: 'Evan Craft', genre: null, delay: 0.32 },
        { name: 'Tú Mirada', artist: 'Reik', genre: 'Pop', delay: 0.46 },
      ].map((r, i) => (
        <div key={i} style={{
          padding: '9px 12px', borderRadius: 11,
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.06)',
          animation: `hlfadeUp 0.45s ${TUT_EASE} ${r.delay}s both`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{
              color: '#fff', fontWeight: 500, fontSize: 12,
              fontFamily: 'var(--hl-font-ui)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{r.name}</div>
            <div style={{
              color: 'rgba(232,220,196,0.55)', fontSize: 10, marginTop: 1,
            }}>{r.artist}{r.genre ? ` · ${r.genre}` : ''}</div>
          </div>
          <span style={{
            fontSize: 8, color: 'var(--vesper-glow)',
            fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.5,
            padding: '2px 6px', borderRadius: 4, background: 'rgba(168,85,247,0.15)',
          }}>cifraclub</span>
        </div>
      ))}
    </div>
  );
}

function HeroModal() {
  return (
    <div style={{
      width: 250, padding: 14,
      background: 'linear-gradient(180deg, #150A30, #0A0520)',
      borderRadius: 18,
      border: '1px solid rgba(232,220,196,0.08)',
      boxShadow: '0 18px 40px rgba(0,0,0,0.55)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 8 }}>
        <div style={{ width: 28, height: 3, borderRadius: 2, background: 'rgba(232,220,196,0.22)' }} />
      </div>
      <div style={{
        fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
        fontSize: 16, color: '#fff', fontWeight: 400, marginBottom: 4,
      }}>Tu Mirada</div>
      <div style={{
        fontSize: 10, color: 'rgba(232,220,196,0.55)', marginBottom: 12,
        fontFamily: 'var(--hl-font-mono)',
      }}>Marcos Witt · Tono G</div>
      <div style={{
        display: 'flex', gap: 3, padding: 3, borderRadius: 10,
        background: 'rgba(255,255,255,0.05)',
        border: '1px solid rgba(255,255,255,0.06)',
      }}>
        {['Letra', 'Letra + Acordes', 'Solo'].map((label, i) => (
          <div key={i} style={{
            flex: 1, padding: '6px 4px', borderRadius: 7,
            background: i === 1 ? 'linear-gradient(135deg, #B45EFF, #4F1FCB)' : 'transparent',
            color: i === 1 ? '#fff' : 'rgba(232,220,196,0.5)',
            fontSize: 9, fontWeight: 600, textAlign: 'center',
            fontFamily: 'var(--hl-font-ui)',
            boxShadow: i === 1 ? '0 4px 12px rgba(168,85,247,0.5), inset 0 1px 0 rgba(255,255,255,0.25)' : 'none',
          }}>{label}</div>
        ))}
      </div>
      <div style={{
        marginTop: 14, fontFamily: 'var(--hl-font-mono)', fontSize: 9.5,
        color: 'rgba(232,220,196,0.75)', lineHeight: 1.7,
      }}>
        <div style={{ color: 'var(--vesper-glow)' }}>G                     Em7</div>
        <div>Tus ojos revelan que yo nada</div>
        <div style={{ color: 'var(--vesper-glow)', marginTop: 4 }}>      C7M           C/D</div>
        <div>puedo esconder, oh fiel Señor</div>
      </div>
    </div>
  );
}

function HeroStatus() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 28 }}>
      <div style={{ position: 'relative', width: 110, height: 110, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{
          position: 'absolute', inset: -20, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(245,197,107,0.55), transparent 60%)',
          filter: 'blur(18px)',
          animation: 'lvHaloPulse 3s ease-in-out infinite',
        }} />
        <div style={{
          width: 64, height: 64, borderRadius: '50%',
          background: 'linear-gradient(135deg, #F5C56B, #D69E2E)',
          boxShadow: '0 10px 30px rgba(245,197,107,0.5), inset 0 1px 0 rgba(255,255,255,0.4)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative',
        }}>
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none"
            stroke="white" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12l5 5L20 7"/>
          </svg>
        </div>
      </div>
      <div style={{
        padding: '8px 16px', borderRadius: 10,
        background: 'rgba(245,197,107,0.16)',
        border: '1px solid rgba(245,197,107,0.4)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <div style={{
          width: 8, height: 8, borderRadius: '50%', background: '#F5C56B',
          boxShadow: '0 0 12px #F5C56B',
        }} />
        <span style={{
          fontSize: 11, color: '#F5C56B', fontFamily: 'var(--hl-font-mono)',
          letterSpacing: 1.5, textTransform: 'uppercase', fontWeight: 600,
        }}>Lista para proyección</span>
      </div>
    </div>
  );
}

// ─── Steps definition ────────────────────────────────────────────────────

const TUT_STEPS = [
  {
    Hero: HeroWelcome,
    headline: 'Bienvenido a tu estudio de adoración',
    description: 'Prepara las letras del próximo culto en LaVid Valencia. Te muestro cómo en 30 segundos.',
  },
  {
    Hero: HeroSetlist,
    headline: 'Tu setlist, domingo a domingo',
    description: 'Cada canción que envías aparece aquí, marcada como Lista cuando ya está disponible para proyección.',
  },
  {
    Hero: HeroSearch,
    headline: 'Encuentra cualquier canción',
    description: 'Buscamos letras y acordes en CifraClub y los enriquecemos con género e información del artista.',
  },
  {
    Hero: HeroModal,
    headline: 'Letra, acordes o ambos',
    description: 'Revisa la versión que necesitas — solo letra para proyectar, completo para ensayar, acordes para tu banda.',
  },
  {
    Hero: HeroStatus,
    headline: 'Listo para proyectar',
    description: 'Cuando una canción cambia a candlelight, está disponible en HolyLyrics para todo el equipo de adoración.',
  },
];

// ─── Main component ──────────────────────────────────────────────────────

function TutorialScreen({ onComplete, onSkip }) {
  const [step, setStep] = React.useState(0);
  const [tk, setTk] = React.useState(0);

  const next = () => {
    if (step >= TUT_STEPS.length - 1) {
      onComplete && onComplete();
      return;
    }
    setStep(s => s + 1);
    setTk(k => k + 1);
  };

  const jumpTo = (i) => {
    if (i === step) return;
    setStep(i);
    setTk(k => k + 1);
  };

  const current = TUT_STEPS[step];
  const isLast = step === TUT_STEPS.length - 1;
  const Hero = current.Hero;

  return (
    <div style={{
      height: '100%', position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(180deg, #150A30 0%, #0A0520 100%)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* drift orbs */}
      <div style={{
        position: 'absolute', top: -150, left: -100, width: 380, height: 380,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.32, pointerEvents: 'none',
        background: 'radial-gradient(circle, var(--lavid-violet, #A855F7), transparent 65%)',
        animation: 'hldrift 16s ease-in-out infinite',
      }} />
      <div style={{
        position: 'absolute', bottom: -150, right: -100, width: 360, height: 360,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.22, pointerEvents: 'none',
        background: 'radial-gradient(circle, var(--vesper-deep, #4F1FCB), transparent 65%)',
        animation: 'hldrift 22s ease-in-out infinite reverse',
      }} />

      {/* grain */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.05, pointerEvents: 'none',
        backgroundImage: 'radial-gradient(rgba(255,255,255,0.5) 1px, transparent 1px)',
        backgroundSize: '3px 3px',
      }} />

      {/* skip top-right */}
      <div style={{
        paddingTop: 60, paddingRight: 18,
        display: 'flex', justifyContent: 'flex-end',
        position: 'relative', zIndex: 3,
      }}>
        <button type="button" onClick={onSkip} style={{
          background: 'transparent', border: 'none',
          color: 'rgba(232,220,196,0.6)',
          fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase',
          fontFamily: 'var(--hl-font-mono)', fontWeight: 600,
          cursor: 'pointer', padding: '6px 8px',
        }}>Saltar</button>
      </div>

      {/* hero zone — re-mounts on step change to re-trigger animation.
          Uses `tutHeroIn` (scale + blur, no translate) so flex-centering isn't broken. */}
      <div key={`hero-${tk}`} style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '8px 28px',
        animation: `tutHeroIn 0.6s ${TUT_EASE} both`,
        position: 'relative', zIndex: 2,
      }}>
        <Hero />
      </div>

      {/* headline + description */}
      <div key={`text-${tk}`} style={{
        padding: '0 28px 8px', textAlign: 'center', position: 'relative', zIndex: 2,
      }}>
        <h1 style={{
          margin: 0,
          fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
          fontSize: 26, fontWeight: 400, color: '#fff',
          letterSpacing: -0.8, lineHeight: 1.2,
          animation: `hlfadeUp 0.5s ${TUT_EASE} 0.1s both`,
        }}>{current.headline}</h1>
        <p style={{
          margin: '12px auto 0', maxWidth: 320,
          fontSize: 14, lineHeight: 1.55,
          color: 'rgba(232,220,196,0.65)',
          letterSpacing: -0.1,
          animation: `hlfadeUp 0.5s ${TUT_EASE} 0.2s both`,
        }}>{current.description}</p>
      </div>

      {/* progress dots + CTA */}
      <div style={{
        padding: 'calc(20px) 28px calc(36px + var(--safe-bottom, 16px))',
        position: 'relative', zIndex: 2,
      }}>
        <div style={{
          display: 'flex', gap: 6, justifyContent: 'center', marginBottom: 18,
        }}>
          {TUT_STEPS.map((_, i) => (
            <button
              key={i}
              type="button"
              onClick={() => jumpTo(i)}
              aria-label={`Paso ${i + 1}`}
              style={{
                width: i === step ? 26 : 6, height: 6, borderRadius: 3,
                background: i === step
                  ? 'var(--lavid-violet, #A855F7)'
                  : i < step
                    ? 'rgba(168,85,247,0.5)'
                    : 'rgba(232,220,196,0.18)',
                border: 'none', padding: 0,
                cursor: 'pointer',
                transition: `all 0.32s ${TUT_EASE}`,
              }}
            />
          ))}
        </div>
        <button type="button" onClick={next} style={{
          width: '100%', height: 54, borderRadius: 16, border: 'none',
          background: 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)',
          color: '#fff', fontSize: 16, fontWeight: 600,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
          cursor: 'pointer',
          boxShadow: '0 12px 30px rgba(168,85,247,0.45), inset 0 1px 0 rgba(255,255,255,0.25)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
            background: 'linear-gradient(180deg, rgba(255,255,255,0.18), transparent)',
            pointerEvents: 'none',
          }} />
          <span style={{ position: 'relative' }}>{isLast ? 'Empezar' : 'Continuar'}</span>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { TutorialScreen });
