// Home.jsx — Setlist do culto, premium SwiftUI vibe

const MOCK_SETLIST = [
  { id: 1, title: 'Reckless Love', artist: 'Cory Asbury', status: 'published', section: 'Adoración', key: 'C', duration: '5:38' },
  { id: 2, title: 'Océanos', artist: 'Hillsong UNITED', status: 'published', section: 'Adoración', key: 'D', duration: '8:55' },
  { id: 3, title: 'Que se Abra el Cielo', artist: 'Casa Worship', status: 'pending', section: 'Entrega', key: 'G', duration: '6:12' },
  { id: 4, title: 'Tú Eres Santo', artist: 'Diante do Trono', status: 'draft', section: 'Entrega', key: 'A', duration: '7:04' },
];

function StatusDot({ status }) {
  // Worship-world palette: candlelight (gold) for "ready to project", parchment (muted)
  // for "still being prepared", vinho for errors. Pending stays amber-warm.
  const map = {
    published: { color: '#F5C56B', label: 'Lista', glow: 'rgba(245,197,107,0.55)' },     // candlelight — "the candle is lit"
    pending:   { color: '#FBBF24', label: 'Enviando', glow: 'rgba(251,191,36,0.6)' },
    draft:     { color: '#E8DCC4', label: 'Borrador', glow: 'rgba(232,220,196,0.25)' },  // parchment — "still on the page"
    error:     { color: '#B14A60', label: 'Error', glow: 'rgba(177,74,96,0.5)' },        // vinho
  };
  const s = map[status] || map.draft;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{
        width: 7, height: 7, borderRadius: '50%', background: s.color,
        boxShadow: `0 0 10px ${s.glow}`,
        animation: status === 'pending' ? 'hlbreathe 1.2s ease-in-out infinite' : undefined,
      }} />
      <span style={{
        fontSize: 10, color: 'rgba(232,220,196,0.6)',  /* parchment-muted */
        textTransform: 'uppercase', letterSpacing: 1,
        fontFamily: 'var(--hl-font-mono)', fontWeight: 500,
      }}>{s.label}</span>
    </div>
  );
}

// Progress ring — replaces the 3 stat counters with one focused metric.
// Tells the story "X of N ready" instead of fragmenting into stats.
function ProgressRing({ value, max, size = 56 }) {
  const stroke = 4;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = max > 0 ? value / max : 0;
  const offset = c * (1 - pct);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size/2} cy={size/2} r={r} fill="none"
        stroke="rgba(232,220,196,0.12)" strokeWidth={stroke} />
      <circle cx={size/2} cy={size/2} r={r} fill="none"
        stroke="var(--lavid-violet)" strokeWidth={stroke}
        strokeLinecap="round" strokeDasharray={c} strokeDashoffset={offset}
        style={{ transition: 'stroke-dashoffset 0.6s cubic-bezier(0.22, 1, 0.36, 1)' }}
        transform={`rotate(-90 ${size/2} ${size/2})`} />
    </svg>
  );
}

// Hymnal-index row (shadcn `Table` row pattern, sin cards).
// One song per line, divide-y rules in parchment-muted, columns via grid.
function SongRow({ song, onClick, idx, isLast }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        width: '100%', textAlign: 'left',
        background: hover ? 'rgba(168,85,247,0.06)' : 'transparent',
        border: 'none',
        borderBottom: isLast ? 'none' : '1px solid rgba(232,220,196,0.07)',
        padding: '14px 8px',
        display: 'grid',
        gridTemplateColumns: '28px 1fr auto auto',
        alignItems: 'center',
        columnGap: 14,
        cursor: 'pointer',
        transition: 'background 0.15s ease',
      }}
    >
      {/* № — setlist position, hymnal-style numbering */}
      <span style={{
        fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
        fontSize: 18, fontWeight: 400,
        color: 'rgba(232,220,196,0.6)',
        textAlign: 'center', letterSpacing: -0.3,
      }}>{(idx ?? 0) + 1}</span>

      {/* canción + artista */}
      <div style={{ minWidth: 0 }}>
        <div style={{
          color: '#fff', fontSize: 16, fontWeight: 500,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.25,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          lineHeight: 1.25,
        }}>{song.name || song.title}</div>
        <div style={{
          color: 'rgba(232,220,196,0.5)', fontSize: 12, marginTop: 2,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{song.artist?.name || song.artist}</div>
      </div>

      {/* tono — typeset character, no pill */}
      {song.key ? (
        <span style={{
          fontFamily: 'var(--hl-font-mono)', fontSize: 12,
          color: 'var(--vesper-glow)', fontWeight: 500,
          letterSpacing: 0.4, paddingRight: 10,
          minWidth: 22, textAlign: 'center',
        }}>{song.key}</span>
      ) : <span style={{ minWidth: 22 }} />}

      {/* estado */}
      <StatusDot status={song.status} />
    </button>
  );
}

function HomeScreen({ onAddSong, onSongClick, onProfile, onHistory, songs = MOCK_SETLIST, user }) {
  const grouped = songs.reduce((acc, s) => {
    (acc[s.section] = acc[s.section] || []).push(s);
    return acc;
  }, {});

  return (
    <div style={{
      height: '100%', overflowY: 'auto', overflowX: 'hidden',
      background: 'linear-gradient(180deg, #0E0726 0%, #08051A 50%, #04020E 100%)',
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: -150, right: -100, width: 380, height: 380,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.32, pointerEvents: 'none',
        background: 'radial-gradient(circle, #A855F7, transparent 65%)',
        animation: 'hldrift 16s ease-in-out infinite',
      }} />
      <div style={{
        position: 'absolute', top: '40%', left: -120, width: 320, height: 320,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.22, pointerEvents: 'none',
        background: 'radial-gradient(circle, #4F1FCB, transparent 65%)',
      }} />

      <div style={{ height: 'calc(var(--safe-top, 44px) + 14px)', flexShrink: 0 }} />

      <div className="hl-stagger" style={{ position: 'relative', zIndex: 2, padding: 'calc(20px) 20px calc(100px + var(--safe-bottom, 16px))' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
              <div style={{
                display: 'flex',
                filter: 'drop-shadow(0 0 8px rgba(192,132,252,0.45)) drop-shadow(0 0 18px rgba(168,85,247,0.2))',
              }}>
                <LavidMark size={26} loop strokeWidth={110} />
              </div>
              <div style={{
                fontFamily: 'var(--hl-font-mono)', fontSize: 10,
                color: 'var(--hl-accent-light)', letterSpacing: 2,
                textTransform: 'uppercase', fontWeight: 500,
              }}>Domingo, 26 abr · LaVid Valencia</div>
            </div>
            <div style={{
              fontFamily: 'var(--hl-font-display)',
              fontSize: 40, fontWeight: 300, color: '#fff',
              letterSpacing: -1.4, marginTop: 8, lineHeight: 1.0,
            }}>Culto de la <span style={{ fontStyle: 'italic', fontWeight: 400 }}>mañana</span></div>
            <div style={{
              fontSize: 14, color: 'rgba(255,255,255,0.55)', marginTop: 6, letterSpacing: -0.2,
            }}>Hola, {(user?.displayName || 'Lucas').split(' ')[0]} · {songs.length} canciones</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button type="button" aria-label="Historial" onClick={onHistory} style={{
            width: 40, height: 40, borderRadius: '50%',
            background: 'rgba(255,255,255,0.06)',
            backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            border: '1px solid rgba(255,255,255,0.08)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', padding: 0,
            color: 'rgba(255,255,255,0.75)',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="9"/>
              <polyline points="12 7 12 12 15 14"/>
            </svg>
          </button>
          <button type="button" aria-label="Abrir perfil" onClick={onProfile} style={{
            width: 44, height: 44, borderRadius: '50%',
            background: 'rgba(255,255,255,0.06)',
            backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            border: '1px solid rgba(255,255,255,0.08)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', padding: 0,
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: user?.avatarUrl
                ? `url(${user.avatarUrl}) center/cover`
                : 'linear-gradient(135deg, #B45EFF, #4F1FCB)',
              color: 'white', fontSize: 13, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.3)',
            }}>{!user?.avatarUrl && (user?.displayName || 'Lucas').split(' ').map(s => s[0]).slice(0, 1).join('').toUpperCase()}</div>
          </button>
          </div>
        </div>

        {/* Progress ring + sub-counts: replaces 3-counter row.
            Tells the story "X de N listas para el culto" in one glance,
            keeps secondary counts in mono micro-text. */}
        <div style={{
          marginTop: 24, display: 'flex', alignItems: 'center', gap: 18,
          padding: '14px 16px',
          background: 'rgba(255,255,255,0.025)',
          border: '1px solid rgba(232,220,196,0.08)',
          borderRadius: 16,
        }}>
          <ProgressRing
            value={songs.filter(s => s.status === 'published').length}
            max={songs.length}
            size={56}
          />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 22, fontWeight: 400,
              color: '#fff', letterSpacing: -0.5, lineHeight: 1.1,
            }}>
              <span style={{ fontStyle: 'italic' }}>{songs.filter(s => s.status === 'published').length}</span>
              <span style={{ color: 'var(--parchment-muted)' }}>{` de ${songs.length} listas`}</span>
            </div>
            <div style={{
              marginTop: 4, fontSize: 10,
              color: 'rgba(232,220,196,0.55)',
              fontFamily: 'var(--hl-font-mono)', letterSpacing: 1, textTransform: 'uppercase',
              fontWeight: 500, display: 'flex', gap: 8, flexWrap: 'wrap',
            }}>
              {songs.filter(s => s.status === 'pending').length > 0 && (
                <span>{songs.filter(s => s.status === 'pending').length} enviando</span>
              )}
              {songs.filter(s => s.status === 'draft').length > 0 && (
                <span style={{ opacity: 0.7 }}>· {songs.filter(s => s.status === 'draft').length} en borrador</span>
              )}
              {songs.filter(s => s.status === 'pending').length === 0 &&
               songs.filter(s => s.status === 'draft').length === 0 && (
                <span>todo listo para domingo</span>
              )}
            </div>
          </div>
          {/* Ghost CTA: small + button for "añadir canción".
              Demoted from full-width gradient — adding is secondary to reviewing. */}
          <button
            onClick={onAddSong}
            type="button"
            aria-label="Añadir canción al setlist"
            style={{
              width: 38, height: 38, borderRadius: 12, flexShrink: 0,
              background: 'transparent',
              border: '1px solid rgba(192,132,252,0.35)',
              color: 'var(--vesper-glow)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', padding: 0,
              transition: 'all 0.18s ease',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'rgba(168,85,247,0.1)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M7 2v10M2 7h10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        {Object.entries(grouped).map(([section, list]) => (
          <div key={section} style={{ marginTop: 28 }}>
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              marginBottom: 10, padding: '0 4px',
            }}>
              <div style={{
                fontFamily: 'var(--hl-font-mono)', fontSize: 10,
                color: 'rgba(255,255,255,0.5)', letterSpacing: 2,
                textTransform: 'uppercase', fontWeight: 600,
              }}>{section}</div>
              <div style={{
                fontFamily: 'var(--hl-font-mono)', fontSize: 10,
                color: 'rgba(255,255,255,0.35)',
              }}>{list.length}</div>
            </div>
            <div style={{
              borderTop: '1px solid rgba(232,220,196,0.1)',
              borderRadius: 0,
            }}>
              {list.map((s, i) => (
                <SongRow
                  key={s.id}
                  song={s}
                  idx={songs.indexOf(s)}
                  isLast={i === list.length - 1}
                  onClick={() => onSongClick && onSongClick(s)}
                />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, MOCK_SETLIST, StatusDot });
